diff --git a/src/net/micode/notes/gtask/data/MetaData.java b/src/net/micode/notes/gtask/data/MetaData.java new file mode 100644 index 0000000..bc07419 --- /dev/null +++ b/src/net/micode/notes/gtask/data/MetaData.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data;//包名声明:路径"net.micode.notes.gtask.data",文件中定义的类和接口都归属于这个包 + +import org.json.JSONException; //引入"org.json.JSONException"类,用于处理JSON格式数据的异常 +import org.json.JSONObject; //表示和操作JSON对象 + +import android.database.Cursor;//导入Android平台的数据库Cursor类用于从数据库中检索数据记录并对结果进行管理和遍历。 +import android.util.Log;//引入工具类Log来存放一些通用的、与业务逻辑无关的工具方法 +import net.micode.notes.tool.GTaskStringUtils;//导入 GTaskStringUtils工具类 + +public class MetaData extends Task { + private final static String TAG = MetaData.class.getSimpleName(); // 用于在日志中标识当前类的名称 + + private String mRelatedGid = null; + + public void setMeta(String gid, JSONObject metaInfo) { + try { + metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); + } catch (JSONException e) { // 如果出现 JSONException 异常,则会捕获并记录日志 + Log.e(TAG, "failed to put related gid"); + } + // try-catch 块中,将键值对 (GTaskStringUtils.META_HEAD_GTASK_ID, gid) 添加到传入的 metaInfo + // JSON 对象中。 + + setNotes(metaInfo.toString()); + setName(GTaskStringUtils.META_NOTE_NAME); + } + + public String getRelatedGid() { + return mRelatedGid; + } + + @Override + // 是一个Java注解,用于告诉编译器该方法是重写父类或接口中的方法。 + public boolean isWorthSaving() { + return getNotes() != null; + } + + @Override + public void setContentByRemoteJSON(JSONObject js) { + super.setContentByRemoteJSON(js); // 调用父类的方法,传入参数js + if (getNotes() != null) { + String notes = getNotes().trim(); // 获取notes并去除首尾空格 + try { + JSONObject metaInfo = new JSONObject(notes); // 转化为JSONObject对象 + mRelatedGid = metaInfo.optString(GTaskStringUtils.META_HEAD_GTASK_ID, null); // 提取特征字段 + } catch (JSONException e) { + Log.w(TAG, "failed to get related gid", e); + mRelatedGid = null; + } + } + } + + // 以下三段表示不应该被调用,如果调用了,抛出了一个IllegalAccessError异常,并提供了错误消息 + + @Override + public void setContentByLocalJSON(JSONObject js) { + // this function should not be called + throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); + } + + @Override + public JSONObject getLocalJSONFromContent() { + throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); + } + + @Override + public int getSyncAction(Cursor c) { + throw new IllegalAccessError("MetaData:getSyncAction should not be called"); + } + +} diff --git a/src/net/micode/notes/gtask/data/Node.java b/src/net/micode/notes/gtask/data/Node.java new file mode 100644 index 0000000..3f79681 --- /dev/null +++ b/src/net/micode/notes/gtask/data/Node.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import org.json.JSONObject; + +import android.database.Cursor; + +public abstract class Node { + public static final int SYNC_ACTION_NONE = 0;// 本地和云端都无可更新内容(即本地和云端内容一致) + + public static final int SYNC_ACTION_ADD_REMOTE = 1;// 在远程云端增加内容 + + public static final int SYNC_ACTION_ADD_LOCAL = 2;// 在本地增加内容 + + public static final int SYNC_ACTION_DEL_REMOTE = 3;// 在云端删除内容 + + public static final int SYNC_ACTION_DEL_LOCAL = 4;// 在本地删除内容 + + public static final int SYNC_ACTION_UPDATE_REMOTE = 5;// 本地上传云端 + + public static final int SYNC_ACTION_UPDATE_LOCAL = 6;// 云端更新本地 + + public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;// 同步出现冲突 + + public static final int SYNC_ACTION_ERROR = 8;// 同步出现错误 + + // 定义了Node类中的私有字段 + private String mGid; // 唯一标识符 + + private String mName; // 名称 + + private long mLastModified; // 最后一次修改时间 + + private boolean mDeleted; // 是否删除 + + public Node() { + mGid = null; + mName = ""; + mLastModified = 0; + mDeleted = false; + }// 初始化 + + public abstract JSONObject getCreateAction(int actionId); // 根据给定的 actionId 返回一个 JSON 对象,表示创建操作 + + public abstract JSONObject getUpdateAction(int actionId); // 根据给定的 actionId 返回一个 JSON 对象,表示更新操作 + + public abstract void setContentByRemoteJSON(JSONObject js); // 根据远程的 JSON 对象设置内容 + + public abstract void setContentByLocalJSON(JSONObject js); // 根据本地的 JSON 对象设置内容 + + public abstract JSONObject getLocalJSONFromContent(); // 返回一个 JSON 对象,表示从当前内容中获取本地 JSON 数据 + + public abstract int getSyncAction(Cursor c); // 根据给定的 Cursor 返回一个 JSON 对象,表示同步操作 + + // 设置相关信息 + public void setGid(String gid) { + this.mGid = gid; + } + + public void setName(String name) { + this.mName = name; + } + + public void setLastModified(long lastModified) { + this.mLastModified = lastModified; + } + + public void setDeleted(boolean deleted) { + this.mDeleted = deleted; + } + + // 获取相关信息 + public String getGid() { + return this.mGid; + } + + public String getName() { + return this.mName; + } + + public long getLastModified() { + return this.mLastModified; + } + + public boolean getDeleted() { + return this.mDeleted; + } + +} diff --git a/src/net/micode/notes/gtask/data/SqlData.java b/src/net/micode/notes/gtask/data/SqlData.java new file mode 100644 index 0000000..a126b6e --- /dev/null +++ b/src/net/micode/notes/gtask/data/SqlData.java @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import java.util.Objects; +import java.util.function.Function; + +import javax.naming.Context; + +import org.json.JSONException; +import org.json.JSONObject; + +import android.content.ContentResolver; //应用程序需要访问其他应用的数据或者系统提供的数据时,就会使用ContentResolver来进行数据访问操作 +import android.content.ContentUris; +import android.content.ContentValues; +import android.database.Cursor; +import android.net.Uri; +import android.util.Log; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE; +import net.micode.notes.gtask.exception.ActionFailureException; + +//数据库中基本数据,方法包括读取数据、获取数据库中数据、提交数据到数据库 + +public class SqlData { + private static final String TAG = SqlData.class.getSimpleName(); // 得到类的简写名称存入字符串TAG中 + + private static final int INVALID_ID = -99999; + + public static final String[] PROJECTION_DATA = new String[] { + DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, + DataColumns.DATA3 + // DataColumns.ID:表示查询结果中每个数据行的唯一标识符。 + // DataColumns.MIME_TYPE:表示查询结果中每个数据行的MIME类型。 + // DataColumns.CONTENT:表示查询结果中每个数据行的内容。 标识不同的数据列 + // DataColumns.DATA1:表示查询结果中每个数据行的第一个数据项。 + // DataColumns.DATA3:表示查询结果中每个数据行的第三个数据项。 + }; + + public static final int DATA_ID_COLUMN = 0; + + public static final int DATA_MIME_TYPE_COLUMN = 1; + + public static final int DATA_CONTENT_COLUMN = 2; + + public static final int DATA_CONTENT_DATA_1_COLUMN = 3; + + public static final int DATA_CONTENT_DATA_3_COLUMN = 4; + // 每个数据行中各个信息的位置 + + private ContentResolver mContentResolver; + + private boolean mIsCreate; + + private long mDataId; + + private String mDataMimeType; + + private String mDataContent; + + private long mDataContentData1; + + private String mDataContentData3; + + private ContentValues mDiffDataValues; + + public SqlData(Context context) { + mContentResolver = context.getContentResolver(); + mIsCreate = true; + mDataId = INVALID_ID; + mDataMimeType = DataConstants.NOTE; + mDataContent = ""; + mDataContentData1 = 0; + mDataContentData3 = ""; + mDiffDataValues = new ContentValues(); + } // 初始化SqlData对象的字段和属性 + + public SqlData(Context context, Cursor c) { + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(c); + mDiffDataValues = new ContentValues(); + } // 传入c,初始化数据 + + private void loadFromCursor(Cursor c) { + mDataId = c.getLong(DATA_ID_COLUMN); + mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); + mDataContent = c.getString(DATA_CONTENT_COLUMN); + mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); + mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); + } // 从传入的 Cursor 对象中加载数据并设置给类中的字段,具体来说,根据 Cursor 中的列索引,将特定列的值提取出来 + + public void setContent(JSONObject js) throws JSONException { + setDataValue(js, DataColumns.ID, mDataId, Long::parseLong); + setDataValue(js, DataColumns.MIME_TYPE, mDataMimeType, Function.identity()); + setDataValue(js, DataColumns.CONTENT, mDataContent, Function.identity()); + setDataValue(js, DataColumns.DATA1, mDataContentData1, Long::parseLong); + setDataValue(js, DataColumns.DATA3, mDataContentData3, Function.identity()); + } + + private void setDataValue(JSONObject jsonObject, String key, T currentValue, Function parser) + throws JSONException { + T newValue = jsonObject.has(key) ? parser.apply(jsonObject.getString(key)) : null; + if (mIsCreate || !Objects.equals(currentValue, newValue)) { + mDiffDataValues.put(key, newValue); + } + setFieldValue(key, newValue); + } + + private void setFieldValue(String key, Object value) { + switch (key) { + case DataColumns.ID: + mDataId = (Long) value; + break; + case DataColumns.MIME_TYPE: + mDataMimeType = (String) value; + break; + case DataColumns.CONTENT: + mDataContent = (String) value; + break; + case DataColumns.DATA1: + mDataContentData1 = (Long) value; + break; + case DataColumns.DATA3: + mDataContentData3 = (String) value; + break; + } + } + + public JSONObject getContent() throws JSONException { // 获取对象的内容并返回一个 JSON格式的对象。 + if (mIsCreate) { + Log.e(TAG, "it seems that we haven't created this in database yet"); + return null; + } + JSONObject js = new JSONObject(); + js.put(DataColumns.ID, mDataId); + js.put(DataColumns.MIME_TYPE, mDataMimeType); + js.put(DataColumns.CONTENT, mDataContent); + js.put(DataColumns.DATA1, mDataContentData1); + js.put(DataColumns.DATA3, mDataContentData3); + return js; + // 首先判断变量 mIsCreate 的值,如果为 true,表示当前对象还未在数据库中创建,则记录错误日志并返回 null。 + // 如果对象在数据库中已经创建,则创建一个新的 JSONObject 对象 js。 + // 将对象中的数据以键值对的形式存储到 JSON 对象 js 中,键包括 DataColumns.ID等,对应的值分别为对象中的 mDataId等 + // 最后返回构建好的 JSON 对象 js + } + + public void commit(long noteId, boolean validateVersion, long version) { + if (mIsCreate) { // 如果是创建操作 + // 判断是否需要移除无效的ID + if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { + mDiffDataValues.remove(DataColumns.ID); + } + // 将笔记ID放入差异数据值中 + mDiffDataValues.put(DataColumns.NOTE_ID, noteId); + // 插入数据并获取新的数据ID + Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); + try { + mDataId = Long.parseLong(uri.getLastPathSegment()); + } catch (NumberFormatException e) { + Log.e(TAG, "Get note id error: " + e.toString()); + throw new ActionFailureException("Failed to create note"); + } + } else { // 如果不是创建操作 + // 如果有差异数据值需要更新 + if (!mDiffDataValues.isEmpty()) { + int result = 0; + // 根据是否需要验证版本号决定更新方式 + if (!validateVersion) { + result = mContentResolver.update(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); + } else { + // 使用版本号验证更新数据 + result = mContentResolver.update(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, + NoteColumns.ID + " IN (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.ID + "=? AND " + NoteColumns.VERSION + "=? )", + new String[] { String.valueOf(noteId), String.valueOf(version) }); + } + // 如果没有更新数据,则打印警告信息 + if (result == 0) { + Log.w(TAG, "No data update. Perhaps the user has updated the note while syncing."); + } + } + } + + // 清空差异数据值并标记不再是创建操作 + mDiffDataValues.clear(); + mIsCreate = false; + } + + public long getId() { + return mDataId; + } +} diff --git a/src/net/micode/notes/gtask/data/SqlNote.java b/src/net/micode/notes/gtask/data/SqlNote.java new file mode 100644 index 0000000..b631785 --- /dev/null +++ b/src/net/micode/notes/gtask/data/SqlNote.java @@ -0,0 +1,516 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.appwidget.AppWidgetManager; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.tool.GTaskStringUtils; +import net.micode.notes.tool.ResourceParser; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + +//定义一个类,类名为SqlNote,作用:处理便签数据 +public class SqlNote { + //定义一个字符串,表示类名 + private static final String TAG = SqlNote.class.getSimpleName(); + //定义一个整型变量,表示无效ID + private static final int INVALID_ID = -99999; + //定义一个字符串数组,表示便签的列名 + public static final String[] PROJECTION_NOTE = new String[] { + NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, + NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, + NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE, + NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID, + NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID, + NoteColumns.VERSION + }; + //定义一个整型变量,表示ID列 + public static final int ID_COLUMN = 0; + //定义一个整型变量,表示提醒日期列 + public static final int ALERTED_DATE_COLUMN = 1; + // 定义一个整型变量,表示背景颜色ID列 + public static final int BG_COLOR_ID_COLUMN = 2; + //定义一个整型变量,表示创建日期列 + public static final int CREATED_DATE_COLUMN = 3; + //定义一个整型变量,表示是否有附件列 + public static final int HAS_ATTACHMENT_COLUMN = 4; + //定义一个整型变量,表示修改日期列 + public static final int MODIFIED_DATE_COLUMN = 5; + //定义一个整型变量,表示便签数量列 + public static final int NOTES_COUNT_COLUMN = 6; + //定义一个整型变量,表示父ID列 + public static final int PARENT_ID_COLUMN = 7; + //定义一个整型变量,表示摘要列 + public static final int SNIPPET_COLUMN = 8; + //定义一个整型变量,表示类型列 + public static final int TYPE_COLUMN = 9; + //定义一个整型变量,表示小部件ID列 + public static final int WIDGET_ID_COLUMN = 10; + //定义一个整型变量,表示小部件类型列 + public static final int WIDGET_TYPE_COLUMN = 11; + //定义一个整型变量,表示同步ID列 + public static final int SYNC_ID_COLUMN = 12; + //定义一个整型变量,表示本地修改列 + public static final int LOCAL_MODIFIED_COLUMN = 13; + //定义一个整型变量,表示原始父ID列 + public static final int ORIGIN_PARENT_ID_COLUMN = 14; + //定义一个整型变量,表示GTask ID列 + public static final int GTASK_ID_COLUMN = 15; + //定义一个整型变量,表示版本列 + public static final int VERSION_COLUMN = 16; + //定义一个上下文对象 + private Context mContext; + //定义一个内容解析器对象 + private ContentResolver mContentResolver; + //定义一个布尔型变量,表示是否创建 + private boolean mIsCreate; + + private long mId; + + private long mAlertDate; + + private int mBgColorId; + + private long mCreatedDate; + + private int mHasAttachment; + + private long mModifiedDate; + + private long mParentId; + + private String mSnippet; + + private int mType; + + private int mWidgetId; + + private int mWidgetType; + + private long mOriginParent; + + private long mVersion; + + private ContentValues mDiffNoteValues; + + private ArrayList mDataList; + //定义一个构造函数,参数为上下文对象 作用:初始化便签数据 + public SqlNote(Context context) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = true; + mId = INVALID_ID; + mAlertDate = 0; + mBgColorId = ResourceParser.getDefaultBgId(context); + mCreatedDate = System.currentTimeMillis(); + mHasAttachment = 0; + mModifiedDate = System.currentTimeMillis(); + mParentId = 0; + mSnippet = ""; + mType = Notes.TYPE_NOTE; + mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; + mWidgetType = Notes.TYPE_WIDGET_INVALIDE; + mOriginParent = 0; + mVersion = 0; + mDiffNoteValues = new ContentValues(); + mDataList = new ArrayList(); + } + //定义一个构造函数,参数为上下文对象和游标对象 作用:初始化便签数据 + public SqlNote(Context context, Cursor c) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(c); + mDataList = new ArrayList(); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + mDiffNoteValues = new ContentValues(); + } + //定义一个构造函数,参数为上下文对象和ID 作用:初始化便签数据 + public SqlNote(Context context, long id) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(id); + mDataList = new ArrayList(); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + mDiffNoteValues = new ContentValues(); + + } + //定义一个方法,参数为JSONObject对象,返回值为布尔型 作用:设置便签内容 + private void loadFromCursor(long id) { + Cursor c = null; + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", + new String[] { + String.valueOf(id) + }, null); + if (c != null) { + c.moveToNext(); + loadFromCursor(c); + } else { + Log.w(TAG, "loadFromCursor: cursor = null"); + } + } finally { + if (c != null) + c.close(); + } + } + //定义一个方法,参数为游标对象 作用:从游标中加载数据 + private void loadFromCursor(Cursor c) { + mId = c.getLong(ID_COLUMN); + mAlertDate = c.getLong(ALERTED_DATE_COLUMN); + mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); + mCreatedDate = c.getLong(CREATED_DATE_COLUMN); + mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); + mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); + mParentId = c.getLong(PARENT_ID_COLUMN); + mSnippet = c.getString(SNIPPET_COLUMN); + mType = c.getInt(TYPE_COLUMN); + mWidgetId = c.getInt(WIDGET_ID_COLUMN); + mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); + mVersion = c.getLong(VERSION_COLUMN); + } + //定义一个方法,参数为游标对象 作用:从游标中加载数据 + private void loadDataContent() { + Cursor c = null; + mDataList.clear(); + try { + //查询数据表 + c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, + "(note_id=?)", new String[] { + String.valueOf(mId) + }, null); + if (c != null) {//如果游标不为空,则遍历游标 + if (c.getCount() == 0) { + Log.w(TAG, "it seems that the note has not data"); + return; + }//如果游标的数量为0,则打印日志信息 + while (c.moveToNext()) { + SqlData data = new SqlData(mContext, c); + mDataList.add(data); + } + } else { //如果游标为空,则打印日志信息 + Log.w(TAG, "loadDataContent: cursor = null"); + } + } finally {//关闭游标 + if (c != null) + c.close(); + } + } + //定义一个方法,参数为JSONObject对象,返回值为布尔型 作用:设置内容 + public boolean setContent(JSONObject js) { + try {//捕获异常 + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { + Log.w(TAG, "cannot set system folder"); + } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { + //对于文件夹,我们只能更新 snnipet 并键入 + String snippet = note.has(NoteColumns.SNIPPET) ? note + .getString(NoteColumns.SNIPPET) : ""; + if (mIsCreate || !mSnippet.equals(snippet)) { + mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); + } + mSnippet = snippet; + //对于文件夹,我们只能更新类型 + int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) + : Notes.TYPE_NOTE; + //如果是创建或者类型不同,则将类型放入差异便签值中 + if (mIsCreate || mType != type) { + mDiffNoteValues.put(NoteColumns.TYPE, type); + } + mType = type; + //对于文件夹,我们只能更新小部件类型 + } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; + if (mIsCreate || mId != id) { + mDiffNoteValues.put(NoteColumns.ID, id); + } + mId = id; + //如果是创建或者提醒日期不同,则将提醒日期放入差异便签值中 + long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note + .getLong(NoteColumns.ALERTED_DATE) : 0; + if (mIsCreate || mAlertDate != alertDate) { + mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); + } + mAlertDate = alertDate; + //如果是创建或者背景颜色ID不同,则将背景颜色ID放入差异便签值中 + int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note + .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); + if (mIsCreate || mBgColorId != bgColorId) { + mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); + } + mBgColorId = bgColorId; + //如果是创建或者创建日期不同,则将创建日期放入差异便签值中 + long createDate = note.has(NoteColumns.CREATED_DATE) ? note + .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); + if (mIsCreate || mCreatedDate != createDate) {//如果是创建或者创建日期不同,则将创建日期放入差异便签值中 + mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); + } + mCreatedDate = createDate; + //如果是创建或者是否有附件不同,则将是否有附件放入差异便签值中 + int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note + .getInt(NoteColumns.HAS_ATTACHMENT) : 0; + if (mIsCreate || mHasAttachment != hasAttachment) { + mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); + } + mHasAttachment = hasAttachment; + //如果是创建或者修改日期不同,则将修改日期放入差异便签值中 + long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note + .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); + if (mIsCreate || mModifiedDate != modifiedDate) { + mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); + } + mModifiedDate = modifiedDate; + //如果是创建或者父ID不同,则将父ID放入差异便签值中 + long parentId = note.has(NoteColumns.PARENT_ID) ? note + .getLong(NoteColumns.PARENT_ID) : 0; + if (mIsCreate || mParentId != parentId) { + mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); + } + mParentId = parentId; + //如果是创建或者摘要不同,则将摘要放入差异便签值中 + String snippet = note.has(NoteColumns.SNIPPET) ? note + .getString(NoteColumns.SNIPPET) : ""; + if (mIsCreate || !mSnippet.equals(snippet)) { + mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); + } + mSnippet = snippet; + //如果是创建或者类型不同,则将类型放入差异便签值中 + int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) + : Notes.TYPE_NOTE; + if (mIsCreate || mType != type) { + mDiffNoteValues.put(NoteColumns.TYPE, type); + } + mType = type; + //如果是创建或者小部件ID不同,则将小部件ID放入差异便签值中 + int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) + : AppWidgetManager.INVALID_APPWIDGET_ID; + if (mIsCreate || mWidgetId != widgetId) { + mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); + } + mWidgetId = widgetId; + //如果是创建或者小部件类型不同,则将小部件类型放入差异便签值中 + int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note + .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; + if (mIsCreate || mWidgetType != widgetType) { + mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); + } + mWidgetType = widgetType; + + long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note + .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; + if (mIsCreate || mOriginParent != originParent) { + mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); + } + mOriginParent = originParent; + //如果是创建或者GTask ID不同,则将GTask ID放入差异便签值中,否则将GTask ID放入差异便签值中 + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + SqlData sqlData = null; + if (data.has(DataColumns.ID)) { + long dataId = data.getLong(DataColumns.ID); + for (SqlData temp : mDataList) { + if (dataId == temp.getId()) { + sqlData = temp; + } + } + } + //如果sqlData为空,则创建一个新的SqlData对象 + if (sqlData == null) { + sqlData = new SqlData(mContext); + mDataList.add(sqlData); + } + + sqlData.setContent(data); + } + } + //捕获异常,打印异常信息作用:设置内容 + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return false; + } + return true; + } + //定义一个方法,返回JSONObject对象 作用:获取内容 + public JSONObject getContent() { + try { + JSONObject js = new JSONObject(); + //如果是创建,则打印日志信息 + if (mIsCreate) { + Log.e(TAG, "it seems that we haven't created this in database yet"); + return null; + } + //创建一个JSONObject对象 + JSONObject note = new JSONObject(); + if (mType == Notes.TYPE_NOTE) { + note.put(NoteColumns.ID, mId); + note.put(NoteColumns.ALERTED_DATE, mAlertDate); + note.put(NoteColumns.BG_COLOR_ID, mBgColorId); + note.put(NoteColumns.CREATED_DATE, mCreatedDate); + note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); + note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); + note.put(NoteColumns.PARENT_ID, mParentId); + note.put(NoteColumns.SNIPPET, mSnippet); + note.put(NoteColumns.TYPE, mType); + note.put(NoteColumns.WIDGET_ID, mWidgetId); + note.put(NoteColumns.WIDGET_TYPE, mWidgetType); + note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); + js.put(GTaskStringUtils.META_HEAD_NOTE, note); + + JSONArray dataArray = new JSONArray(); + for (SqlData sqlData : mDataList) { + JSONObject data = sqlData.getContent(); + if (data != null) { + dataArray.put(data); + } + } + js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); + //如果是文件夹,则打印日志信息 + } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { + note.put(NoteColumns.ID, mId); + note.put(NoteColumns.TYPE, mType); + note.put(NoteColumns.SNIPPET, mSnippet); + js.put(GTaskStringUtils.META_HEAD_NOTE, note); + } + + return js; + //捕获异常,打印异常信息 + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + return null; + } + //定义一个方法,返回JSONObject对象 作用:获取内容 + public void setParentId(long id) { + mParentId = id; + mDiffNoteValues.put(NoteColumns.PARENT_ID, id); + } + //定义一个方法,返回JSONObject对象 作用:获取内容 + public void setGtaskId(String gid) { + mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); + } + //定义一个方法,返回JSONObject对象 作用:获取内容 + public void setSyncId(long syncId) { + mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); + } + //定义一个方法,返回JSONObject对象 作用:获取内容 + public void resetLocalModified() { + mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); + } + + public long getId() { + return mId; + } + + public long getParentId() { + return mParentId; + } + + public String getSnippet() { + return mSnippet; + } + + public boolean isNoteType() { + return mType == Notes.TYPE_NOTE; + } + //定义一个方法,返回布尔型 作用:是否是文件夹类型 + public void commit(boolean validateVersion) { + if (mIsCreate) {//如果是创建,则打印日志信息 + if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { + mDiffNoteValues.remove(NoteColumns.ID); + } + //如果是创建,则插入数据 + Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); + try {//捕获异常,打印异常信息 + mId = Long.valueOf(uri.getPathSegments().get(1)); + } catch (NumberFormatException e) { + Log.e(TAG, "Get note id error :" + e.toString()); + throw new ActionFailureException("create note failed"); + } + if (mId == 0) { + throw new IllegalStateException("Create thread id failed"); + } + //如果是便签类型,则插入数据 + if (mType == Notes.TYPE_NOTE) { + for (SqlData sqlData : mDataList) { + sqlData.commit(mId, false, -1); + } + } + //如果是文件夹类型,则打印日志信息 + } else { + if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { + Log.e(TAG, "No such note"); + throw new IllegalStateException("Try to update note with invalid id"); + } + //如果是便签类型,则更新数据 + if (mDiffNoteValues.size() > 0) { + mVersion ++; + int result = 0; + if (!validateVersion) { + result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" + + NoteColumns.ID + "=?)", new String[] { + String.valueOf(mId) + }); + } else { + //如果是便签类型,则更新数据 + result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" + + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", + new String[] { + String.valueOf(mId), String.valueOf(mVersion) + }); + } + //如果结果为0,则打印日志信息 + if (result == 0) { + Log.w(TAG, "there is no update. maybe user updates note when syncing"); + } + } + //如果是便签类型,则更新数据 + if (mType == Notes.TYPE_NOTE) { + for (SqlData sqlData : mDataList) { + sqlData.commit(mId, validateVersion, mVersion); + } + } + } + //如果是便签类型,则打印日志信息 + // refresh local info + loadFromCursor(mId); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + //如果是便签类型,则清空差异便签值 + mDiffNoteValues.clear(); + mIsCreate = false; + } +} diff --git a/src/net/micode/notes/gtask/data/Task.java b/src/net/micode/notes/gtask/data/Task.java new file mode 100644 index 0000000..07a3638 --- /dev/null +++ b/src/net/micode/notes/gtask/data/Task.java @@ -0,0 +1,368 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +//任务类,继承自Node类 +public class Task extends Node { + //定义一个字符串,表示任务类的简单名称 + private static final String TAG = Task.class.getSimpleName(); + //定义一个布尔型变量,表示任务是否已完成 + private boolean mCompleted; + + private String mNotes; + + private JSONObject mMetaInfo; + + private Task mPriorSibling; + + private TaskList mParent; + //定义一个整型变量,表示同步操作为更新本地 + public Task() { + super(); + mCompleted = false; + mNotes = null; + mPriorSibling = null; + mParent = null; + mMetaInfo = null; + } + //定义一个整型变量,表示同步操作为更新本地 + public JSONObject getCreateAction(int actionId) { + JSONObject js = new JSONObject(); + // try catch语句,捕获异常 + try { + // action_type + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); + // + // action_id + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // index + js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); + + // entity_delta + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); + entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, + GTaskStringUtils.GTASK_JSON_TYPE_TASK); + // notes,作用:获取任务的备注 + if (getNotes() != null) { + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); + } + // deleted,作用:获取任务是否已删除 + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + // parent_id,作用:获取任务的父ID + js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); + + // dest_parent_type + js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, + GTaskStringUtils.GTASK_JSON_TYPE_GROUP); + + // list_id + js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); + + // prior_sibling_id + if (mPriorSibling != null) { + js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate task-create jsonobject"); + } + + return js; + } + //定义一个整型变量,表示同步操作为更新本地 + public JSONObject getUpdateAction(int actionId) { + JSONObject js = new JSONObject(); + // try catch语句,捕获异常 + try { + // action_type + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); + + // action_id + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // id + js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); + + // entity_delta + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + // notes,作用:获取任务的备注 + if (getNotes() != null) { + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); + } + entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + //捕获异常 + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate task-update jsonobject"); + } + + return js; + } + //定义一个整型变量,表示同步操作为更新本地 + public void setContentByRemoteJSON(JSONObject js) { + if (js != null) { + try { + // 获取任务的ID + if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { + setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); + } + + // last_modified + // 获取任务的最后修改时间 + if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { + setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); + } + + // name + // 获取任务的名称 + if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { + setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); + } + + // notes + // 获取任务的备注 + if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { + setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); + } + + // deleted + // 获取任务是否已删除 + if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { + setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); + } + + // completed + // 获取任务是否已完成 + if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { + setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to get task content from jsonobject"); + } + } + } + //定义一个整型变量,表示同步操作为更新本地 + public void setContentByLocalJSON(JSONObject js) { + if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) + || !js.has(GTaskStringUtils.META_HEAD_DATA)) { + Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); + } + // try catch语句,捕获异常 + try { + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + + if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { + Log.e(TAG, "invalid type"); + return; + } + + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { + setName(data.getString(DataColumns.CONTENT)); + break; + } + } + //捕获异常 + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to get task content from jsonobject"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + } + //定义一个整型变量,表示同步操作为更新本地 + public JSONObject getLocalJSONFromContent() { + String name = getName(); + try { + if (mMetaInfo == null) { + // new task created from web + if (name == null) { + Log.w(TAG, "the note seems to be an empty one"); + return null; + } + //创建一个JSONObject对象 + JSONObject js = new JSONObject(); + JSONObject note = new JSONObject(); + JSONArray dataArray = new JSONArray(); + JSONObject data = new JSONObject(); + data.put(DataColumns.CONTENT, name); + dataArray.put(data); + js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + js.put(GTaskStringUtils.META_HEAD_NOTE, note); + return js; + } else { + + 同步任务 + JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + //遍历JSONArray数组,获取数据 + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { + data.put(DataColumns.CONTENT, getName()); + break; + } + } + //创建一个JSONObject对象 + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + return mMetaInfo; + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return null; + } + } + //定义一个整型变量,表示同步操作为更新本地 + public void setMetaInfo(MetaData metaData) { + // try catch语句,捕获异常 + if (metaData != null && metaData.getNotes() != null) { + try { + mMetaInfo = new JSONObject(metaData.getNotes()); + } catch (JSONException e) { + Log.w(TAG, e.toString()); + mMetaInfo = null; + } + } + } + //定义一个整型变量,表示同步操作为更新本地 + public int getSyncAction(Cursor c) { + try { + JSONObject noteInfo = null; + //判断JSONObject对象是否为空 + if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { + noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + } + //判断Cursor对象是否为空 + if (noteInfo == null) { + Log.w(TAG, "it seems that note meta has been deleted"); + return SYNC_ACTION_UPDATE_REMOTE; + } + //判断JSONObject对象是否包含指定的键 + if (!noteInfo.has(NoteColumns.ID)) { + Log.w(TAG, "remote note id seems to be deleted"); + return SYNC_ACTION_UPDATE_LOCAL; + } + //判断Cursor对象是否包含指定的列 + // validate the note id now + if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { + Log.w(TAG, "note id doesn't match"); + return SYNC_ACTION_UPDATE_LOCAL; + } + //判断Cursor对象是否包含指定的列 + if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { + // there is no local update + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // no update both side + return SYNC_ACTION_NONE; + } else { + // apply remote to local + return SYNC_ACTION_UPDATE_LOCAL; + } + // Cursor对象是否包含指定的列 + } else { + // validate gtask id + if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { + Log.e(TAG, "gtask id doesn't match"); + return SYNC_ACTION_ERROR; + } + // Cursor对象是否包含指定的列,获取任务的最后修改时间 + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // local modification only + return SYNC_ACTION_UPDATE_REMOTE; + } else { + return SYNC_ACTION_UPDATE_CONFLICT; + } + } + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + + return SYNC_ACTION_ERROR; + } + //定义一个整型变量,表示同步操作为更新本地 + public boolean isWorthSaving() { + return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) + || (getNotes() != null && getNotes().trim().length() > 0); + } + //定义一个整型变量,表示同步操作为更新本地 + public void setCompleted(boolean completed) { + this.mCompleted = completed; + } + //定义一个整型变量,表示同步操作为更新本地 + public void setNotes(String notes) { + this.mNotes = notes; + } + //定义一个整型变量,表示同步操作为更新本地 + public void setPriorSibling(Task priorSibling) { + this.mPriorSibling = priorSibling; + } + //定义一个整型变量,表示同步操作为更新本地 + public void setParent(TaskList parent) { + this.mParent = parent; + } + //定义一个整型变量,表示同步操作为更新本地 + public boolean getCompleted() { + return this.mCompleted; + } + //定义一个整型变量,表示同步操作为更新本地 + public String getNotes() { + return this.mNotes; + } + //定义一个整型变量,表示同步操作为更新本地 + public Task getPriorSibling() { + return this.mPriorSibling; + } + //定义一个整型变量,表示同步操作为更新本地 + public TaskList getParent() { + return this.mParent; + } + +} diff --git a/src/net/micode/notes/gtask/data/TaskList.java b/src/net/micode/notes/gtask/data/TaskList.java new file mode 100644 index 0000000..0f0ed45 --- /dev/null +++ b/src/net/micode/notes/gtask/data/TaskList.java @@ -0,0 +1,422 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import java.util.ArrayList; + +import org.json.JSONException; +import org.json.JSONObject; + +import android.database.Cursor; +import android.util.Log; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.tool.GTaskStringUtils; + +public class TaskList extends Node { + private static final String TAG = TaskList.class.getSimpleName();// tag标记 + + private int mIndex;// 当前TaskList的指针 + + private ArrayList mChildren;// 类中主要的保存数据的单元,用来实现一个以Task为元素的ArrayList + + public TaskList() { + super(); + mChildren = new ArrayList(); + mIndex = 1; + } + + // 根据传入的 actionId 生成一个包含一定数据的 JSONObject 实体 + public JSONObject getCreateAction(int actionId) { + // 创建一个新的JSONObject对象,用于存储要返回的JSON数据 + JSONObject js = new JSONObject(); + + try { + // 将动作类型设为创建类型,并添加到JSONObject中 + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); + + // 将传入的actionId参数设置为action_id,表示该操作的唯一标识,并添加到JSONObject中 + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // 将TaskList对象的mIndex属性设置为index,表示当前TaskList的指针位置,并添加到JSONObject中 + js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); + + // 创建一个新的JSONObject对象entity,用于存储实体信息 + JSONObject entity = new JSONObject(); + // 将任务列表的名称信息添加到entity中 + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + // 将创建者ID设置为"null",并添加到entity中 + entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); + // 将实体类型设为群组类型,并添加到entity中 + entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, GTaskStringUtils.GTASK_JSON_TYPE_GROUP); + // 将存储实体信息的entity对象添加到JSONObject中 + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + } catch (JSONException e) { + // 如果出现异常,则打印错误信息并抛出自定义异常 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate tasklist-create jsonobject"); + } + + // 返回构建好的JSONObject对象 + return js; + } + + public JSONObject getUpdateAction(int actionId) { + // 创建一个新的JSONObject对象 + JSONObject js = new JSONObject(); + + try { + // 设置action_type字段为UPDATE + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); + + // 设置action_id字段为传入的actionId参数值 + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // 设置id字段为当前任务的gid(全局唯一标识符) + js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); + + // 创建一个新的JSONObject对象,用于存储任务的实体信息 + JSONObject entity = new JSONObject(); + // 设置实体的名称字段为当前任务的名称 + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + // 设置实体的删除状态字段为当前任务的删除状态 + entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); + // 将实体信息添加到主JSONObject对象中的entity_delta字段 + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + } catch (JSONException e) { + // 捕获JSONException异常并记录异常信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出自定义的ActionFailureException异常,提示生成任务更新JSONObject对象失败 + throw new ActionFailureException("fail to generate tasklist-update jsonobject"); + } + + // 返回构建好的JSONObject对象 + return js; + } + + public void setContentByRemoteJSON(JSONObject js) { + // 检查传入的JSONObject对象是否为空 + if (js != null) { + try { + // 解析并设置任务的id字段,如果JSONObject包含该字段 + if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { + setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); + } + + // 解析并设置任务的last_modified字段,如果JSONObject包含该字段 + if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { + setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); + } + + // 解析并设置任务的name字段,如果JSONObject包含该字段 + if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { + setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); + } + + } catch (JSONException e) { + // 捕获JSONException异常并记录异常信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 抛出自定义的ActionFailureException异常,提示从JSONObject获取任务内容失败 + throw new ActionFailureException("fail to get tasklist content from jsonobject"); + } + } + } + + public void setContentByLocalJSON(JSONObject js) { + // 检查传入的JSONObject对象是否为空,或者是否包含了指定的元数据 + if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { + // 如果条件不满足,则记录警告日志 + Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); + } + + try { + // 从JSONObject中获取名为META_HEAD_NOTE的子JSONObject + JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + + // 判断获取的folder的类型 + if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { + // 如果是文件夹类型,则获取文件夹的名称,并在前面添加MIUI_FOLDER_PREFFIX前缀,然后设置为任务的名称 + String name = folder.getString(NoteColumns.SNIPPET); + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); + } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { + // 如果是系统类型的文件夹 + if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) + // 如果是根文件夹,则设置名称为MIUI_FOLDER_PREFFIX + FOLDER_DEFAULT + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); + else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) + // 如果是通话记录文件夹,则设置名称为MIUI_FOLDER_PREFFIX + FOLDER_CALL_NOTE + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE); + else + // 如果是其他系统文件夹,则记录错误日志 + Log.e(TAG, "invalid system folder"); + } else { + // 如果是其他类型的文件夹,则记录错误日志 + Log.e(TAG, "error type"); + } + } catch (JSONException e) { + // 捕获JSONException异常并记录异常信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + } + + public JSONObject getLocalJSONFromContent() { + try { + // 创建一个新的JSONObject对象 + JSONObject js = new JSONObject(); + // 创建一个用于存储文件夹信息的JSONObject对象 + JSONObject folder = new JSONObject(); + + // 获取任务的名��� + String folderName = getName(); + // 如果任务名称以MIUI_FOLDER_PREFFIX前缀开头,则去除前缀 + if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) + folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), + folderName.length()); + // 将文件夹名称添加到folder JSONObject中 + folder.put(NoteColumns.SNIPPET, folderName); + // 判断文件夹名称是否为系统默认文件夹名称或者通话记录文件夹名称,如果是则设置类型为系统文件夹,否则设置为普通文件夹 + if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) + || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) + folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + else + folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + + // 将存储文件夹信息的folder JSONObject添加到js JSONObject中 + js.put(GTaskStringUtils.META_HEAD_NOTE, folder); + + // 返回构建好的JSONObject对象 + return js; + } catch (JSONException e) { + // 捕获JSONException异常并记录异常信息 + Log.e(TAG, e.toString()); + e.printStackTrace(); + // 返回null表示发生异常 + return null; + } + } + + public int getSyncAction(Cursor c) { + try { + if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { + // there is no local update + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // no update both side + return SYNC_ACTION_NONE; + } else { + // apply remote to local + return SYNC_ACTION_UPDATE_LOCAL; + } + } else { + // validate gtask id + if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { + Log.e(TAG, "gtask id doesn't match"); + return SYNC_ACTION_ERROR; + } + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // local modification only + return SYNC_ACTION_UPDATE_REMOTE; + } else { + // for folder conflicts, just apply local modification + return SYNC_ACTION_UPDATE_REMOTE; + } + } + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + + return SYNC_ACTION_ERROR; + } + + public int getChildTaskCount() { + return mChildren.size(); + } + + public boolean addChildTask(Task task) { + // 初始化返回值为false + boolean ret = false; + // 检查传入的任务对象是否为空,并且该任务对象不在子任务列表中 + if (task != null && !mChildren.contains(task)) { + // 将任务对象添加到子任务列表中,并将添加结果保存到ret变量中 + ret = mChildren.add(task); + // 如果成功添加任务,则需要设置任务的前一个兄弟节点和父节点 + if (ret) { + // 设置任务的前一个兄弟节点,如果子任务列表为空,则前一个兄弟节点为null,否则为子任务列表中最后一个任务 + task.setPriorSibling(mChildren.isEmpty() ? null + : mChildren + .get(mChildren.size() - 1)); + // 设置任务的父节点为当前任务对象 + task.setParent(this); + } + } + // 返回添加任务的结果 + return ret; + } + + public boolean addChildTask(Task task, int index) { + // 检查传入的索引是否合法,即不小于0且不大于子任务列表的大小 + if (index < 0 || index > mChildren.size()) { + // 如果索引非法,则记录错误日志并返回false + Log.e(TAG, "add child task: invalid index"); + return false; + } + + // 查找任务在子任务列表中的位置 + int pos = mChildren.indexOf(task); + // 如果任务不为空且不在子任务列表中 + if (task != null && pos == -1) { + // 将任务添加到指定位置 + mChildren.add(index, task); + + // 更新任务列表中的任务关系 + Task preTask = null; + Task afterTask = null; + // 获取新添加任务的前一个任务和后一个任务 + if (index != 0) + preTask = mChildren.get(index - 1); + if (index != mChildren.size() - 1) + afterTask = mChildren.get(index + 1); + + // 设置新添加任务的前一个兄弟节点为preTask + task.setPriorSibling(preTask); + // 如果存在后一个任务,则将其前一个兄弟节点设置为新添加的任务 + if (afterTask != null) + afterTask.setPriorSibling(task); + } + + // 返回添加任务的结果 + return true; + } + + public boolean removeChildTask(Task task) { + // 初始化返回值为false + boolean ret = false; + // 获取任务在子任务列表中的索引 + int index = mChildren.indexOf(task); + // 如果任务存在于子任务列表中 + if (index != -1) { + // 从子任务列表中移除任务,并将移除结果保存到ret变量中 + ret = mChildren.remove(task); + + // 如果成功移除任务 + if (ret) { + // 重置移除任务的前一个兄弟节点和父节点 + task.setPriorSibling(null); + task.setParent(null); + + // 更新任务列表中的任务关系 + if (index != mChildren.size()) { + // 如果移除的任务不是列表中的最后一个任务,则将后一个任务的前一个兄弟节点设置为移除任务的前一个任务 + mChildren.get(index).setPriorSibling( + index == 0 ? null : mChildren.get(index - 1)); + } + } + } + // 返回移除任务的结果 + return ret; + } + + public boolean moveChildTask(Task task, int index) { + // 检查传入的索引是否合法,即不小于0且小于子任务列表的大小 + if (index < 0 || index >= mChildren.size()) { + // 如果索引非法,则记录错误日志并返回false + Log.e(TAG, "move child task: invalid index"); + return false; + } + + // 查找任务在子任务列表中的位置 + int pos = mChildren.indexOf(task); + // 如果任务不在子任务列表中,则记录错误日志并返回false + if (pos == -1) { + Log.e(TAG, "move child task: the task should in the list"); + return false; + } + + // 如果任务已经在目标位置上,则直接返回true + if (pos == index) + return true; + + // 先移除任务,然后再添加到目标位置上 + return (removeChildTask(task) && addChildTask(task, index)); + } + + // 根据任务的gid查找子任务 + public Task findChildTaskByGid(String gid) { + // 遍历子任务列表 + for (int i = 0; i < mChildren.size(); i++) { + Task t = mChildren.get(i); + // 如果找到gid匹配的任务,则返回该任务 + if (t.getGid().equals(gid)) { + return t; + } + } + // 如果没有找到匹配的任务,则返回null + return null; + } + + // 获取子任务在子任务列表中的索引 + public int getChildTaskIndex(Task task) { + return mChildren.indexOf(task); + } + + // 根据索引获取子任务 + public Task getChildTaskByIndex(int index) { + // 检查传入的索引是否合法 + if (index < 0 || index >= mChildren.size()) { + // 如果索引非法,则记录错误日志并返回null + Log.e(TAG, "getTaskByIndex: invalid index"); + return null; + } + // 返回索引处的子任务 + return mChildren.get(index); + } + + // 根据gid获取子任务 + public Task getChilTaskByGid(String gid) { + // 遍历子任务列表 + for (Task task : mChildren) { + // 如果找到gid匹配的任务,则返回该任务 + if (task.getGid().equals(gid)) + return task; + } + // 如果没有找到匹配的任务,则返回null + return null; + } + + // 获取子任务列表 + public ArrayList getChildTaskList() { + return this.mChildren; + } + + // 设置任务在父任务列表中的索引 + public void setIndex(int index) { + this.mIndex = index; + } + + // 获取任务在父任务列表中的索引 + public int getIndex() { + return this.mIndex; + } +}