From c0fb563004c242e675df46fa75fbcddcea4798b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E6=98=8A=E9=98=B3?= <2406241504@qq.com> Date: Fri, 14 Apr 2023 16:34:55 +0800 Subject: [PATCH 1/3] mm --- lhy/ActionFailureException.java | 34 ++ lhy/Contact.java | 74 +++ lhy/GTaskASyncTask.java | 127 +++++ lhy/GTaskClient.java | 585 ++++++++++++++++++++++ lhy/GTaskManager.java | 800 +++++++++++++++++++++++++++++++ lhy/GTaskSyncService.java | 128 +++++ lhy/MetaData.java | 82 ++++ lhy/NetworkFailureException.java | 33 ++ lhy/Node.java | 101 ++++ lhy/Notes.java | 279 +++++++++++ lhy/NotesDatabaseHelper.java | 362 ++++++++++++++ lhy/NotesProvider.java | 305 ++++++++++++ lhy/SqlData.java | 189 ++++++++ lhy/SqlNote.java | 505 +++++++++++++++++++ lhy/Task.java | 351 ++++++++++++++ lhy/TaskList.java | 343 +++++++++++++ 16 files changed, 4298 insertions(+) create mode 100644 lhy/ActionFailureException.java create mode 100644 lhy/Contact.java create mode 100644 lhy/GTaskASyncTask.java create mode 100644 lhy/GTaskClient.java create mode 100644 lhy/GTaskManager.java create mode 100644 lhy/GTaskSyncService.java create mode 100644 lhy/MetaData.java create mode 100644 lhy/NetworkFailureException.java create mode 100644 lhy/Node.java create mode 100644 lhy/Notes.java create mode 100644 lhy/NotesDatabaseHelper.java create mode 100644 lhy/NotesProvider.java create mode 100644 lhy/SqlData.java create mode 100644 lhy/SqlNote.java create mode 100644 lhy/Task.java create mode 100644 lhy/TaskList.java diff --git a/lhy/ActionFailureException.java b/lhy/ActionFailureException.java new file mode 100644 index 0000000..32e5cab --- /dev/null +++ b/lhy/ActionFailureException.java @@ -0,0 +1,34 @@ +/* + * 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.exception; + +public class ActionFailureException extends RuntimeException {//用来验证版本一致性,如果不一致会导致反序列化的时候版本不一致的异常。 + private static final long serialVersionUID = 4425249765923293627L; +// 函数:交给父类的构造函数(包括下面的两个构造函数) + public ActionFailureException() { + super(); + }//super是指向父类的一个指针,与其相对的还有this,指向当前类。 +//调用父类具有相同形参paramString的构造方法 + public ActionFailureException(String paramString) { + super(paramString); + } +//函数:第三种形式的构造函数 + public ActionFailureException(String paramString, Throwable paramThrowable) { + super(paramString, paramThrowable); + } +} diff --git a/lhy/Contact.java b/lhy/Contact.java new file mode 100644 index 0000000..760d8bd --- /dev/null +++ b/lhy/Contact.java @@ -0,0 +1,74 @@ +/* + * 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.data;//当前文件所在的包名 +/*接下来引用android的一些库*/ +import android.content.Context;//调用Android自带的类 +import android.database.Cursor;//从数据库导入Cursor +import android.provider.ContactsContract.CommonDataKinds.Phone;//导入联系人电话 +import android.provider.ContactsContract.Data;//存储通讯信息 +import android.telephony.PhoneNumberUtils;//格式化用户输入的电话号码 +import android.util.Log;//安卓日志输出工具类 + +import java.util.HashMap;//用hashmap存储联系人信息 + +public class Contact {//存放联系人信息 + private static HashMap sContactCache;//存储联系人及对应的电话号码 + private static final String TAG = "Contact";//定义字符串常量 TAG指向Contact + + private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER//定义 CALLER_ID_SELECTION字符串,用于匹配联系人 + + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + + " AND " + Data.RAW_CONTACT_ID + " IN "//定义的callerIDSELEDTION所包含的各项数据 + + "(SELECT raw_contact_id " + + " FROM phone_lookup" + + " WHERE min_match = '+')"; + /*获取联系人参数Context context内容 phoneNumber和电话号码 + */ + public static String getContact(Context context, String phoneNumber) {//获取联系人 + if(sContactCache == null) {//如果当前还没有联系人,那么新建一个HashMap存储联系人 + sContactCache = new HashMap();//创建哈希表 + } + + if(sContactCache.containsKey(phoneNumber)) {//如果hashmap实例里包含电话号码,则返回电话号码 + return sContactCache.get(phoneNumber);//如果根据电话号码phoneNumber索引到了对应的联系人,那么把对应的联系人的信息返回 + } + + String selection = CALLER_ID_SELECTION.replace("+",//将CALLER_ID_SELECTION的“+”号替代为号码的后MIN_MATCH位 + PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); + Cursor cursor = context.getContentResolver().query(//通过selection的查询语句去数据库查询 + Data.CONTENT_URI,//提供联系人的内容的地址 + new String [] { Phone.DISPLAY_NAME },//返回联系人名字 + selection,//设置条件,相当于whlie + new String[] { phoneNumber },//get..函数返回字符串类phoneNUmber(手机号码) + null);//判定查询结果 + + if (cursor != null && cursor.moveToFirst()) {// 判断查询结果,如果找到,并且成功返回第一天数据 + try {//得到cursor的第一个字符串name + String name = cursor.getString(0);//从内容中获取联系人姓名 + sContactCache.put(phoneNumber, name);//将联系人姓名和电话号码写入缓存 + return name;//返回名字 + } catch (IndexOutOfBoundsException e) {//出现异常 + Log.e(TAG, " Cursor get string error " + e.toString());//Log.e为红色,可以想到error错误,这里仅显示红色的错误信息 + return null; + } finally {//关闭数据库的访问 + cursor.close();//关闭数据库的访问 + } + } else {//未找到相关信息,返回空指针 + Log.d(TAG, "No contact matched with number:" + phoneNumber);//如果没有找到信息,返回没有匹配到该电话 + return null;//返回空 + } + } +} diff --git a/lhy/GTaskASyncTask.java b/lhy/GTaskASyncTask.java new file mode 100644 index 0000000..08a48a3 --- /dev/null +++ b/lhy/GTaskASyncTask.java @@ -0,0 +1,127 @@ + +/* + * 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.remote; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.os.AsyncTask; + +import net.micode.notes.R; +import net.micode.notes.ui.NotesListActivity; +import net.micode.notes.ui.NotesPreferenceActivity; + + +public class GTaskASyncTask extends AsyncTask {/*异步操作类,实现GTask的异步操作过程 + private void showNotification(int tickerId, String content) 向用户提示当前同步的状态,是一个用于交互的方法*/ + + private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; +//初始化异步功能 + public interface OnCompleteListener { + void onComplete(); + } + private Context mContext;//文本内容 + + private NotificationManager mNotifiManager;//对象: 通知管理器类的实例化 + + private GTaskManager mTaskManager;//实例化任务管理器 + + private OnCompleteListener mOnCompleteListener; + + public GTaskASyncTask(Context context, OnCompleteListener listener) {//函数: GTaskASyncTask类的构造函数 + mContext = context; + mOnCompleteListener = listener; + mNotifiManager = (NotificationManager) mContext + .getSystemService(Context.NOTIFICATION_SERVICE); + mTaskManager = GTaskManager.getInstance(); + } + + public void cancelSync() {//取消同步 + mTaskManager.cancelSync(); + } + + public void publishProgess(String message) {//显示消息 + publishProgress(new String[] { + message + }); + } + + private void showNotification(int tickerId, String content) { + PendingIntent pendingIntent; + if (tickerId != R.string.ticker_success) { + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, + NotesPreferenceActivity.class), 0); + + } else {//点击清除按钮或点击通知后会自动消失 + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, + NotesListActivity.class), 0); + } + +//若同步成功,就从系统取得一个来启动一个NotesListActivity的对象 + Notification.Builder builder = new Notification.Builder(mContext) + .setAutoCancel(true) + .setContentTitle(mContext.getString(R.string.app_name))//设置最新事件信息 + .setContentText(content) + .setContentIntent(pendingIntent) + .setWhen(System.currentTimeMillis()) + .setOngoing(true); + Notification notification=builder.getNotification(); + mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//执行后台操作 + } + + @Override + protected Integer doInBackground(Void... unused) { + publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity + .getSyncAccountName(mContext))); + return mTaskManager.sync(mContext, this);//显示进度的更新 + } + + @Override + protected void onProgressUpdate(String... progress) { + showNotification(R.string.ticker_syncing, progress[0]); + if (mContext instanceof GTaskSyncService) { + ((GTaskSyncService) mContext).sendBroadcast(progress[0]); + } + } + + @Override + protected void onPostExecute(Integer result) { + if (result == GTaskManager.STATE_SUCCESS) {//设置任务,比如在用户界面显示一个进度条 + showNotification(R.string.ticker_success, mContext.getString( + R.string.success_sync_account, mTaskManager.getSyncAccount())); + NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); + } else if (result == GTaskManager.STATE_NETWORK_ERROR) { + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); + } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); + } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { + showNotification(R.string.ticker_cancel, mContext + .getString(R.string.error_sync_cancelled)); + } + if (mOnCompleteListener != null) {//若监听器为空,则创建新进程 + new Thread(new Runnable() { + + public void run() {//执行完后调用然后返回主线程中 + mOnCompleteListener.onComplete(); + } + }).start(); + } + } +} diff --git a/lhy/GTaskClient.java b/lhy/GTaskClient.java new file mode 100644 index 0000000..7cbc0dc --- /dev/null +++ b/lhy/GTaskClient.java @@ -0,0 +1,585 @@ +/* + * 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.remote; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AccountManagerFuture; +import android.app.Activity; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.GTaskStringUtils; +import net.micode.notes.ui.NotesPreferenceActivity; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.cookie.Cookie; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpConnectionParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.Inflater; +import java.util.zip.InflaterInputStream; + + +public class GTaskClient {//GTaskClient类:实现GTask的登录以及创建GTask任务和任务列表,从网络上获取任务内容 + private static final String TAG = GTaskClient.class.getSimpleName();//Google邮箱指定URL + + private static final String GTASK_URL = "https://mail.google.com/tasks/";//获得URL + + private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";//传递URL + + private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; + + private static GTaskClient mInstance = null;//后续使用的参数以及变量 + + private DefaultHttpClient mHttpClient; + + private String mGetUrl; +//构造函数:初始化各属性 + private String mPostUrl; + + private long mClientVersion; + + private boolean mLoggedin; + + private long mLastLoginTime; + + private int mActionId; + + private Account mAccount; + + private JSONArray mUpdateArray; + + private GTaskClient() {//初始化客户端,如果没有就new一个,否则就用当前的。 + mHttpClient = null; + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + mClientVersion = -1; + mLoggedin = false; + mLastLoginTime = 0; + mActionId = 1; + mAccount = null; + mUpdateArray = null; + } + + public static synchronized GTaskClient getInstance() {//获取实例,如果当前没有示例,则新建一个登陆的gtask,如果有直接返回 + if (mInstance == null) { + mInstance = new GTaskClient(); + } + return mInstance; + } + + public boolean login(Activity activity) {//login:用于实现登录的方法,以activity作为参数 + // we suppose that the cookie would expire after 5 minutes + // then we need to re-login + final long interval = 1000 * 60 * 5; + if (mLastLoginTime + interval < System.currentTimeMillis()) { + mLoggedin = false; + } + + // need to re-login after account switch + if (mLoggedin//在登陆成功的情况下检测到用户名和密码不匹配时登录失败 + && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity + .getSyncAccountName(activity))) { + mLoggedin = false; + } + + if (mLoggedin) {//代码块,如果登录的时候符合上面的要求则让其显示已登录登陆 + Log.d(TAG, "already logged in"); + return true; + } + + mLastLoginTime = System.currentTimeMillis(); + String authToken = loginGoogleAccount(activity, false); + if (authToken == null) {//登录失败的情况 + Log.e(TAG, "login google account failed"); + return false; + } + + // login with custom domain if necessary + if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()//使用用户域名进行登录 + .endsWith("googlemail.com"))) { + StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); + int index = mAccount.name.indexOf('@') + 1;//返回@第一次出现的位置并把位置+1后记录在index里 + String suffix = mAccount.name.substring(index); + url.append(suffix + "/"); + mGetUrl = url.toString() + "ig"; + mPostUrl = url.toString() + "r/ig"; + + if (tryToLoginGtask(activity, authToken)) {//成功登入 + mLoggedin = true; + } + } + + // try to login with google official url + if (!mLoggedin) {//代码块: 若前面的尝试失败,则尝试使用官方的域名登陆 + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + if (!tryToLoginGtask(activity, authToken)) {//第二次登录失败,返回false + return false; + } + } + + mLoggedin = true; + return true; + } + + private String loginGoogleAccount(Activity activity, boolean invalidateToken) {//登录谷歌账号的主函数,在登陆成功后获取认证令牌 + String authToken; + AccountManager accountManager = AccountManager.get(activity); + Account[] accounts = accountManager.getAccountsByType("com.google"); + + if (accounts.length == 0) {//如果没有这样的账号,输出日志信息“无有效的google账户” + Log.e(TAG, "there is no available google account"); + return null; + } + + String accountName = NotesPreferenceActivity.getSyncAccountName(activity); + Account account = null; + for (Account a : accounts) {//找到后,为属性赋值 + if (a.name.equals(accountName)) { + account = a; + break; + } + } + if (account != null) {//判断设置里有无该账号 + mAccount = account; + } else { + Log.e(TAG, "unable to get an account with the same name in the settings"); + return null; + } + + // get the token now + AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, + "goanna_mobile", null, activity, null, null); + try { + Bundle authTokenBundle = accountManagerFuture.getResult(); + authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); + if (invalidateToken) {//如果是非法的令牌,那么废除这个账号,取消登录状态 + accountManager.invalidateAuthToken("com.google", authToken); + loginGoogleAccount(activity, false); + } + } catch (Exception e) { + Log.e(TAG, "get auth token failed"); + authToken = null; + } + + return authToken; + } + + private boolean tryToLoginGtask(Activity activity, String authToken) {//方法:用于判断令牌对于登陆gtask账号是否有效 + if (!loginGtask(authToken)) { + // maybe the auth token is out of date, now let's invalidate the + // token and try again + authToken = loginGoogleAccount(activity, true); + if (authToken == null) { + Log.e(TAG, "login google account failed"); + return false; + } + + if (!loginGtask(authToken)) {//代码块: 重新获取的令牌再次失效 + Log.e(TAG, "login gtask failed"); + return false; + } + } + return true; + } + + private boolean loginGtask(String authToken) {//.loginGtask:实现登录Gtask的方法 + int timeoutConnection = 10000; + int timeoutSocket = 15000; + HttpParams httpParameters = new BasicHttpParams(); + HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); + HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); + mHttpClient = new DefaultHttpClient(httpParameters); + BasicCookieStore localBasicCookieStore = new BasicCookieStore(); + mHttpClient.setCookieStore(localBasicCookieStore); + HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); + + // login gtask + try {//登录Gtask + String loginUrl = mGetUrl + "?auth=" + authToken; + HttpGet httpGet = new HttpGet(loginUrl); + HttpResponse response = null; + response = mHttpClient.execute(httpGet); + + // get the cookie now + List cookies = mHttpClient.getCookieStore().getCookies(); + boolean hasAuthCookie = false; + for (Cookie cookie : cookies) { + if (cookie.getName().contains("GTL")) {//验证cookie信息,这里通过GTL标志来验证 + hasAuthCookie = true; + } + } + if (!hasAuthCookie) { + Log.w(TAG, "it seems that there is no auth cookie"); + } + + // get the client version + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin != -1 && end != -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + mClientVersion = js.getLong("v");//验证cookie信息,这里通过GTL标志来验证 + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return false; + } catch (Exception e) { + // simply catch all exceptions + Log.e(TAG, "httpget gtask_url failed"); + return false; + } + + return true; + } + + private int getActionId() { + return mActionId++; + }//获取动作的id号码 + + private HttpPost createHttpPost() { + HttpPost httpPost = new HttpPost(mPostUrl); + httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); + httpPost.setHeader("AT", "1"); + return httpPost; + } + + private String getResponseContent(HttpEntity entity) throws IOException {//getResponseContent:获取服务器响应的数据,主要通过方法getContentEncoding来获取网上资源,返回这些资源 + String contentEncoding = null; + if (entity.getContentEncoding() != null) { + contentEncoding = entity.getContentEncoding().getValue(); + Log.d(TAG, "encoding: " + contentEncoding); + } + + InputStream input = entity.getContent(); + if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { + input = new GZIPInputStream(entity.getContent()); + } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { + Inflater inflater = new Inflater(true); + input = new InflaterInputStream(entity.getContent(), inflater); + } + + try {//完成将字节流数据内容进行存储的功能 + InputStreamReader isr = new InputStreamReader(input); + BufferedReader br = new BufferedReader(isr); + StringBuilder sb = new StringBuilder(); + + while (true) { + String buff = br.readLine(); + if (buff == null) { + return sb.toString(); + } + sb = sb.append(buff); + } + } finally { + input.close(); + } + } + + private JSONObject postRequest(JSONObject js) throws NetworkFailureException {//获取客户端资源的函数 + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + HttpPost httpPost = createHttpPost(); + try {//.实例化一个对象,用于与服务器交互和发送请求 + LinkedList list = new LinkedList(); + list.add(new BasicNameValuePair("r", js.toString())); + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); + httpPost.setEntity(entity); + + // execute the post + HttpResponse response = mHttpClient.execute(httpPost); + String jsString = getResponseContent(response.getEntity()); + return new JSONObject(jsString); + + } catch (ClientProtocolException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed"); + } catch (IOException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("unable to convert response content to jsonobject"); + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("error occurs when posting request"); + } + } + + public void createTask(Task task) throws NetworkFailureException {//创建单个任务,通过json获取TASK中的内容并创建对应的jsPost,通过postRequest方法获取任务的返回信息,使用setGid方法设置task的new_id + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // action_list + actionList.put(task.getCreateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // post + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) {//对异常情况的处理 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("create task: handing jsonobject failed"); + } + } + + public void createTaskList(TaskList tasklist) throws NetworkFailureException {//创建一个任务列表 + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // action_list + actionList.put(tasklist.getCreateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // post + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) {//创建失败 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("create tasklist: handing jsonobject failed"); + } + } + + public void commitUpdate() throws NetworkFailureException {//更新时出现异常 + if (mUpdateArray != null) { + try { + JSONObject jsPost = new JSONObject(); + + // action_list + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + mUpdateArray = null; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("commit update: handing jsonobject failed"); + } + } + } + + public void addUpdateNode(Node node) throws NetworkFailureException {//添加更新节点,主要利用commitUpdate + if (node != null) { + // too many update items may result in an error + // set max to 10 items + if (mUpdateArray != null && mUpdateArray.length() > 10) { + commitUpdate(); + } + + if (mUpdateArray == null) + mUpdateArray = new JSONArray(); + mUpdateArray.put(node.getUpdateAction(getActionId())); + } + } + + public void moveTask(Task task, TaskList preParent, TaskList curParent)//移动一个任务,通过getGid获取task所属的Id,还是通过JSONObject和postRequest实现 + throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + // action_list + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); + if (preParent == curParent && task.getPriorSibling() != null) {//只有当移动是发生在任务列表中且不是第一个时设置优先级 + // put prioring_sibing_id only if moving within the tasklist and + // it is not the first one + action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); + } + action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); + action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); + if (preParent != curParent) {//当移动发生在不同的任务列表之间,设置为dest_list + // put the dest_list only if moving between tasklists + action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); + } + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("move task: handing jsonobject failed"); + } + } + + public void deleteNode(Node node) throws NetworkFailureException {//删除节点,过程类似移动 + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // action_list + node.setDeleted(true); + actionList.put(node.getUpdateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + mUpdateArray = null; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("delete node: handing jsonobject failed"); + } + } + + public JSONArray getTaskLists() throws NetworkFailureException {//获取任务列表,首先通过getURI在网上获取数据,在截取所需部分内容返回 + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + try { + HttpGet httpGet = new HttpGet(mGetUrl); + HttpResponse response = null; + response = mHttpClient.execute(httpGet); + + // get the task list + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin != -1 && end != -1 && begin < end) {//带参数的获取指定的任务列表 + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); + } catch (ClientProtocolException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (IOException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task lists: handing jasonobject failed"); + } + } + + public JSONArray getTaskList(String listGid) throws NetworkFailureException {//方法:对于已经获取的任务列表,可以通过其id来获取到 + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + // action_list 通过action.pu()t对JSONObject对象action添加元素,通过jsPost.put()对jsPost添加相关元素,然后通过postRequest()提交更新后的请求并返回一个JSONObject的对象,最后使用jsResponse.getJSONArray( )获取jsResponse中的JSONArray值并作为函数返回值 + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); + action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + JSONObject jsResponse = postRequest(jsPost); + return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); + } catch (JSONException e) {//处理异常 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task list: handing jsonobject failed"); + } + } + + public Account getSyncAccount() { + return mAccount; + }//获得同步账户 + + public void resetUpdateArray() { + mUpdateArray = null; + }//重置更新内容 +} diff --git a/lhy/GTaskManager.java b/lhy/GTaskManager.java new file mode 100644 index 0000000..ebfd7ca --- /dev/null +++ b/lhy/GTaskManager.java @@ -0,0 +1,800 @@ +/* + * 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.remote; + +import android.app.Activity; +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.R; +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.data.MetaData; +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.SqlNote; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + + +public class GTaskManager {//GTask管理类,封装了对GTask进行管理的一些方法 + private static final String TAG = GTaskManager.class.getSimpleName(); + + public static final int STATE_SUCCESS = 0;//成功 + + public static final int STATE_NETWORK_ERROR = 1;//网络错误 + + public static final int STATE_INTERNAL_ERROR = 2; + + public static final int STATE_SYNC_IN_PROGRESS = 3; + + public static final int STATE_SYNC_CANCELLED = 4; + + private static GTaskManager mInstance = null;//private 定义一系列不可被外部的类访问的量 + + private Activity mActivity; + + private Context mContext;//构造函数 + + private ContentResolver mContentResolver; + + private boolean mSyncing; + + private boolean mCancelled; + + private HashMap mGTaskListHashMap; + + private HashMap mGTaskHashMap; + + private HashMap mMetaHashMap; + + private TaskList mMetaList; + + private HashSet mLocalDeleteIdMap; + + private HashMap mGidToNid; + + private HashMap mNidToGid; + + private GTaskManager() {//类的构造函数,对其内部变量进行初始化 + mSyncing = false;//正在同步标识,false代表未同步 + mCancelled = false; + mGTaskListHashMap = new HashMap(); + mGTaskHashMap = new HashMap(); + mMetaHashMap = new HashMap(); + mMetaList = null; + mLocalDeleteIdMap = new HashSet(); + mGidToNid = new HashMap(); + mNidToGid = new HashMap(); + } + + public static synchronized GTaskManager getInstance() {//synchronized指明该函数可以运行在多线程下 + if (mInstance == null) { + mInstance = new GTaskManager(); + } + return mInstance; + } + + public synchronized void setActivityContext(Activity activity) {//对类的当前实例进行加锁,防止其他线程同时访问该类的该实例的所有synchronized块 + // used for getting authtoken + mActivity = activity; + } + + public int sync(Context context, GTaskASyncTask asyncTask) {//实现本地和远程同步的操作 + if (mSyncing) { + Log.d(TAG, "Sync is in progress"); + return STATE_SYNC_IN_PROGRESS; + } + mContext = context; + mContentResolver = mContext.getContentResolver(); + mSyncing = true; + mCancelled = false; + mGTaskListHashMap.clear(); + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + + try {//异常处理程序 + GTaskClient client = GTaskClient.getInstance(); + client.resetUpdateArray(); + + // login google task + if (!mCancelled) { + if (!client.login(mActivity)) { + throw new NetworkFailureException("login google task failed"); + }//登录 google 任务失败 + } + + // get the task list from google + asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); + initGTaskList();//调用下面自定义的方法,初始化GTaskList + + // do content sync work + asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); + syncContent();//同步便签内容 + } catch (NetworkFailureException e) { + Log.e(TAG, e.toString()); + return STATE_NETWORK_ERROR; + } catch (ActionFailureException e) { + Log.e(TAG, e.toString()); + return STATE_INTERNAL_ERROR; + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return STATE_INTERNAL_ERROR; + } finally {//结束后清空环境 + mGTaskListHashMap.clear(); + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + mSyncing = false; + } + + return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;//若在同步时操作未取消,则说明同步成功,否则返回同步操作取消 + } + + private void initGTaskList() throws NetworkFailureException {//初始化GTask列表,将google上的JSONTaskList转为本地任务列表 + if (mCancelled) + return; + GTaskClient client = GTaskClient.getInstance(); + try {//客户端获取任务列表 + JSONArray jsTaskLists = client.getTaskLists(); + + // init meta list first + mMetaList = null; + for (int i = 0; i < jsTaskLists.length(); i++) { + JSONObject object = jsTaskLists.getJSONObject(i); + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); + + if (name//如果 name 等于 字符串 "[MIUI_Notes]" + "METADATA",执行if语句块 + .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { + mMetaList = new TaskList(); + mMetaList.setContentByRemoteJSON(object); + + // load meta data + JSONArray jsMetas = client.getTaskList(gid); + for (int j = 0; j < jsMetas.length(); j++) { + object = (JSONObject) jsMetas.getJSONObject(j); + MetaData metaData = new MetaData(); + metaData.setContentByRemoteJSON(object); + if (metaData.isWorthSaving()) { + mMetaList.addChildTask(metaData); + if (metaData.getGid() != null) { + mMetaHashMap.put(metaData.getRelatedGid(), metaData);//把元数据放到哈希表中 + } + } + } + } + } + + // create meta list if not existed + if (mMetaList == null) {//若元数据列表不存在则创建一个 + mMetaList = new TaskList(); + mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META); + GTaskClient.getInstance().createTaskList(mMetaList); + } + + // init task list + for (int i = 0; i < jsTaskLists.length(); i++) {//以下循环用于初始化任务列表 + JSONObject object = jsTaskLists.getJSONObject(i); + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); + + if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) + && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META)) { + TaskList tasklist = new TaskList();//创建一个新的任务列表 + tasklist.setContentByRemoteJSON(object); + mGTaskListHashMap.put(gid, tasklist); + mGTaskHashMap.put(gid, tasklist); + + // load tasks + JSONArray jsTasks = client.getTaskList(gid); + for (int j = 0; j < jsTasks.length(); j++) {//任务id号 + object = (JSONObject) jsTasks.getJSONObject(j); + gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + Task task = new Task(); + task.setContentByRemoteJSON(object); + if (task.isWorthSaving()) {//判断该任务有无价值保存 + task.setMetaInfo(mMetaHashMap.get(gid)); + tasklist.addChildTask(task); + mGTaskHashMap.put(gid, task); + } + } + } + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("initGTaskList: handing JSONObject failed"); + } + } + + private void syncContent() throws NetworkFailureException {//实现内容同步 + int syncType; + Cursor c = null; + String gid; + Node node; + + mLocalDeleteIdMap.clear(); + + if (mCancelled) {//对于本地已删除的便签采取的动作 + return; + } + + // for local deleted note + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type<>? AND parent_id=?)", new String[] { + String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) + }, null); + if (c != null) { + while (c.moveToNext()) { + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); + } + + mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); + } + } else { + Log.w(TAG, "failed to query trash folder"); + } + } finally {//最后把c关闭并重置 + if (c != null) { + c.close(); + c = null; + } + } + + // sync folder first + syncFolder(); + + // for note existing in database + try {//对于数据库中已经存在的便签,采取以下操作 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type=? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c != null) { + while (c.moveToNext()) { + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); + syncType = node.getSyncAction(c); + } else { + if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { + // local add + syncType = Node.SYNC_ACTION_ADD_REMOTE; + } else { + // remote delete + syncType = Node.SYNC_ACTION_DEL_LOCAL; + } + } + doContentSync(syncType, node, c); + } + } else { + Log.w(TAG, "failed to query existing note in database"); + } + + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // go through remaining items//访问保留的项目 + Iterator> iter = mGTaskHashMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + node = entry.getValue(); + doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); + } + + // mCancelled can be set by another thread, so we neet to check one by + // one + // clear local delete table + if (!mCancelled) {//终止标识有可能被其他进程改变,因此需要一个个进行检查 + if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { + throw new ActionFailureException("failed to batch-delete local deleted notes"); + } + } + + // refresh local sync id + if (!mCancelled) {//更新同步表 + GTaskClient.getInstance().commitUpdate(); + refreshLocalSyncId(); + } + + } + + private void syncFolder() throws NetworkFailureException {//初始化文件夹。放在第一种情况之后是因为第一种情况不需要初始化文件夹 + Cursor c = null; + String gid; + Node node; + int syncType; + + if (mCancelled) { + return; + } + + // for root folder + try { + c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, + Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); + if (c != null) { + c.moveToNext(); + gid = c.getString(SqlNote.GTASK_ID_COLUMN);//获取指针指向内容对应的gid + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); + mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); + // for system folder, only update remote name if necessary + if (!node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) + doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); + } else { + doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); + } + } else { + Log.w(TAG, "failed to query root folder");//出现异常时,在日志中写回出错信息 + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // for call-note folder + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", + new String[] { + String.valueOf(Notes.ID_CALL_RECORD_FOLDER) + }, null); + if (c != null) { + if (c.moveToNext()) { + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); + mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); + // for system folder, only update remote name if + // necessary + if (!node.getName().equals(//若当前访问的文件夹是系统文件夹则只需要更新 + GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_CALL_NOTE)) + doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); + } else { + doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); + } + } + } else { + Log.w(TAG, "failed to query call note folder"); + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // for local existing folders + try {//对于本地已存在的文件的操作 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type=? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c != null) { + while (c.moveToNext()) {//使指针遍历所有的文件夹 + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); + syncType = node.getSyncAction(c); + } else { + if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { + // local add + syncType = Node.SYNC_ACTION_ADD_REMOTE; + } else { + // remote delete + syncType = Node.SYNC_ACTION_DEL_LOCAL; + } + } + doContentSync(syncType, node, c); + } + } else {//进行同步操作 + Log.w(TAG, "failed to query existing folder"); + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // for remote add folders + Iterator> iter = mGTaskListHashMap.entrySet().iterator(); + while (iter.hasNext()) {//使用迭代器对远程增添的内容进行遍历 + Map.Entry entry = iter.next(); + gid = entry.getKey(); + node = entry.getValue(); + if (mGTaskHashMap.containsKey(gid)) { + mGTaskHashMap.remove(gid); + doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); + } + } + + if (!mCancelled) + GTaskClient.getInstance().commitUpdate(); + } + + private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {//内容同步,同步同步类型、节点以及数据库指针 + if (mCancelled) { + return; + } + + MetaData meta; + switch (syncType) { + case Node.SYNC_ACTION_ADD_LOCAL: + addLocalNode(node); + break; + case Node.SYNC_ACTION_ADD_REMOTE: + addRemoteNode(node, c); + break; + case Node.SYNC_ACTION_DEL_LOCAL: + meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN)); + if (meta != null) { + GTaskClient.getInstance().deleteNode(meta); + } + mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); + break; + case Node.SYNC_ACTION_DEL_REMOTE: + meta = mMetaHashMap.get(node.getGid()); + if (meta != null) { + GTaskClient.getInstance().deleteNode(meta); + } + GTaskClient.getInstance().deleteNode(node); + break; + case Node.SYNC_ACTION_UPDATE_LOCAL: + updateLocalNode(node, c); + break; + case Node.SYNC_ACTION_UPDATE_REMOTE: + updateRemoteNode(node, c); + break; + case Node.SYNC_ACTION_UPDATE_CONFLICT: + // merging both modifications maybe a good idea + // right now just use local update simply + updateRemoteNode(node, c); + break; + case Node.SYNC_ACTION_NONE: + break; + case Node.SYNC_ACTION_ERROR: + default: + throw new ActionFailureException("unkown sync action type"); + }//抛出异常 + } + + private void addLocalNode(Node node) throws NetworkFailureException { + if (mCancelled) { + return; + } + + SqlNote sqlNote; + if (node instanceof TaskList) { + if (node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { + sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); + } else if (node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { + sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); + } else { + sqlNote = new SqlNote(mContext); + sqlNote.setContent(node.getLocalJSONFromContent()); + sqlNote.setParentId(Notes.ID_ROOT_FOLDER); + } + } else {//代码块:若待增添节点不是任务列表中的节点,进一步操作 + sqlNote = new SqlNote(mContext); + JSONObject js = node.getLocalJSONFromContent(); + try { + if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + if (note.has(NoteColumns.ID)) { + long id = note.getLong(NoteColumns.ID); + if (DataUtils.existInNoteDatabase(mContentResolver, id)) { + // the id is not available, have to create a new one + note.remove(NoteColumns.ID); + } + } + } + + if (js.has(GTaskStringUtils.META_HEAD_DATA)) {//以下为判断便签中的数据条目 + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + if (data.has(DataColumns.ID)) { + long dataId = data.getLong(DataColumns.ID); + if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { + // the data id is not available, have to create + // a new one + data.remove(DataColumns.ID); + } + } + } + + } + } catch (JSONException e) {//出现异常时,打印异常信息 + Log.w(TAG, e.toString()); + e.printStackTrace(); + } + sqlNote.setContent(js); + + Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); + if (parentId == null) { + Log.e(TAG, "cannot find task's parent id locally"); + throw new ActionFailureException("cannot add local node"); + } + sqlNote.setParentId(parentId.longValue()); + } + + // create the local node + sqlNote.setGtaskId(node.getGid()); + sqlNote.commit(false); + + // update gid-nid mapping + mGidToNid.put(node.getGid(), sqlNote.getId()); + mNidToGid.put(sqlNote.getId(), node.getGid()); + + // update meta + updateRemoteMeta(node.getGid(), sqlNote); + } + + private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {//更新本地节点,两个传入参数,一个是待更新的节点,一个是指向待增加位置的指针 + if (mCancelled) { + return; + } + + SqlNote sqlNote; + // update the note locally + sqlNote = new SqlNote(mContext, c); + sqlNote.setContent(node.getLocalJSONFromContent()); + + Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) + : new Long(Notes.ID_ROOT_FOLDER); + if (parentId == null) { + Log.e(TAG, "cannot find task's parent id locally"); + throw new ActionFailureException("cannot update local node"); + } + sqlNote.setParentId(parentId.longValue()); + sqlNote.commit(true); + + // update meta info + updateRemoteMeta(node.getGid(), sqlNote); + } + + private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {//添加远程节点 + if (mCancelled) { + return; + } + + SqlNote sqlNote = new SqlNote(mContext, c); + Node n; + + // update remotely + if (sqlNote.isNoteType()) { + Task task = new Task(); + task.setContentByLocalJSON(sqlNote.getContent()); + + String parentGid = mNidToGid.get(sqlNote.getParentId()); + if (parentGid == null) { + Log.e(TAG, "cannot find task's parent tasklist"); + throw new ActionFailureException("cannot add remote task"); + } + mGTaskListHashMap.get(parentGid).addChildTask(task); + + GTaskClient.getInstance().createTask(task); + n = (Node) task; + + // add meta + updateRemoteMeta(task.getGid(), sqlNote); + } else { + TaskList tasklist = null; + + // we need to skip folder if it has already existed//当文件夹存在则跳过,若不存在则创建新的文件夹 + String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX; + if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) + folderName += GTaskStringUtils.FOLDER_DEFAULT; + else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER) + folderName += GTaskStringUtils.FOLDER_CALL_NOTE; + else + folderName += sqlNote.getSnippet(); + + Iterator> iter = mGTaskListHashMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + String gid = entry.getKey(); + TaskList list = entry.getValue(); + + if (list.getName().equals(folderName)) { + tasklist = list; + if (mGTaskHashMap.containsKey(gid)) { + mGTaskHashMap.remove(gid); + } + break; + } + } + + // no match we can add now + if (tasklist == null) {//直接新建一个任务链 + tasklist = new TaskList(); + tasklist.setContentByLocalJSON(sqlNote.getContent()); + GTaskClient.getInstance().createTaskList(tasklist); + mGTaskListHashMap.put(tasklist.getGid(), tasklist); + } + n = (Node) tasklist; + } + + // update local note + sqlNote.setGtaskId(n.getGid()); + sqlNote.commit(false); + sqlNote.resetLocalModified(); + sqlNote.commit(true); + + // gid-id mapping + mGidToNid.put(n.getGid(), sqlNote.getId()); + mNidToGid.put(sqlNote.getId(), n.getGid()); + } + + private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {//更新远程结点,参数node是要更新的结点,c是数据库的指针 + if (mCancelled) { + return; + } + + SqlNote sqlNote = new SqlNote(mContext, c); + + // update remotely + node.setContentByLocalJSON(sqlNote.getContent()); + GTaskClient.getInstance().addUpdateNode(node); + + // update meta + updateRemoteMeta(node.getGid(), sqlNote); + + // move task if necessary + if (sqlNote.isNoteType()) {//判断节点类型是否符合要求 + Task task = (Task) node; + TaskList preParentList = task.getParent(); + + String curParentGid = mNidToGid.get(sqlNote.getParentId()); + if (curParentGid == null) { + Log.e(TAG, "cannot find task's parent tasklist"); + throw new ActionFailureException("cannot update remote task"); + } + TaskList curParentList = mGTaskListHashMap.get(curParentGid); + + if (preParentList != curParentList) { + preParentList.removeChildTask(task); + curParentList.addChildTask(task); + GTaskClient.getInstance().moveTask(task, preParentList, curParentList); + } + } + + // clear local modified flag + sqlNote.resetLocalModified(); + sqlNote.commit(true); + } + + private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {//更新远程结点的数据,与上一个函数不同的是这里只更新数据,因此只用将metadata复制上去即可。参数gid是要更新的数据对应的在数据库中的结点id,sqlnote是用于获得数据内容 + if (sqlNote != null && sqlNote.isNoteType()) { + MetaData metaData = mMetaHashMap.get(gid); + if (metaData != null) { + metaData.setMeta(gid, sqlNote.getContent()); + GTaskClient.getInstance().addUpdateNode(metaData); + } else { + metaData = new MetaData(); + metaData.setMeta(gid, sqlNote.getContent()); + mMetaList.addChildTask(metaData); + mMetaHashMap.put(gid, metaData); + GTaskClient.getInstance().createTask(metaData); + } + } + } + + private void refreshLocalSyncId() throws NetworkFailureException {//刷新本地便签id,从远程同步 + if (mCancelled) { + return; + } + + // get the latest gtask list + mGTaskHashMap.clear(); + mGTaskListHashMap.clear(); + mMetaHashMap.clear(); + initGTaskList(); + + Cursor c = null; + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type<>? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c != null) { + while (c.moveToNext()) { + String gid = c.getString(SqlNote.GTASK_ID_COLUMN); + Node node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + ContentValues values = new ContentValues(); + values.put(NoteColumns.SYNC_ID, node.getLastModified()); + mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,//进行批量更改,选择参数为NULL,应该可以用insert替换,参数分别为表名和需要更新的value对象。 + c.getLong(SqlNote.ID_COLUMN)), values, null, null); + } else { + Log.e(TAG, "something is missed"); + throw new ActionFailureException( + "some local items don't have gid after sync"); + } + } + } else { + Log.w(TAG, "failed to query local note to refresh sync id"); + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + } + + public String getSyncAccount() { + return GTaskClient.getInstance().getSyncAccount().name; + }//获取同步账号 + + public void cancelSync() { + mCancelled = true; + }//取消同步,置mCancelled为true +}//若需要取消同步,则将mCancelled值设置为真 diff --git a/lhy/GTaskSyncService.java b/lhy/GTaskSyncService.java new file mode 100644 index 0000000..522bdb9 --- /dev/null +++ b/lhy/GTaskSyncService.java @@ -0,0 +1,128 @@ +/* + * 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.remote; + +import android.app.Activity; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.IBinder; + +public class GTaskSyncService extends Service {//service通常用作在后台处理耗时的逻辑,不用与用户进行交互,即使应用被销毁依然可以继续工作。 + public final static String ACTION_STRING_NAME = "sync_action_type";//定义一系列静态变量 + + public final static int ACTION_START_SYNC = 0;//开始同步 + + public final static int ACTION_CANCEL_SYNC = 1; + + public final static int ACTION_INVALID = 2; + + public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";//服务广播的名称 + + public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; + + public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";//进程消息 + + private static GTaskASyncTask mSyncTask = null; + + private static String mSyncProgress = ""; + + private void startSync() {//开始同步 + if (mSyncTask == null) { + mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { + public void onComplete() {//实现了在GTaskASyncTask类中定义的接口onComplete( ) + mSyncTask = null; + sendBroadcast(""); + stopSelf(); + } + }); + sendBroadcast(""); + mSyncTask.execute(); + } + } + + private void cancelSync() {//取消同步 + if (mSyncTask != null) { + mSyncTask.cancelSync(); + } + } + + @Override + public void onCreate() { + mSyncTask = null; + }//初始化一个service + + @Override + public int onStartCommand(Intent intent, int flags, int startId) {//充当重启便签指令 + Bundle bundle = intent.getExtras(); + if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { + switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { + case ACTION_START_SYNC: + startSync(); + break; + case ACTION_CANCEL_SYNC:// 两种情况,开始同步或者取消同步 + cancelSync(); + break; + default: + break; + } + return START_STICKY; + } + return super.onStartCommand(intent, flags, startId); + } + + @Override + public void onLowMemory() {//发送广播 + if (mSyncTask != null) { + mSyncTask.cancelSync(); + } + } + + public IBinder onBind(Intent intent) { + return null; + }//service服务中的绑定操作 + + public void sendBroadcast(String msg) {//发送广播内容 + mSyncProgress = msg; + Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); + intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); + intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); + sendBroadcast(intent); + } + + public static void startSync(Activity activity) {//启动同步 + GTaskManager.getInstance().setActivityContext(activity); + Intent intent = new Intent(activity, GTaskSyncService.class); + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); + activity.startService(intent); + } + + public static void cancelSync(Context context) {//取消同步 + Intent intent = new Intent(context, GTaskSyncService.class); + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); + context.startService(intent); + } + + public static boolean isSyncing() { + return mSyncTask != null; + }//判断当前是否处于同步状态 + + public static String getProgressString() { + return mSyncProgress; + }//返回当前同步状态 +} diff --git a/lhy/MetaData.java b/lhy/MetaData.java new file mode 100644 index 0000000..df043ae --- /dev/null +++ b/lhy/MetaData.java @@ -0,0 +1,82 @@ +/* + * 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;//包名,继承于Task,主要用于记录数据的变化。 + +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONException; +import org.json.JSONObject; + + +public class MetaData extends Task {//创建一个继承 Task 的类MataData + private final static String TAG = MetaData.class.getSimpleName();//调用getSimpleName ()函数,得到类的简写名称存入字符串TAG中 + + private String mRelatedGid = null;//创建私有变量mRelatedGid,并初始化为null + + public void setMeta(String gid, JSONObject metaInfo) {//调用JSONObject库函数put (),Task类中的setNotes ()和setName ()函数,设置数据,即生成元数据库 + try { + metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); + } catch (JSONException e) {//捕捉异常 + Log.e(TAG, "failed to put related gid"); + } + setNotes(metaInfo.toString()); + setName(GTaskStringUtils.META_NOTE_NAME);//设置gtask的名字 + } + + public String getRelatedGid() { + return mRelatedGid; + }//获取相关联的Gid + + @Override + public boolean isWorthSaving() { + return getNotes() != null; + }//判断是否值得存放,即当前数据是否有效,若数据非空则返回真值 + + @Override + public void setContentByRemoteJSON(JSONObject js) {//使用远程json数据对象设置元数据内容 + super.setContentByRemoteJSON(js); + if (getNotes() != null) {//如果数据非空,获取jsono metainfo和相关gid + try { + JSONObject metaInfo = new JSONObject(getNotes().trim()); + mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); + } catch (JSONException e) {//catch中的代码是进行异常处理的 + Log.w(TAG, "failed to get related gid"); + mRelatedGid = null; + } + } + } + + @Override + public void setContentByLocalJSON(JSONObject js) {//使用本地json数据对象设置元数据内容,一般不会用到,若用到,则抛出异常 + // this function should not be called + throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); + } + + @Override + public JSONObject getLocalJSONFromContent() {//从元数据内容中获取本地json对象,抛出异常 + 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/lhy/NetworkFailureException.java b/lhy/NetworkFailureException.java new file mode 100644 index 0000000..2e4ae44 --- /dev/null +++ b/lhy/NetworkFailureException.java @@ -0,0 +1,33 @@ +/* + * 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.exception;//小米便签网络异常处理包,该源文件里定义的所有类都属于这个包 + +public class NetworkFailureException extends Exception { + private static final long serialVersionUID = 2107610287180234136L; +//serialVersionUID相当于java类的身份证。主要用于版本控制。 + public NetworkFailureException() { + super(); + } + + public NetworkFailureException(String paramString) { + super(paramString); + }//调用父类具有相同形参paramString的构造方法 + + public NetworkFailureException(String paramString, Throwable paramThrowable) { + super(paramString, paramThrowable);// 调用父类具有相同形参paramString和paramThrowable的构造方法 + } +} diff --git a/lhy/Node.java b/lhy/Node.java new file mode 100644 index 0000000..f52992d --- /dev/null +++ b/lhy/Node.java @@ -0,0 +1,101 @@ +/* + * 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 org.json.JSONObject; + +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; + + private String mGid;//记录最后一次修改时间 + + private String mName;//记录是否被删除 + + private long mLastModified;//记录最后一次修改时间 + + private boolean mDeleted; + + public Node() {//构造函数,进行初始化,界面没有,名字为空,最后一次修改时间为0(没有修改),表征是否删除。 + mGid = null; + mName = ""; + mLastModified = 0; + mDeleted = false; + } + + public abstract JSONObject getCreateAction(int actionId);//获取创建信息 + + public abstract JSONObject getUpdateAction(int actionId);//获取需要更新活动的ID + + public abstract void setContentByRemoteJSON(JSONObject js);//创建相应的对象,并且实现远端与本地的同步操作 + + public abstract void setContentByLocalJSON(JSONObject js);//创建相应对象进行本地操作 + + public abstract JSONObject getLocalJSONFromContent();//声明JSONObject对象抽象类,从目录中获取本地JSON + + public abstract int getSyncAction(Cursor c);//声明int抽象类,获取同步行为代号 + + 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; + }//函数:返回mGid + + public String getName() { + return this.mName; + }//获取名称 + + public long getLastModified() { + return this.mLastModified; + }//获取最近创建时间标识 + + public boolean getDeleted() { + return this.mDeleted; + }//获取删除标识 + +} diff --git a/lhy/Notes.java b/lhy/Notes.java new file mode 100644 index 0000000..60fd58c --- /dev/null +++ b/lhy/Notes.java @@ -0,0 +1,279 @@ +/* + * 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.data;//声明该文件所属包名 + +import android.net.Uri;//用来识别或者标识资源名称用的一串字符串 +public class Notes {//Notes 类中定义了很多常量,这些常量大多是int型和string型 + public static final String AUTHORITY = "micode_notes";//定义了一个权限名称,看作为数字证书 + public static final String TAG = "Notes";//设置标签,表示APP的名称是Notes + public static final int TYPE_NOTE = 0; + public static final int TYPE_FOLDER = 1; + public static final int TYPE_SYSTEM = 2;//对三种TYPE:NOTE,FOLDER,SYSTEM进行变量定义 + + /** + * Following IDs are system folders' identifiers + * {@link Notes#ID_ROOT_FOLDER } is default folder + * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder + * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records + */ + public static final int ID_ROOT_FOLDER = 0;//回收站目录 + public static final int ID_TEMPARAY_FOLDER = -1;//不属于文件夹的便签 + public static final int ID_CALL_RECORD_FOLDER = -2;//设定背景 + public static final int ID_TRASH_FOLER = -3;//回收站文件夹 + + public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";//文件夹编号 + public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";//背景颜色 + public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";//插件的大小 + public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";//大号桌面插件 + public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";//定义文件夹的名称 + public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";//定义call_date的ID + + public static final int TYPE_WIDGET_INVALIDE = -1;//定义查询便签和文件夹的指针 + public static final int TYPE_WIDGET_2X = 0;//定义查找数据的指针 + public static final int TYPE_WIDGET_4X = 1;//4*4桌面大小 + + public static class DataConstants {//DataContants类:存放textnotes和callnotes地址 + public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;//定义变量NOTE,用来识别text_note的存放地址 + public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;//DataContants类:存放TextNotes和CallNotes地址 + } + + /** + * Uri to query all notes and folders + */ + public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");//URI常量,方便进行系统查询 + + /** + * Uri to query data + */ + public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");//URI常量,方便查询数据 + + public interface NoteColumns {//定义了类NoteColumns的部分参数 + /** + * The unique ID for a row + *

Type: INTEGER (long)

+ */ + public static final String ID = "_id";//每一行的ID + + /** + * The parent's id for note or folder + *

Type: INTEGER (long)

+ */ + public static final String PARENT_ID = "parent_id";//父节点的ID + + /** + * Created data for note or folder + *

Type: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date";//用来保存一些创建信息,比如时间 + + /** + * Latest modified date + *

Type: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date";//提醒的日期 + + + /** + * Alert date + *

Type: INTEGER (long)

+ */ + public static final String ALERTED_DATE = "alert_date";//储存 提醒时间 + + /** + * Folder's name or text content of note + *

Type: TEXT

+ */ + public static final String SNIPPET = "snippet";//文件夹的名字或者便签内容 + + /** + * Note's widget id + *

Type: INTEGER (long)

+ */ + public static final String WIDGET_ID = "widget_id";//note的布局ID + + /** + * Note's widget type + *

Type: INTEGER (long)

+ */ + public static final String WIDGET_TYPE = "widget_type";//小部件类型 + + /** + * Note's background color's id + *

Type: INTEGER (long)

+ */ + public static final String BG_COLOR_ID = "bg_color_id";//便签背景颜色的ID + + /** + * For text note, it doesn't has attachment, for multi-media + * note, it has at least one attachment + *

Type: INTEGER

+ */ + public static final String HAS_ATTACHMENT = "has_attachment";//设置附件是否存在 + + /** + * Folder's count of notes + *

Type: INTEGER (long)

+ */ + public static final String NOTES_COUNT = "notes_count";//文件夹中的便签数量 + + /** + * The file type: folder or note + *

Type: INTEGER

+ */ + public static final String TYPE = "type";//设置文件的类型 + + /** + * The last sync id + *

Type: INTEGER (long)

+ */ + public static final String SYNC_ID = "sync_id";//最后一次同步的ID + + /** + * Sign to indicate local modified or not + *

Type: INTEGER

+ */ + public static final String LOCAL_MODIFIED = "local_modified";//本地信号是否修改 + + /** + * Original parent id before moving into temporary folder + *

Type : INTEGER

+ */ + public static final String ORIGIN_PARENT_ID = "origin_parent_id";//移动到临时文件夹之前的父文件夹 + + /** + * The gtask id + *

Type : TEXT

+ */ + public static final String GTASK_ID = "gtask_id";//后台任务ID + + /** + * The version code + *

Type : INTEGER (long)

+ */ + public static final String VERSION = "version";// 版本代号 + } + + public interface DataColumns {//定义了接口类,在数据库的创建、查询中需要DataColumns的所有信息,主要存储便签数据的信息。 + /** + * The unique ID for a row + *

Type: INTEGER (long)

+ */ + public static final String ID = "_id";//定义DataColumns的部分常量 + + /** + * The MIME type of the item represented by this row. + *

Type: Text

+ */ + public static final String MIME_TYPE = "mime_type";// 这一排表示的项目的MIME类型。MIME类型包含视频、图像、文本、音频、应用程序等数据。 + + /** + * The reference id to note that this data belongs to + *

Type: INTEGER (long)

+ */ + public static final String NOTE_ID = "note_id";//便签ID + + /** + * Created data for note or folder + *

Type: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + // 创建日期 + /** + * Latest modified date + *

Type: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + //最新的修改时间 + /** + * Data's content + *

Type: TEXT

+ */ + public static final String CONTENT = "content";//数据包含的内容 + + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * integer data type + *

Type: INTEGER

+ */ + public static final String DATA1 = "data1";//文本内容的数据结构 + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * integer data type + *

Type: INTEGER

+ */ + public static final String DATA2 = "data2";//定义了文本内容的类型 + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA3 = "data3";//定义常量 + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA4 = "data4"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA5 = "data5";//.继承DataColumns的类,组织电话内容数据结构 + } + + public static final class TextNote implements DataColumns {//文本笔记,通过定义的接口集成了上面的属性 + /** + * Mode to indicate the text in check list mode or not + *

Type: Integer 1:check list mode 0: normal mode

+ */ + public static final String MODE = DATA1;//模式数据为data1类型 + + public static final int MODE_CHECK_LIST = 1;//note中内容的类型 + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";//定义内容类型 + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";//内容项目类型 + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");//通过uri的parse方法访问资源 + } + + public static final class CallNote implements DataColumns {//记录通话数据的表头 + /** + * Call date for this record + *

Type: INTEGER (long)

+ */ + public static final String CALL_DATE = DATA1;//存放通话时间信息到DATA1中 + + /** + * Phone number for this record + *

Type: TEXT

+ */ + public static final String PHONE_NUMBER = DATA3;//电话号码为data3类型 + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";//修改CONTENT_TYPE属性,即内容类型 + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";//内容项目类型 + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");// 访问uri,并将解析结果保存于CONTENT_URI属性 + } +} diff --git a/lhy/NotesDatabaseHelper.java b/lhy/NotesDatabaseHelper.java new file mode 100644 index 0000000..738ef1c --- /dev/null +++ b/lhy/NotesDatabaseHelper.java @@ -0,0 +1,362 @@ +/* + * 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.data;//声明包 + +import android.content.ContentValues; +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns;//数据库操作中保存数据信息 + + +public class NotesDatabaseHelper extends SQLiteOpenHelper {//继承于SQLiteOpenHelper的类NotesDatabaseHelper,用于实现对便签或者 文件的数据库操作,例如删除便签 + private static final String DB_NAME = "note.db";//定义数据库的名称为“note.db” + + private static final int DB_VERSION = 4;//数据库版本号 + + public interface TABLE {//将接口分成note和data + public static final String NOTE = "note";//创建便签表的数据库 + + public static final String DATA = "data";//数据库中需要存储的项目的名称,就类似创建一个表格的表头的内容。 + } + + private static final String TAG = "NotesDatabaseHelper";//存储便签编号的一个数据表格 + + private static NotesDatabaseHelper mInstance;//创建类NotesDatabaseHelper的对象——mInstance + + private static final String CREATE_NOTE_TABLE_SQL =//文件夹增加Note后需要更改的数据的表格 + "CREATE TABLE " + TABLE.NOTE + "(" +//文件夹减少Note后需要更改的数据的表格 + NoteColumns.ID + " INTEGER PRIMARY KEY," +//文件夹插入Note后需要更改的数据的表格 + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +//文件夹删除Note后需要更改的数据的表格 + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +//应用界面颜色选择 + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +// 创建时间数据 + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +//文件夹中便签数据初始化为0 + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +//Note中数据删除更改的数据表格。 + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +//数据库中需要存储的项目的名称,就相当于创建一个表格的表头的内容 + ")"; + + private static final String CREATE_DATA_TABLE_SQL =//创建SQL的data表 + "CREATE TABLE " + TABLE.DATA + "(" +//note删除数据触发 + DataColumns.ID + " INTEGER PRIMARY KEY," + + DataColumns.MIME_TYPE + " TEXT NOT NULL," + + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA1 + " INTEGER," + + DataColumns.DATA2 + " INTEGER," + + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + + ")";//文件夹删除note触发 + + private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =//文件夹移除note时触发垃圾回收 + "CREATE INDEX IF NOT EXISTS note_id_index ON " + + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";//存储便签编号的一个数据表格 +//以下几个都是在创建触发器(trigger)。触发器是一些在特定的数据库事件(database-event) 发生时自动进行的数据库操作 + /** + * Increase folder's note count when move note to the folder + *///Increase增加文件Decrease减少文件 + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =//将新的note移入该文件夹时,更新该文件夹note的数量 + "CREATE TRIGGER increase_folder_count_on_update "+ + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END";// 在文件夹中移入一个Note之后需要更改的数据的表格 + + /** + * Decrease folder's note count when move note from folder + */ + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =//notes从文件夹移除后,数量减一,并且进行一系列的操作 + "CREATE TRIGGER decrease_folder_count_on_update " + + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +//在文件夹中移出一个Note之后需要更改的数据的表格 + " END"; +//便签从文件夹移除后,数量减一,并且进行一系列的操作进行更新 + /** + * Increase folder's note count when insert new note to the folder + */ + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =//在文件夹中新建notes后,数量加1 + "CREATE TRIGGER increase_folder_count_on_insert " + + " AFTER INSERT ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END";//在文件夹中插入一个Note之后需要更改的数据的表格 + + /** + * Decrease folder's note count when delete note from the folder + */ + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = + "CREATE TRIGGER decrease_folder_count_on_delete " +//定义一个更新文件夹中便签数目的SQL语句。当有便签从该文件夹中删除时使用 + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0;" + + " END";//在文件夹中删除一个Note之后需要更改的数据的表格 + + /** + * Update note's content when insert data with type {@link DataConstants#NOTE} + *///构建一条SQL语句,用于实现在note中输入data后,进行当前状态的更新 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = + "CREATE TRIGGER update_note_content_on_insert " + + " AFTER INSERT ON " + TABLE.DATA + + " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END";//在文件夹中对一个Note导入新的数据之后需要更改的数据的表格 + + /** + * Update note's content when data with {@link DataConstants#NOTE} type has changed + *///在data数据改变后对整个应用进行数据刷新 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = + "CREATE TRIGGER update_note_content_on_update " + + " AFTER UPDATE ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END";//Note数据被修改后需要更改的数据的表格 + + /** + * Update note's content when data with {@link DataConstants#NOTE} type has deleted + *///在数据被删除时,进行更新。 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = + "CREATE TRIGGER update_note_content_on_delete " + + " AFTER delete ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=''" + + " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + + " END";//Note数据被删除后需要更改的数据的表格 + + /** + * Delete datas belong to note which has been deleted + *///实现在note被删除后,将该note对应的data删除的功能 + private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = + "CREATE TRIGGER delete_data_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.DATA + + " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + + " END";//删除已删除的便签的数据后需要更改的数据的表格 + + /** + * Delete notes belong to folder which has been deleted + *///用于实现在文件夹被删除后,将该文件夹中的note删除的功能 + private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = + "CREATE TRIGGER folder_delete_notes_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END";//删除已删除的文件夹的便签后需要更改的数据的表格 + + /** + * Move notes belong to folder which has been moved to trash folder + *///恢复删除的notes,并且更新一些数据 + private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =//将垃圾文件夹里的note还原,并更新数据表格 + "CREATE TRIGGER folder_move_notes_on_trash " + + " AFTER UPDATE ON " + TABLE.NOTE + + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END";//还原垃圾桶中便签后需要更改的数据的表格 + + public NotesDatabaseHelper(Context context) { + super(context, DB_NAME, null, DB_VERSION); + }//构造函数,传入数据库的名称和版本 + + public void createNoteTable(SQLiteDatabase db) {//标注出数据库的名称和版本 + db.execSQL(CREATE_NOTE_TABLE_SQL);//创建表头 + reCreateNoteTableTriggers(db); + createSystemFolder(db); + Log.d(TAG, "note table has been created"); + }//创建表格,存储标签属性 + + private void reCreateNoteTableTriggers(SQLiteDatabase db) {//创建一个储存标签属性的表格 + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");//创建增加文件夹的触发器 + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");//创建减少文件夹的触发器 + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); +//在删除原来的触发器后,创建新的触发器 + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);//创建自己的数据库操作 + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);//创建更新减少文件夹的触发器 + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); + db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER); + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER); + db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);//创建删除notes的触发器 + db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);//创建将回收站中的notes还原的触发器 + }//execSQL通过添加sql语句可以执行sql操作 +//execSQL通过添加sql语句可以执行sql操作 + private void createSystemFolder(SQLiteDatabase db) {//创建几个系统文件夹 + ContentValues values = new ContentValues();//向数据库中插入数据,就要新建一个contentValues的对象。但只能存储基本类型数据 + + /** + * call record foler for call notes + *///储存呼叫记录的文件夹 + values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);//放入数据(NoteColumns的id,呼叫记录文件夹的ld) + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values);//插入ContantValues对象 + + /** + * root folder which is default folder + *///对默认文件夹(根文件夹)进行操作 + values.clear();//对根文件夹(默认文件夹)进行修改,首先先把values容器清空,在对他添加内容,最后放入数据库 + values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);//将数据库ID与通话记录文件夹ID形成映射 + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);//将数据库中数据类型与通话记录文件夹类型形成映射 + db.insert(TABLE.NOTE, null, values); + + /** + * temporary folder which is used for moving note + *///移动note的临时文件夹 + values.clear();// 临时文件夹的修改操作 + values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);//将数据库ID与通话记录文件夹ID形成映射 + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + /** + * create trash folder + *///创建垃圾文件夹 + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);//将数据库ID与通话记录文件夹ID形成映射 + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + public void createDataTable(SQLiteDatabase db) {//将数据库ID与通话记录文件夹ID形成映射 + db.execSQL(CREATE_DATA_TABLE_SQL);//用来重新创建note对应的data的表项 + reCreateDataTableTriggers(db);//重新建立数据表的触发器 + db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); + Log.d(TAG, "data table has been created"); + } + + private void reCreateDataTableTriggers(SQLiteDatabase db) {//删除重建表格 + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); + + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); + } + + static synchronized NotesDatabaseHelper getInstance(Context context) {//如果NotesDatabaseHelper的实例创建失败,那就重新建一个,重新分配内从空间 + if (mInstance == null) { + mInstance = new NotesDatabaseHelper(context); + } + return mInstance; + } + + @Override + public void onCreate(SQLiteDatabase db) {//在NotesDatabaseHelper对象生命周期开始时创建Note table和Datatable + createNoteTable(db);//函数:生命周期开始的时候oncreate 被调用,这里对其进行重写,加入notes表单和数据表单 + createDataTable(db); + }//实现两个表格 + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//数据库版本的更新 + boolean reCreateTriggers = false;//是否重新建立note及data的表项 + boolean skipV2 = false; + + if (oldVersion == 1) {//代码段:如果版本是一则更新到版本二 + upgradeToV2(db); + skipV2 = true; // this upgrade including the upgrade from v2 to v3 + oldVersion++; + } + + if (oldVersion == 2 && !skipV2) {//判断旧版本是不是2号版本且没有跳过2号版本,就更新到3号版本 + upgradeToV3(db); + reCreateTriggers = true; + oldVersion++; + } + + if (oldVersion == 3) {//v3-v4 + upgradeToV4(db); + oldVersion++; + } + + if (reCreateTriggers) {//重新创建的同时,创建新的note table和datatable + reCreateNoteTableTriggers(db); + reCreateDataTableTriggers(db); + } + + if (oldVersion != newVersion) {//旧版本与最新版本不一致,抛出异常 + throw new IllegalStateException("Upgrade notes database to version " + newVersion + + "fails"); + } + } + + private void upgradeToV2(SQLiteDatabase db) {//将数据库的版本更新到V2 + db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); + db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); + createNoteTable(db); + createDataTable(db); + } + + private void upgradeToV3(SQLiteDatabase db) {//gengxinv3 + // drop unused triggers + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); + // add a column for gtask id + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID + + " TEXT NOT NULL DEFAULT ''"); + // add a trash system folder在数据库的便签(note)表单中加上一个默认的垃圾文件夹,不用用户自己创建 + ContentValues values = new ContentValues();//添加垃圾系统文件夹 + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values);//插入到表中 + } + + private void upgradeToV4(SQLiteDatabase db) {//数据库版本升级到V4 + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION + + " INTEGER NOT NULL DEFAULT 0"); + } +} diff --git a/lhy/NotesProvider.java b/lhy/NotesProvider.java new file mode 100644 index 0000000..17dbf7c --- /dev/null +++ b/lhy/NotesProvider.java @@ -0,0 +1,305 @@ +/* + * 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.data;//标注该文件所属的软件包 + + +import android.app.SearchManager; +import android.content.ContentProvider; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Intent; +import android.content.UriMatcher; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.net.Uri; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE;// SearchManager 的作用是提供对系统搜索服务的访问 + + +public class NotesProvider extends ContentProvider {//为存储和获取数据提供接口。可以在不同的应用程序之间共享数据 + private static final UriMatcher mMatcher;//UriMatcher是Android提供的用来操作Uri的工具类 + + private NotesDatabaseHelper mHelper;//数据库辅助类的实例化 + + private static final String TAG = "NotesProvider"; + + private static final int URI_NOTE = 1; + private static final int URI_NOTE_ITEM = 2; + private static final int URI_DATA = 3; + private static final int URI_DATA_ITEM = 4; + + private static final int URI_SEARCH = 5; + private static final int URI_SEARCH_SUGGEST = 6; + + static {//初始化mMatcher UriMatcher类 + mMatcher = new UriMatcher(UriMatcher.NO_MATCH);//创建UriMatcher时,调用UriMatcher。UriMatcher.NO_MATCH表示不匹配任何路径 + mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); + mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); + mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); + mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); + mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);//SUGGEST_URI_PATH_QUERY 并不属于URI的一部分,而应是用于指向此路径的常量。 + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); + }//注册完需要匹配的Uri后,就可以使用sMatcher.match(uri)方法对输入的Uri进行匹配 + + /** + * x'0A' represents the '\n' character in sqlite. For title and content in the search result, + * we will trim '\n' and white space in order to show more information. + */ + private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","//声明 NOTES_SEARCH_PROJECTION + + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","//设置表明额外数据、推荐显示的文本、图标、操作、数据 + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","//TEXT_1是将该字段作为安卓搜索框中建议显示的文本。如果每个建议想显示两行数据,还有SearchManager.SUGGEST_COLUMN_TEXT_2 + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," + + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," + + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + + private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION//构造数据库查询语句,用于通过notes的片段查询notes + + " FROM " + TABLE.NOTE//在特定表中某一字段检索特定子串 + + " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + + @Override + public boolean onCreate() {//创建一个便签数据库助手helper + mHelper = NotesDatabaseHelper.getInstance(getContext());//对mHelper进行实例化 + return true; + } + + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,//在数据库中查询uri,然后返回uri的位置 + String sortOrder) { + Cursor c = null; + SQLiteDatabase db = mHelper.getReadableDatabase(); + String id = null; + switch (mMatcher.match(uri)) { + case URI_NOTE: + c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_NOTE_ITEM://查询便签条目 + id = uri.getPathSegments().get(1);//获取uri中1号描述符 + c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_DATA://根据日期进行查询 + c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_DATA_ITEM://查询id对应的具体数据 + id = uri.getPathSegments().get(1); + c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_SEARCH://匹配到搜索 + case URI_SEARCH_SUGGEST: + if (sortOrder != null || projection != null) { + throw new IllegalArgumentException( + "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");//在查询时不能指定排序参数(sortOrder)、查询条件(selection)、占位符(selectionArgs)、要查询的表(projection) + } + + String searchString = null;//搜索所得的内容 + if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { + if (uri.getPathSegments().size() > 1) { + searchString = uri.getPathSegments().get(1); + } + } else {//利用URI的getQueryParameter方法可以获取字符串参数 + searchString = uri.getQueryParameter("pattern"); + } + + if (TextUtils.isEmpty(searchString)) {//格式化搜索的字符串 + return null; + } + + try {//非法状态异常 + searchString = String.format("%%%s%%", searchString); + c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, + new String[] { searchString }); + } catch (IllegalStateException ex) { + Log.e(TAG, "got exception: " + ex.toString()); + } + break; + default://如果以上多个case均不命中,则抛出未知uri的异常 + throw new IllegalArgumentException("Unknown URI " + uri); + } + if (c != null) {//若getContentResolver发生变化,就接收通知 + c.setNotificationUri(getContext().getContentResolver(), uri); + } + return c; + } + + @Override + public Uri insert(Uri uri, ContentValues values) {//插入一个uri,uri是一个用于标识某一互联网资源名称的字符串 + SQLiteDatabase db = mHelper.getWritableDatabase();//获得可写的数据库 + long dataId = 0, noteId = 0, insertedId = 0; + switch (mMatcher.match(uri)) {//数据库的插入,用来存放数据 + case URI_NOTE: + insertedId = noteId = db.insert(TABLE.NOTE, null, values); + break; + case URI_DATA://如果是数据类型,且其id能对应于某个便签id,则插入 + if (values.containsKey(DataColumns.NOTE_ID)) { + noteId = values.getAsLong(DataColumns.NOTE_ID); + } else {//错误的数据格式,没有note的id + Log.d(TAG, "Wrong data format without note id:" + values.toString()); + } + insertedId = dataId = db.insert(TABLE.DATA, null, values); + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri);//未知uri异常 + } + // Notify the note uri + if (noteId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);//把noteId加到URI的尾部,连接成新的URI + } + + // Notify the data uri + if (dataId > 0) {//更新data + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);//返回插入的uri的路径 + } + + return ContentUris.withAppendedId(uri, insertedId);//返回插入的uri的路径 + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) {//从数据库中删除uri + int count = 0; + String id = null; + SQLiteDatabase db = mHelper.getWritableDatabase(); + boolean deleteData = false; + switch (mMatcher.match(uri)) { + case URI_NOTE://查找到不同类型的相应的uri后在数据库中删除 + selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; + count = db.delete(TABLE.NOTE, selection, selectionArgs); + break; + case URI_NOTE_ITEM://如果是便签条目,获取对应id,且对应id非系统文件夹,则删除 + id = uri.getPathSegments().get(1); + /** + * ID that smaller than 0 is system folder which is not allowed to + * trash + */ + long noteId = Long.valueOf(id);//.语句:将string类型转换为long类型 + if (noteId <= 0) { + break; + } + count = db.delete(TABLE.NOTE, + NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + break; + case URI_DATA: + count = db.delete(TABLE.DATA, selection, selectionArgs);//删除数据 + deleteData = true; + break; + case URI_DATA_ITEM://删除uri标识的指定数据 + id = uri.getPathSegments().get(1); + count = db.delete(TABLE.DATA, + DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + deleteData = true; + break; + default://匹配失败,则报错 + throw new IllegalArgumentException("Unknown URI " + uri); + } + if (count > 0) {//对上述的操作进行判断,上述更改发生,count>0 + if (deleteData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null);//对所有修改进行通知 + } + return count; + } + + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {//数据库更新uri + int count = 0; + String id = null; + SQLiteDatabase db = mHelper.getWritableDatabase(); + boolean updateData = false; + switch (mMatcher.match(uri)) { + case URI_NOTE: + increaseNoteVersion(-1, selection, selectionArgs);//升级note版本 + count = db.update(TABLE.NOTE, values, selection, selectionArgs); + break; + case URI_NOTE_ITEM: + id = uri.getPathSegments().get(1); + increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); + count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id//对notes item uri进行更新 + + parseSelection(selection), selectionArgs); + break; + case URI_DATA://对多个数据进行修改 + count = db.update(TABLE.DATA, values, selection, selectionArgs); + updateData = true; + break; + case URI_DATA_ITEM: + id = uri.getPathSegments().get(1);//获取该项目id并将其uri更新 + count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); + updateData = true; + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + + if (count > 0) {//代码段:通知观察者,数据更新 + if (updateData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } +//将字符串解析成规定格式 + private String parseSelection(String selection) { + return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); + } + + private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { + StringBuilder sql = new StringBuilder(120); + sql.append("UPDATE "); + sql.append(TABLE.NOTE); + sql.append(" SET "); + sql.append(NoteColumns.VERSION); + sql.append("=" + NoteColumns.VERSION + "+1 "); + + if (id > 0 || !TextUtils.isEmpty(selection)) {//操作条件selection不为空或者ID>0,增加WHERE语句 + sql.append(" WHERE "); + } + if (id > 0) {//如果id为正,更新id + sql.append(NoteColumns.ID + "=" + String.valueOf(id)); + } + if (!TextUtils.isEmpty(selection)) {//输入的文本非空的条件下输入到数据库中 + String selectString = id > 0 ? parseSelection(selection) : selection; + for (String args : selectionArgs) { + selectString = selectString.replaceFirst("\\?", args);//用args替换掉?的占位符 + } + sql.append(selectString);//增加selectString语句 + } + + mHelper.getWritableDatabase().execSQL(sql.toString());//execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句 + } + + @Override + public String getType(Uri uri) { + // TODO Auto-generated method stub + return null;//初始化,返回一个空指针 + } + +} diff --git a/lhy/SqlData.java b/lhy/SqlData.java new file mode 100644 index 0000000..c330d58 --- /dev/null +++ b/lhy/SqlData.java @@ -0,0 +1,189 @@ +/* + * 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.content.ContentResolver; +import android.content.ContentUris; +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.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE; +import net.micode.notes.gtask.exception.ActionFailureException; + +import org.json.JSONException; +import org.json.JSONObject; + + +public class SqlData {//数据库中基本数据类:读取数据、获取数据库中数据、提交数据到数据库 + private static final String TAG = SqlData.class.getSimpleName();//调用getSimpleName ()函数来得到类的简写名称存入字符串TAG中 + + private static final int INVALID_ID = -99999;//将得到类的简写名称存入字符串TAG中,为mDataId置初始值-99999 + + public static final String[] PROJECTION_DATA = new String[] {//新建一个字符串数组,集合了interface DataColumns中所有SF常量 + DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,//获得数据列id,mime类型,内容,1类型数据,3类型数据 + DataColumns.DATA3 + }; + + public static final int DATA_ID_COLUMN = 0;//以下五个变量作为sql表中5列的编号 + + 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;//定义的一些私有全局变量,可以与sqlNote中的变量相对应分析 + + 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) {//第一种SQLData的构造方式,只从上下文获取,初始化其中的变量 + mContentResolver = context.getContentResolver(); + mIsCreate = true; + mDataId = INVALID_ID; + mDataMimeType = DataConstants.NOTE; + mDataContent = ""; + mDataContentData1 = 0; + mDataContentData3 = "";//数据类型 + mDiffDataValues = new ContentValues();//创建内容 + } + + public SqlData(Context context, Cursor c) {//构造函数,初始化数据,参数类型分别为 Context 和 Cursor + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(c); + mDiffDataValues = new ContentValues(); + } + + private void loadFromCursor(Cursor c) {//构造函数,初始化数据,参数类型分别为 Context 和 Cursor + mDataId = c.getLong(DATA_ID_COLUMN);//调用cursor类的方法,获取数据id,参数为id长度 + 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); + } + + public void setContent(JSONObject js) throws JSONException {//设置共享数据,并且抛出JSON类型的异常与处理机制 + long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;//设置数据 id,如果传入的 JSONObject 对象中存在DataColumns.ID则获取并设置,否则设为INVALID_ID + if (mIsCreate || mDataId != dataId) {//如果是根据目录创建的或者当前数据的ID与元数据的ID不符,那么发送更新此ID 的请求 + mDiffDataValues.put(DataColumns.ID, dataId); + } + mDataId = dataId;//与共享数据库同步后,共享数据ID就等于数据ID + + String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)//若json中有MIME_TYPE这一项,则将其获取,否则,将其定义为notes类中定义的文本类型 + : DataConstants.NOTE; + if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {//如果共享数据文本类型与数据文本类型不同,则将原有的数据类型,放入共享库中 + mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); + } + mDataMimeType = dataMimeType; + + String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; + if (mIsCreate || !mDataContent.equals(dataContent)) {//对比DataContent,并更新contentValue中的DataContent + mDiffDataValues.put(DataColumns.CONTENT, dataContent); + } + mDataContent = dataContent;//共享数据同步后,共享数据内容等于该数据内容 + + long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;// 如果传入的JSONObject对象有DataColumn.DATA1一项,那么将其获取,否则。将其设置为0。 + if (mIsCreate || mDataContentData1 != dataContentData1) { + mDiffDataValues.put(DataColumns.DATA1, dataContentData1); + } + mDataContentData1 = dataContentData1; + + String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; + if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { + mDiffDataValues.put(DataColumns.DATA3, dataContentData3); + } + mDataContentData3 = dataContentData3; + } +//获取共享数据内容及提供异常抛出与处理机制 + public JSONObject getContent() throws JSONException { + if (mIsCreate) { + Log.e(TAG, "it seems that we haven't created this in database yet");//判断是否创建数据表 + return null; + } + JSONObject js = new JSONObject();//将相关数据放入新创建的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; + } +//将当前数据提交到数据库 + public void commit(long noteId, boolean validateVersion, long version) {//commit 函数用于把当前所做的修改保存到数据库 + + if (mIsCreate) {//判断是否是第一种SqlData构造方式 + if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {//如果该id是无效id且在共享数据中不存在该数据id对应的键,则从共享数据中移除 + mDiffDataValues.remove(DataColumns.ID);//删除数据 + } + + mDiffDataValues.put(DataColumns.NOTE_ID, noteId);//加入的ID有效,也就是操作有效,则数据库加入这个note的ID,这条data对应在这个note的ID下 + Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);//在note的资源标识下加入data数据 + try {//上一句实现的是URI到Uri的转换/将路径转换为Long型,附识给当前id + mDataId = Long.valueOf(uri.getPathSegments().get(1));//获取有效便签id并创建 + } catch (NumberFormatException e) {//如果转换出错则日志中显示错误“获取note的ID出错” + Log.e(TAG, "Get note id error :" + e.toString());//获取note id错误,e.toString()获取异常类型和异常详细消息 + throw new ActionFailureException("create note failed"); + } + } else { + if (mDiffDataValues.size() > 0) {//若共享数据存在,则通过内容解析器更新关于新URI的共享数据 + int result = 0; + if (!validateVersion) { + result = mContentResolver.update(ContentUris.withAppendedId(//如果版本已确认,则结果还记录下所在note的Id,以及版本号 + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); + } else {//如果版本确认了,则从数据库中选取对应版本的id进行更新 + result = mContentResolver.update(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, + " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { + String.valueOf(noteId), String.valueOf(version) + });//更新不存在,可能是用户在同步时已更新 + } + if (result == 0) { + Log.w(TAG, "there is no update. maybe user updates note when syncing"); + } + } + } + + mDiffDataValues.clear();//回到初始化,清空,表示已经更新 + mIsCreate = false; + } + + public long getId() { + return mDataId; + } +} diff --git a/lhy/SqlNote.java b/lhy/SqlNote.java new file mode 100644 index 0000000..689b1be --- /dev/null +++ b/lhy/SqlNote.java @@ -0,0 +1,505 @@ +/* + * 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; + + +public class SqlNote {//调用getSimpleName ()函数得到类的简写名称存入字符串TAG中 + private static final String TAG = SqlNote.class.getSimpleName(); + + private static final int INVALID_ID = -99999;//将INVALID_ID 初始化为-99999 + + public static final String[] PROJECTION_NOTE = new String[] {//集合了interface NoteColumns中所有17个SF常量 + 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 + };//以下设置17个列的编号 + + public static final int ID_COLUMN = 0;//提醒时间 + + public static final int ALERTED_DATE_COLUMN = 1;//note的背景颜色 + + 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; + + public static final int PARENT_ID_COLUMN = 7; + + public static final int SNIPPET_COLUMN = 8; + + public static final int TYPE_COLUMN = 9; + + public static final int WIDGET_ID_COLUMN = 10; + + public static final int WIDGET_TYPE_COLUMN = 11; + + public static final int SYNC_ID_COLUMN = 12; + + public static final int LOCAL_MODIFIED_COLUMN = 13; + + public static final int ORIGIN_PARENT_ID_COLUMN = 14; + + public static final int GTASK_ID_COLUMN = 15; + + public static final int VERSION_COLUMN = 16; + + private Context mContext;//以下定义了17个内部变量,其中12个可以由content获得,5个需要初始化为0或者new + + private ContentResolver mContentResolver; + + private boolean mIsCreate; + + private long mId;//通过ArrayList记录note中的data + + 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) {//构造函数,参数只有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();//新建一个data的列表 + } + + public SqlNote(Context context, Cursor c) {//构造函数,参数有context和cursor,对cursor指向的对象进行初始化 + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(c); + mDataList = new ArrayList(); + if (mType == Notes.TYPE_NOTE)//如果是note类型,则调用下面的 loadDataContent()函数,加载数据内容 + loadDataContent(); + mDiffNoteValues = new ContentValues(); + } + + public SqlNote(Context context, long id) {//第三种构造方式,采用context和id + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(id);//调用下面的 loadFromCursor函数,通过ID从光标处加载数据 + mDataList = new ArrayList(); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + mDiffNoteValues = new ContentValues(); + + } + + private void loadFromCursor(long id) {//通过id从光标处加载数据 + Cursor c = null; + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",//通过id获取ContentResolver中的相应内容,并赋给cursor + new String[] { + String.valueOf(id) + }, null);//如果获取成功,则cursor移动到下一条记录,并加载该记录 + 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); + } +//获取ID对应content内容,如果查询到该note的id确实有对应项,即cursor有对应,获取ID对应content内容 + private void loadDataContent() {//通过content机制获取共享数据并加载到数据库当前游标处 + Cursor c = null; + mDataList.clear(); + try {//获取ID对应content内容 + c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,//获得该ID对应的数据内容 + "(note_id=?)", new String[] { + String.valueOf(mId) + }, null);//查询到该note的id确实有对应项,即cursor有对应 + if (c != null) { + if (c.getCount() == 0) { + Log.w(TAG, "it seems that the note has not data"); + return; + } + while (c.moveToNext()) {//记录数量不为0,则循环直到记录不存在,不断地取出记录放到DataList中 + SqlData data = new SqlData(mContext, c); + mDataList.add(data); + } + } else { + Log.w(TAG, "loadDataContent: cursor = null"); + } + } finally {//论如何,最后需要关闭数据库游标 + if (c != null) + c.close(); + } + } + + public boolean setContent(JSONObject js) {//设置通过content机制共享的数据信息 + 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) {//文件夹只能更新摘要和类型 + // for folder we can only update the snnipet and type + String snippet = note.has(NoteColumns.SNIPPET) ? note//语句:如果共享数据存在摘要,则将其赋给snippet变量,否则该变量为空 + .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)//以下操作都和上面对snippet的操作一样,一起根据共享的数据设置SqlNote内容的上述17项 + : Notes.TYPE_NOTE; + if (mIsCreate || mType != type) {//如果是新建的或 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; + + int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note//获取数据的背景颜色 + .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); + if (mIsCreate || mBgColorId != bgColorId) {//如果只是通过上下文对note进行数据库操作,或者该背景颜色与原背景颜色不相同, + 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) {//如果只是通过上下文对note进行数据库操作,或者该创建日期与原创建日期不相同, + mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);//将该创建日期保存在mDiffNoteValue这个变量中,说明这两个值不相同 + } + mCreatedDate = createDate;//将该创建日期覆盖原创建日期 + + int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note + .getInt(NoteColumns.HAS_ATTACHMENT) : 0; + if (mIsCreate || mHasAttachment != hasAttachment) {//如果只是通过上下文对note进行数据库操作,或者该有无附件的布尔值与原有无附件的布尔值不相同, + 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) {//如果只是通过上下文对note进行数据库操作,或者该修改日期与原修改日期不相同, + mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); + } + mModifiedDate = modifiedDate; + + 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)) {//如果只是通过上下文对note进行数据库操作,或者该文本片段与原文本片段不相同, + 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; + + 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);//将该小部件ID保存在mDiffNoteValue这个变量中,说明这两个值不相同 + } + 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) {//如果只是通过上下文对note进行数据库操作,或者该原始父文件夹ID与原原始父文件夹ID不相同, + mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); + } + mOriginParent = originParent; + + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + SqlData sqlData = null; + if (data.has(DataColumns.ID)) {//该数据ID对应的数据如果存在,将对应的数据存在数据库中 + long dataId = data.getLong(DataColumns.ID); + for (SqlData temp : mDataList) { + if (dataId == temp.getId()) { + sqlData = temp; + } + } + } + + if (sqlData == null) { + sqlData = new SqlData(mContext); + mDataList.add(sqlData); + } + + sqlData.setContent(data);//最后为数据库数据进行设置 + } + } + } catch (JSONException e) {//出现JSONException时,日志显示错误,同时打印堆栈轨迹 + Log.e(TAG, e.toString());//获取异常类型和异常详细消息 + e.printStackTrace(); + return false; + } + return true; + } +//获取content机制提供的数据并加载到note中 + public JSONObject getContent() {//获取content机制提供的数据并加载到note中 + try { + JSONObject js = new JSONObject(); + + if (mIsCreate) { + Log.e(TAG, "it seems that we haven't created this in database yet"); + return null; + } + + JSONObject note = new JSONObject();//新建变量note用于传输共享数据 + if (mType == Notes.TYPE_NOTE) {//note类型 + note.put(NoteColumns.ID, mId); + note.put(NoteColumns.ALERTED_DATE, mAlertDate); + note.put(NoteColumns.BG_COLOR_ID, mBgColorId);//背景颜色ID + 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) {//将note中的data全部存入JSONArray中 + JSONObject data = sqlData.getContent(); + if (data != null) { + dataArray.put(data);//再将这个JSONArray对应共享数据mata,按键值对存入共享 + } + } + js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);//将元数据存入数组中 + } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {//类型为系统文件或目录文件时 + note.put(NoteColumns.ID, mId);//将id,类型,以及摘要,存入jsonobject,然后对应META_HEAD_NOTE键,存入共享 + 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; + } + + public void setParentId(long id) { + mParentId = id; + mDiffNoteValues.put(NoteColumns.PARENT_ID, id); + } +//设置当前ID的gtask的ID + public void setGtaskId(String gid) { + mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); + } +//同步id + public void setSyncId(long syncId) { + mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); + } + + public void resetLocalModified() { + mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); + }//初始化本地修改,即撤销所有当前修改 + + public long getId() { + return mId; + }//获得当前id + + public long getParentId() { + return mParentId; + }//获得当前id的父id + + 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);//那么就把这个ID移出便签列 + } + + Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);//插入该便签的uri + try { + mId = Long.valueOf(uri.getPathSegments().get(1)); + } catch (NumberFormatException e) {//捕获异常,转换出错,显示错误“获取note的id出现错误” + Log.e(TAG, "Get note id error :" + e.toString()); + throw new ActionFailureException("create note failed");//抛出异常,创建 note 失败 + } + if (mId == 0) { + throw new IllegalStateException("Create thread id failed"); + } + + if (mType == Notes.TYPE_NOTE) {//对于note类型,引用sqlData.commit方法操作 + 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");//尝试以无效 id 更新 note + } + 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) + }); + } + if (result == 0) {//如果内容解析器没有更新,那么报错:没有更新,或许用户在同步时进行更新 + Log.w(TAG, "there is no update. maybe user updates note when syncing"); + } + } + + if (mType == Notes.TYPE_NOTE) {//对note类型,还是对其中的data引用commit,从而实现目的 + 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/lhy/Task.java b/lhy/Task.java new file mode 100644 index 0000000..db1aa72 --- /dev/null +++ b/lhy/Task.java @@ -0,0 +1,351 @@ +/* + * 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; + + +public class Task extends Node {//一个task类(任务),继承自Node类 + private static final String TAG = Task.class.getSimpleName();//调用 getSimpleName ()函数来得到类的简写名称并存入字符串TAG中 + + private boolean mCompleted;//以下四个变量用于Task构造,mCompleted判断是否完成 + + private String mNotes;//将在实例中存储数据的类型 + + private JSONObject mMetaInfo; + + private Task mPriorSibling;//优先兄弟task的指针 + + private TaskList mParent;//任务列表的指针 + + public Task() {//Task类的构造函数,对对象进行初始化 + super(); + mCompleted = false; + mNotes = null; + mPriorSibling = null; + mParent = null; + mMetaInfo = null;//对类的变量进行初始化 + } + + public JSONObject getCreateAction(int actionId) {//对操作号即actionId 进行一些操作的公用函数 + JSONObject js = new JSONObject(); + + 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();//创建实体数据并将name,创建者id,实体类型存入数据 + 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); + if (getNotes() != null) {//如果有文本输入 + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); + } + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + // parent_id + js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); + + // dest_parent_type + js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,//所在列表的id存入父id + GTaskStringUtils.GTASK_JSON_TYPE_GROUP); + + // list_id + js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());//存入列表id + + // prior_sibling_id + if (mPriorSibling != null) { + js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());//那么将其存入优先ID序列中 + } + + } 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) {//接收更新action + JSONObject js = new JSONObject(); + + try {//同样是使用try和catch进行异常处理操作,跟上面的差不多就不再赘述了 + // 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()); + if (getNotes() != null) {//如果存在 notes ,则将其也放入 entity 中 + 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 {//用try和catch进行异常处理操作 + // 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)) {//设置notes + setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); + } + + // name + if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {//设置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) {//通过本地的json设置内容 + if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) + || !js.has(GTaskStringUtils.META_HEAD_DATA)) { + Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");//那么反馈给用户出错信息 + } + + try {//否则进行try和catch的异常处理操作 + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + + if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {//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)) {//遍历 dataArray 查找与数据库中DataConstants.NOTE 记录信息一致的 data + setName(data.getString(DataColumns.CONTENT)); + break; + } + } + + } catch (JSONException e) {//异常处理操作 + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + } + + public JSONObject getLocalJSONFromContent() {//从content获取本地json + 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 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);//获取metainfo中的head_note + return js; + } else { + // synced task + JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);//定义一个数组并进行初始化 + + for (int i = 0; i < dataArray.length(); i++) {//遍历 dataArray 查找与数据库中DataConstants.NOTE 记录信息一致的 data + JSONObject data = dataArray.getJSONObject(i); + if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { + data.put(DataColumns.CONTENT, getName()); + break; + } + } + + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + return mMetaInfo; + } + } catch (JSONException e) { + Log.e(TAG, e.toString());//e.toString()获取异常类型和异常详细消息 + e.printStackTrace(); + return null; + } + } + + public void setMetaInfo(MetaData metaData) { + 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; + if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { + noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);//便签元数据已被删除,不存在,返回更新云端数据的同步行为 + } + + if (noteInfo == null) {//云端便签 id 已被删除,不存在,返回更新本地数据的同步行为 + Log.w(TAG, "it seems that note meta has been deleted"); + return SYNC_ACTION_UPDATE_REMOTE; + } + + if (!noteInfo.has(NoteColumns.ID)) {//便签 id 不匹配,返回更新本地数据的同步行为 + Log.w(TAG, "remote note id seems to be deleted"); + return SYNC_ACTION_UPDATE_LOCAL; + } + + // 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; + } + + 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())) {//判断gtask的id与获取的id是否匹配 + Log.e(TAG, "gtask id doesn't match"); + return SYNC_ACTION_ERROR; + } + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {//本地id与云端id一致,即更新云端 + // 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; + }//设定是note成员变量 + + public void setPriorSibling(Task priorSibling) { + this.mPriorSibling = priorSibling; + }//设置优先兄弟 task 的优先级 + + public void setParent(TaskList parent) { + this.mParent = parent; + }//设置这个任务的父节点 + + public boolean getCompleted() { + return this.mCompleted; + }//获取 task 是否修改完毕的记录 + + public String getNotes() { + return this.mNotes; + }//获取成员变量 mNotes 的信息 + + public Task getPriorSibling() { + return this.mPriorSibling; + }//获取优先兄弟 task + + public TaskList getParent() { + return this.mParent; + }//获取父节点列表 + +} diff --git a/lhy/TaskList.java b/lhy/TaskList.java new file mode 100644 index 0000000..0bf3642 --- /dev/null +++ b/lhy/TaskList.java @@ -0,0 +1,343 @@ +/* + * 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.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; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + + +public class TaskList extends Node {//创建继承 Node的任务表类 + private static final String TAG = TaskList.class.getSimpleName();//调用getSimpleName ()函数得到类的简称存入字符串TAG中 + + private int mIndex;//当前Tasklist的指针 + + private ArrayList mChildren;//类中主要的保存数据的单元,用来实现一个以Task为元素的ArrayList + + public TaskList() {//TaskList 的构造函数 + super(); + mChildren = new ArrayList(); + mIndex = 1; + } + + public JSONObject getCreateAction(int actionId) {//生成并返回一个包含了一定数据的JSONObject实体 + JSONObject js = new JSONObject(); + + 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, mIndex); + + // entity_delta + JSONObject entity = new JSONObject();//.新建一个 JSONObject 对象,名为实体,将 name,creator id,entity type 三个信息存在一起 + 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_GROUP); + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);//将实体类型设置为“GROUP” + + } catch (JSONException e) { + Log.e(TAG, e.toString());//获取异常类型和异常详细消息 + e.printStackTrace(); + throw new ActionFailureException("fail to generate tasklist-create jsonobject"); + } + + return js; + } + + public JSONObject getUpdateAction(int actionId) {//接受更新action,返回jsonobject + JSONObject js = new JSONObject(); + + try {// 初始化 js 中的数据 + // 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(实体) + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + 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 tasklist-update jsonobject"); + } + + return js; + } + + public void setContentByRemoteJSON(JSONObject js) {//通过云端 JSON 数据设置实例化对象 js 的内容 + if (js != null) { + try { + // id + if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {//如果传入的对象中含有GTASK_JSON_ID,说明动作的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)) {//语句块:对任务的name进行设置 + setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to get tasklist content from jsonobject");//通过 JSONObeject 获取任务表内容失败 + } + } + } + + public void setContentByLocalJSON(JSONObject js) {//通过本地 JSON 数据设置对象 js 内容 + if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { + Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); + } + + try { + JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);//NullPointerException这个异常出现在处理对象时对象不存在但又没有捕捉到进行处理的时候 + + if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {//若为一般类型的文件夹 + String name = folder.getString(NoteColumns.SNIPPET);//获取文件夹片段字符串作为文件夹名称 + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);//设置名称:MIUI系统文件夹前缀+文件夹名称 + } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { + if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)//若为根目录文件夹 + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);//MIUI系统文件夹前缀+默认文件夹名称 + else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) + 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) { + Log.e(TAG, e.toString());//获取异常类型和异常详细消息 + e.printStackTrace(); + } + } + + public JSONObject getLocalJSONFromContent() { + try { + JSONObject js = new JSONObject(); + JSONObject folder = new JSONObject();//创建一个 JSONObject 的实例化对象 folder + + String folderName = getName(); + if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) + folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), + folderName.length()); + 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); + + js.put(GTaskStringUtils.META_HEAD_NOTE, folder); + + return js; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + 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()) {//最近一次修改的 id 匹配成功,返回无的同步行为 + // 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())) {//如果获取的ID不匹配,返回同步动作失败 + 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) { + boolean ret = false; + if (task != null && !mChildren.contains(task)) { + ret = mChildren.add(task); + if (ret) {//若添加成功,则设置优先兄弟和父节点 + // need to set prior sibling and parent + task.setPriorSibling(mChildren.isEmpty() ? null : mChildren + .get(mChildren.size() - 1)); + task.setParent(this); + } + } + return ret;//返回值为是否成功添加任务 + } + + public boolean addChildTask(Task task, int index) {//在当前任务表的指定位置添加新的任务,index是指针。 + if (index < 0 || index > mChildren.size()) { + Log.e(TAG, "add child task: invalid index"); + return false; + } + + int pos = mChildren.indexOf(task);//获取要添加的任务在任务表中的位置 + if (task != null && pos == -1) { + mChildren.add(index, task); + + // update the task list + Task preTask = null;//更新任务表 + Task afterTask = null; + if (index != 0) + preTask = mChildren.get(index - 1); + if (index != mChildren.size() - 1) + afterTask = mChildren.get(index + 1); + + task.setPriorSibling(preTask);//使得三个任务前后连在一块 + if (afterTask != null)//下一个任务设置兄弟任务优先级 + afterTask.setPriorSibling(task); + } + + return true; + } + + public boolean removeChildTask(Task task) {//删除TaskList中的一个Task + boolean ret = false; + int index = mChildren.indexOf(task); + if (index != -1) { + ret = mChildren.remove(task);//删除mChildren中的任务。 + + if (ret) { + // reset prior sibling and parent + task.setPriorSibling(null); + task.setParent(null); + + // update the task list + if (index != mChildren.size()) {//代码块:删除成功后,要对任务列表进行更新 + mChildren.get(index).setPriorSibling( + index == 0 ? null : mChildren.get(index - 1)); + } + } + } + return ret; + } + + public boolean moveChildTask(Task task, int index) {//以下为对子任务的移动,直接查找,获取任务索引,依据索引查找,依据坐标查找以及设定和获取索引的操作 + + if (index < 0 || index >= mChildren.size()) { + Log.e(TAG, "move child task: invalid index"); + return false; + } + + int pos = mChildren.indexOf(task);//所要查找的子任务不存在,返回假值 + if (pos == -1) { + Log.e(TAG, "move child task: the task should in the list"); + return false; + } + + if (pos == index) + return true; + return (removeChildTask(task) && addChildTask(task, index)); + } + + public Task findChildTaskByGid(String gid) {//按gid寻找Task + for (int i = 0; i < mChildren.size(); i++) { + Task t = mChildren.get(i); + if (t.getGid().equals(gid)) { + return t; + } + } + return null; + } + + public int getChildTaskIndex(Task task) { + return mChildren.indexOf(task); + }//返回指定Task的index + + public Task getChildTaskByIndex(int index) { + if (index < 0 || index >= mChildren.size()) { + Log.e(TAG, "getTaskByIndex: invalid index"); + return null; + } + return mChildren.get(index); + } + + public Task getChilTaskByGid(String gid) {//通过索引获取子任务 + for (Task task : mChildren) { + if (task.getGid().equals(gid)) + return task; + } + return null; + } + + public ArrayList getChildTaskList() { + return this.mChildren; + }//获取子任务列表 + + public void setIndex(int index) { + this.mIndex = index; + }//设置任务索引 + + public int getIndex() { + return this.mIndex; + }//获取任务指针。 +} From bc3a585e3adbfe1da8efd5b4164b51014f73ba14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E6=98=8A=E9=98=B3?= <2406241504@qq.com> Date: Fri, 14 Apr 2023 20:38:07 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E5=B0=8F=E7=B1=B3=E4=BE=BF=E7=AD=BE?= =?UTF-8?q?=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 1111.txt | 1 - README.md | 2 -- 2 files changed, 3 deletions(-) delete mode 100644 1111.txt delete mode 100644 README.md diff --git a/1111.txt b/1111.txt deleted file mode 100644 index 9d07aa0..0000000 --- a/1111.txt +++ /dev/null @@ -1 +0,0 @@ -111 \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 8613681..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# git-xiaomibianqian - From 1320d150f3fd38c80efc51b0caa93950c98d7a8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E6=98=8A=E9=98=B3?= <2406241504@qq.com> Date: Fri, 21 Apr 2023 15:59:19 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E6=9D=8E=E6=98=8A=E9=98=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/data/Contact.java | 74 +++ src/data/Notes.java | 279 +++++++++ src/data/NotesDatabaseHelper.java | 362 +++++++++++ src/data/NotesProvider.java | 305 ++++++++++ src/gatsk/ActionFailureException.java | 34 ++ src/gatsk/GTaskASyncTask.java | 127 ++++ src/gatsk/GTaskClient.java | 585 ++++++++++++++++++ src/gatsk/GTaskManager.java | 800 +++++++++++++++++++++++++ src/gatsk/GTaskSyncService.java | 128 ++++ src/gatsk/MetaData.java | 82 +++ src/gatsk/NetworkFailureException.java | 33 + src/gatsk/Node.java | 101 ++++ src/gatsk/SqlData.java | 189 ++++++ src/gatsk/SqlNote.java | 505 ++++++++++++++++ src/gatsk/Task.java | 351 +++++++++++ src/gatsk/TaskList.java | 343 +++++++++++ 16 files changed, 4298 insertions(+) create mode 100644 src/data/Contact.java create mode 100644 src/data/Notes.java create mode 100644 src/data/NotesDatabaseHelper.java create mode 100644 src/data/NotesProvider.java create mode 100644 src/gatsk/ActionFailureException.java create mode 100644 src/gatsk/GTaskASyncTask.java create mode 100644 src/gatsk/GTaskClient.java create mode 100644 src/gatsk/GTaskManager.java create mode 100644 src/gatsk/GTaskSyncService.java create mode 100644 src/gatsk/MetaData.java create mode 100644 src/gatsk/NetworkFailureException.java create mode 100644 src/gatsk/Node.java create mode 100644 src/gatsk/SqlData.java create mode 100644 src/gatsk/SqlNote.java create mode 100644 src/gatsk/Task.java create mode 100644 src/gatsk/TaskList.java diff --git a/src/data/Contact.java b/src/data/Contact.java new file mode 100644 index 0000000..760d8bd --- /dev/null +++ b/src/data/Contact.java @@ -0,0 +1,74 @@ +/* + * 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.data;//当前文件所在的包名 +/*接下来引用android的一些库*/ +import android.content.Context;//调用Android自带的类 +import android.database.Cursor;//从数据库导入Cursor +import android.provider.ContactsContract.CommonDataKinds.Phone;//导入联系人电话 +import android.provider.ContactsContract.Data;//存储通讯信息 +import android.telephony.PhoneNumberUtils;//格式化用户输入的电话号码 +import android.util.Log;//安卓日志输出工具类 + +import java.util.HashMap;//用hashmap存储联系人信息 + +public class Contact {//存放联系人信息 + private static HashMap sContactCache;//存储联系人及对应的电话号码 + private static final String TAG = "Contact";//定义字符串常量 TAG指向Contact + + private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER//定义 CALLER_ID_SELECTION字符串,用于匹配联系人 + + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + + " AND " + Data.RAW_CONTACT_ID + " IN "//定义的callerIDSELEDTION所包含的各项数据 + + "(SELECT raw_contact_id " + + " FROM phone_lookup" + + " WHERE min_match = '+')"; + /*获取联系人参数Context context内容 phoneNumber和电话号码 + */ + public static String getContact(Context context, String phoneNumber) {//获取联系人 + if(sContactCache == null) {//如果当前还没有联系人,那么新建一个HashMap存储联系人 + sContactCache = new HashMap();//创建哈希表 + } + + if(sContactCache.containsKey(phoneNumber)) {//如果hashmap实例里包含电话号码,则返回电话号码 + return sContactCache.get(phoneNumber);//如果根据电话号码phoneNumber索引到了对应的联系人,那么把对应的联系人的信息返回 + } + + String selection = CALLER_ID_SELECTION.replace("+",//将CALLER_ID_SELECTION的“+”号替代为号码的后MIN_MATCH位 + PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); + Cursor cursor = context.getContentResolver().query(//通过selection的查询语句去数据库查询 + Data.CONTENT_URI,//提供联系人的内容的地址 + new String [] { Phone.DISPLAY_NAME },//返回联系人名字 + selection,//设置条件,相当于whlie + new String[] { phoneNumber },//get..函数返回字符串类phoneNUmber(手机号码) + null);//判定查询结果 + + if (cursor != null && cursor.moveToFirst()) {// 判断查询结果,如果找到,并且成功返回第一天数据 + try {//得到cursor的第一个字符串name + String name = cursor.getString(0);//从内容中获取联系人姓名 + sContactCache.put(phoneNumber, name);//将联系人姓名和电话号码写入缓存 + return name;//返回名字 + } catch (IndexOutOfBoundsException e) {//出现异常 + Log.e(TAG, " Cursor get string error " + e.toString());//Log.e为红色,可以想到error错误,这里仅显示红色的错误信息 + return null; + } finally {//关闭数据库的访问 + cursor.close();//关闭数据库的访问 + } + } else {//未找到相关信息,返回空指针 + Log.d(TAG, "No contact matched with number:" + phoneNumber);//如果没有找到信息,返回没有匹配到该电话 + return null;//返回空 + } + } +} diff --git a/src/data/Notes.java b/src/data/Notes.java new file mode 100644 index 0000000..60fd58c --- /dev/null +++ b/src/data/Notes.java @@ -0,0 +1,279 @@ +/* + * 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.data;//声明该文件所属包名 + +import android.net.Uri;//用来识别或者标识资源名称用的一串字符串 +public class Notes {//Notes 类中定义了很多常量,这些常量大多是int型和string型 + public static final String AUTHORITY = "micode_notes";//定义了一个权限名称,看作为数字证书 + public static final String TAG = "Notes";//设置标签,表示APP的名称是Notes + public static final int TYPE_NOTE = 0; + public static final int TYPE_FOLDER = 1; + public static final int TYPE_SYSTEM = 2;//对三种TYPE:NOTE,FOLDER,SYSTEM进行变量定义 + + /** + * Following IDs are system folders' identifiers + * {@link Notes#ID_ROOT_FOLDER } is default folder + * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder + * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records + */ + public static final int ID_ROOT_FOLDER = 0;//回收站目录 + public static final int ID_TEMPARAY_FOLDER = -1;//不属于文件夹的便签 + public static final int ID_CALL_RECORD_FOLDER = -2;//设定背景 + public static final int ID_TRASH_FOLER = -3;//回收站文件夹 + + public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";//文件夹编号 + public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";//背景颜色 + public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";//插件的大小 + public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";//大号桌面插件 + public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";//定义文件夹的名称 + public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";//定义call_date的ID + + public static final int TYPE_WIDGET_INVALIDE = -1;//定义查询便签和文件夹的指针 + public static final int TYPE_WIDGET_2X = 0;//定义查找数据的指针 + public static final int TYPE_WIDGET_4X = 1;//4*4桌面大小 + + public static class DataConstants {//DataContants类:存放textnotes和callnotes地址 + public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;//定义变量NOTE,用来识别text_note的存放地址 + public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;//DataContants类:存放TextNotes和CallNotes地址 + } + + /** + * Uri to query all notes and folders + */ + public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");//URI常量,方便进行系统查询 + + /** + * Uri to query data + */ + public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");//URI常量,方便查询数据 + + public interface NoteColumns {//定义了类NoteColumns的部分参数 + /** + * The unique ID for a row + *

Type: INTEGER (long)

+ */ + public static final String ID = "_id";//每一行的ID + + /** + * The parent's id for note or folder + *

Type: INTEGER (long)

+ */ + public static final String PARENT_ID = "parent_id";//父节点的ID + + /** + * Created data for note or folder + *

Type: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date";//用来保存一些创建信息,比如时间 + + /** + * Latest modified date + *

Type: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date";//提醒的日期 + + + /** + * Alert date + *

Type: INTEGER (long)

+ */ + public static final String ALERTED_DATE = "alert_date";//储存 提醒时间 + + /** + * Folder's name or text content of note + *

Type: TEXT

+ */ + public static final String SNIPPET = "snippet";//文件夹的名字或者便签内容 + + /** + * Note's widget id + *

Type: INTEGER (long)

+ */ + public static final String WIDGET_ID = "widget_id";//note的布局ID + + /** + * Note's widget type + *

Type: INTEGER (long)

+ */ + public static final String WIDGET_TYPE = "widget_type";//小部件类型 + + /** + * Note's background color's id + *

Type: INTEGER (long)

+ */ + public static final String BG_COLOR_ID = "bg_color_id";//便签背景颜色的ID + + /** + * For text note, it doesn't has attachment, for multi-media + * note, it has at least one attachment + *

Type: INTEGER

+ */ + public static final String HAS_ATTACHMENT = "has_attachment";//设置附件是否存在 + + /** + * Folder's count of notes + *

Type: INTEGER (long)

+ */ + public static final String NOTES_COUNT = "notes_count";//文件夹中的便签数量 + + /** + * The file type: folder or note + *

Type: INTEGER

+ */ + public static final String TYPE = "type";//设置文件的类型 + + /** + * The last sync id + *

Type: INTEGER (long)

+ */ + public static final String SYNC_ID = "sync_id";//最后一次同步的ID + + /** + * Sign to indicate local modified or not + *

Type: INTEGER

+ */ + public static final String LOCAL_MODIFIED = "local_modified";//本地信号是否修改 + + /** + * Original parent id before moving into temporary folder + *

Type : INTEGER

+ */ + public static final String ORIGIN_PARENT_ID = "origin_parent_id";//移动到临时文件夹之前的父文件夹 + + /** + * The gtask id + *

Type : TEXT

+ */ + public static final String GTASK_ID = "gtask_id";//后台任务ID + + /** + * The version code + *

Type : INTEGER (long)

+ */ + public static final String VERSION = "version";// 版本代号 + } + + public interface DataColumns {//定义了接口类,在数据库的创建、查询中需要DataColumns的所有信息,主要存储便签数据的信息。 + /** + * The unique ID for a row + *

Type: INTEGER (long)

+ */ + public static final String ID = "_id";//定义DataColumns的部分常量 + + /** + * The MIME type of the item represented by this row. + *

Type: Text

+ */ + public static final String MIME_TYPE = "mime_type";// 这一排表示的项目的MIME类型。MIME类型包含视频、图像、文本、音频、应用程序等数据。 + + /** + * The reference id to note that this data belongs to + *

Type: INTEGER (long)

+ */ + public static final String NOTE_ID = "note_id";//便签ID + + /** + * Created data for note or folder + *

Type: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + // 创建日期 + /** + * Latest modified date + *

Type: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + //最新的修改时间 + /** + * Data's content + *

Type: TEXT

+ */ + public static final String CONTENT = "content";//数据包含的内容 + + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * integer data type + *

Type: INTEGER

+ */ + public static final String DATA1 = "data1";//文本内容的数据结构 + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * integer data type + *

Type: INTEGER

+ */ + public static final String DATA2 = "data2";//定义了文本内容的类型 + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA3 = "data3";//定义常量 + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA4 = "data4"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA5 = "data5";//.继承DataColumns的类,组织电话内容数据结构 + } + + public static final class TextNote implements DataColumns {//文本笔记,通过定义的接口集成了上面的属性 + /** + * Mode to indicate the text in check list mode or not + *

Type: Integer 1:check list mode 0: normal mode

+ */ + public static final String MODE = DATA1;//模式数据为data1类型 + + public static final int MODE_CHECK_LIST = 1;//note中内容的类型 + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";//定义内容类型 + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";//内容项目类型 + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");//通过uri的parse方法访问资源 + } + + public static final class CallNote implements DataColumns {//记录通话数据的表头 + /** + * Call date for this record + *

Type: INTEGER (long)

+ */ + public static final String CALL_DATE = DATA1;//存放通话时间信息到DATA1中 + + /** + * Phone number for this record + *

Type: TEXT

+ */ + public static final String PHONE_NUMBER = DATA3;//电话号码为data3类型 + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";//修改CONTENT_TYPE属性,即内容类型 + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";//内容项目类型 + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");// 访问uri,并将解析结果保存于CONTENT_URI属性 + } +} diff --git a/src/data/NotesDatabaseHelper.java b/src/data/NotesDatabaseHelper.java new file mode 100644 index 0000000..738ef1c --- /dev/null +++ b/src/data/NotesDatabaseHelper.java @@ -0,0 +1,362 @@ +/* + * 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.data;//声明包 + +import android.content.ContentValues; +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns;//数据库操作中保存数据信息 + + +public class NotesDatabaseHelper extends SQLiteOpenHelper {//继承于SQLiteOpenHelper的类NotesDatabaseHelper,用于实现对便签或者 文件的数据库操作,例如删除便签 + private static final String DB_NAME = "note.db";//定义数据库的名称为“note.db” + + private static final int DB_VERSION = 4;//数据库版本号 + + public interface TABLE {//将接口分成note和data + public static final String NOTE = "note";//创建便签表的数据库 + + public static final String DATA = "data";//数据库中需要存储的项目的名称,就类似创建一个表格的表头的内容。 + } + + private static final String TAG = "NotesDatabaseHelper";//存储便签编号的一个数据表格 + + private static NotesDatabaseHelper mInstance;//创建类NotesDatabaseHelper的对象——mInstance + + private static final String CREATE_NOTE_TABLE_SQL =//文件夹增加Note后需要更改的数据的表格 + "CREATE TABLE " + TABLE.NOTE + "(" +//文件夹减少Note后需要更改的数据的表格 + NoteColumns.ID + " INTEGER PRIMARY KEY," +//文件夹插入Note后需要更改的数据的表格 + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +//文件夹删除Note后需要更改的数据的表格 + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +//应用界面颜色选择 + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +// 创建时间数据 + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +//文件夹中便签数据初始化为0 + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +//Note中数据删除更改的数据表格。 + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +//数据库中需要存储的项目的名称,就相当于创建一个表格的表头的内容 + ")"; + + private static final String CREATE_DATA_TABLE_SQL =//创建SQL的data表 + "CREATE TABLE " + TABLE.DATA + "(" +//note删除数据触发 + DataColumns.ID + " INTEGER PRIMARY KEY," + + DataColumns.MIME_TYPE + " TEXT NOT NULL," + + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA1 + " INTEGER," + + DataColumns.DATA2 + " INTEGER," + + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + + ")";//文件夹删除note触发 + + private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =//文件夹移除note时触发垃圾回收 + "CREATE INDEX IF NOT EXISTS note_id_index ON " + + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";//存储便签编号的一个数据表格 +//以下几个都是在创建触发器(trigger)。触发器是一些在特定的数据库事件(database-event) 发生时自动进行的数据库操作 + /** + * Increase folder's note count when move note to the folder + *///Increase增加文件Decrease减少文件 + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =//将新的note移入该文件夹时,更新该文件夹note的数量 + "CREATE TRIGGER increase_folder_count_on_update "+ + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END";// 在文件夹中移入一个Note之后需要更改的数据的表格 + + /** + * Decrease folder's note count when move note from folder + */ + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =//notes从文件夹移除后,数量减一,并且进行一系列的操作 + "CREATE TRIGGER decrease_folder_count_on_update " + + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +//在文件夹中移出一个Note之后需要更改的数据的表格 + " END"; +//便签从文件夹移除后,数量减一,并且进行一系列的操作进行更新 + /** + * Increase folder's note count when insert new note to the folder + */ + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =//在文件夹中新建notes后,数量加1 + "CREATE TRIGGER increase_folder_count_on_insert " + + " AFTER INSERT ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END";//在文件夹中插入一个Note之后需要更改的数据的表格 + + /** + * Decrease folder's note count when delete note from the folder + */ + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = + "CREATE TRIGGER decrease_folder_count_on_delete " +//定义一个更新文件夹中便签数目的SQL语句。当有便签从该文件夹中删除时使用 + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0;" + + " END";//在文件夹中删除一个Note之后需要更改的数据的表格 + + /** + * Update note's content when insert data with type {@link DataConstants#NOTE} + *///构建一条SQL语句,用于实现在note中输入data后,进行当前状态的更新 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = + "CREATE TRIGGER update_note_content_on_insert " + + " AFTER INSERT ON " + TABLE.DATA + + " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END";//在文件夹中对一个Note导入新的数据之后需要更改的数据的表格 + + /** + * Update note's content when data with {@link DataConstants#NOTE} type has changed + *///在data数据改变后对整个应用进行数据刷新 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = + "CREATE TRIGGER update_note_content_on_update " + + " AFTER UPDATE ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END";//Note数据被修改后需要更改的数据的表格 + + /** + * Update note's content when data with {@link DataConstants#NOTE} type has deleted + *///在数据被删除时,进行更新。 + private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = + "CREATE TRIGGER update_note_content_on_delete " + + " AFTER delete ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=''" + + " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + + " END";//Note数据被删除后需要更改的数据的表格 + + /** + * Delete datas belong to note which has been deleted + *///实现在note被删除后,将该note对应的data删除的功能 + private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = + "CREATE TRIGGER delete_data_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.DATA + + " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + + " END";//删除已删除的便签的数据后需要更改的数据的表格 + + /** + * Delete notes belong to folder which has been deleted + *///用于实现在文件夹被删除后,将该文件夹中的note删除的功能 + private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = + "CREATE TRIGGER folder_delete_notes_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END";//删除已删除的文件夹的便签后需要更改的数据的表格 + + /** + * Move notes belong to folder which has been moved to trash folder + *///恢复删除的notes,并且更新一些数据 + private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =//将垃圾文件夹里的note还原,并更新数据表格 + "CREATE TRIGGER folder_move_notes_on_trash " + + " AFTER UPDATE ON " + TABLE.NOTE + + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END";//还原垃圾桶中便签后需要更改的数据的表格 + + public NotesDatabaseHelper(Context context) { + super(context, DB_NAME, null, DB_VERSION); + }//构造函数,传入数据库的名称和版本 + + public void createNoteTable(SQLiteDatabase db) {//标注出数据库的名称和版本 + db.execSQL(CREATE_NOTE_TABLE_SQL);//创建表头 + reCreateNoteTableTriggers(db); + createSystemFolder(db); + Log.d(TAG, "note table has been created"); + }//创建表格,存储标签属性 + + private void reCreateNoteTableTriggers(SQLiteDatabase db) {//创建一个储存标签属性的表格 + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");//创建增加文件夹的触发器 + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");//创建减少文件夹的触发器 + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); +//在删除原来的触发器后,创建新的触发器 + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);//创建自己的数据库操作 + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);//创建更新减少文件夹的触发器 + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); + db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER); + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER); + db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);//创建删除notes的触发器 + db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);//创建将回收站中的notes还原的触发器 + }//execSQL通过添加sql语句可以执行sql操作 +//execSQL通过添加sql语句可以执行sql操作 + private void createSystemFolder(SQLiteDatabase db) {//创建几个系统文件夹 + ContentValues values = new ContentValues();//向数据库中插入数据,就要新建一个contentValues的对象。但只能存储基本类型数据 + + /** + * call record foler for call notes + *///储存呼叫记录的文件夹 + values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);//放入数据(NoteColumns的id,呼叫记录文件夹的ld) + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values);//插入ContantValues对象 + + /** + * root folder which is default folder + *///对默认文件夹(根文件夹)进行操作 + values.clear();//对根文件夹(默认文件夹)进行修改,首先先把values容器清空,在对他添加内容,最后放入数据库 + values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);//将数据库ID与通话记录文件夹ID形成映射 + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);//将数据库中数据类型与通话记录文件夹类型形成映射 + db.insert(TABLE.NOTE, null, values); + + /** + * temporary folder which is used for moving note + *///移动note的临时文件夹 + values.clear();// 临时文件夹的修改操作 + values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);//将数据库ID与通话记录文件夹ID形成映射 + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + /** + * create trash folder + *///创建垃圾文件夹 + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);//将数据库ID与通话记录文件夹ID形成映射 + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + public void createDataTable(SQLiteDatabase db) {//将数据库ID与通话记录文件夹ID形成映射 + db.execSQL(CREATE_DATA_TABLE_SQL);//用来重新创建note对应的data的表项 + reCreateDataTableTriggers(db);//重新建立数据表的触发器 + db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); + Log.d(TAG, "data table has been created"); + } + + private void reCreateDataTableTriggers(SQLiteDatabase db) {//删除重建表格 + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); + + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); + } + + static synchronized NotesDatabaseHelper getInstance(Context context) {//如果NotesDatabaseHelper的实例创建失败,那就重新建一个,重新分配内从空间 + if (mInstance == null) { + mInstance = new NotesDatabaseHelper(context); + } + return mInstance; + } + + @Override + public void onCreate(SQLiteDatabase db) {//在NotesDatabaseHelper对象生命周期开始时创建Note table和Datatable + createNoteTable(db);//函数:生命周期开始的时候oncreate 被调用,这里对其进行重写,加入notes表单和数据表单 + createDataTable(db); + }//实现两个表格 + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//数据库版本的更新 + boolean reCreateTriggers = false;//是否重新建立note及data的表项 + boolean skipV2 = false; + + if (oldVersion == 1) {//代码段:如果版本是一则更新到版本二 + upgradeToV2(db); + skipV2 = true; // this upgrade including the upgrade from v2 to v3 + oldVersion++; + } + + if (oldVersion == 2 && !skipV2) {//判断旧版本是不是2号版本且没有跳过2号版本,就更新到3号版本 + upgradeToV3(db); + reCreateTriggers = true; + oldVersion++; + } + + if (oldVersion == 3) {//v3-v4 + upgradeToV4(db); + oldVersion++; + } + + if (reCreateTriggers) {//重新创建的同时,创建新的note table和datatable + reCreateNoteTableTriggers(db); + reCreateDataTableTriggers(db); + } + + if (oldVersion != newVersion) {//旧版本与最新版本不一致,抛出异常 + throw new IllegalStateException("Upgrade notes database to version " + newVersion + + "fails"); + } + } + + private void upgradeToV2(SQLiteDatabase db) {//将数据库的版本更新到V2 + db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); + db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); + createNoteTable(db); + createDataTable(db); + } + + private void upgradeToV3(SQLiteDatabase db) {//gengxinv3 + // drop unused triggers + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); + // add a column for gtask id + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID + + " TEXT NOT NULL DEFAULT ''"); + // add a trash system folder在数据库的便签(note)表单中加上一个默认的垃圾文件夹,不用用户自己创建 + ContentValues values = new ContentValues();//添加垃圾系统文件夹 + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values);//插入到表中 + } + + private void upgradeToV4(SQLiteDatabase db) {//数据库版本升级到V4 + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION + + " INTEGER NOT NULL DEFAULT 0"); + } +} diff --git a/src/data/NotesProvider.java b/src/data/NotesProvider.java new file mode 100644 index 0000000..17dbf7c --- /dev/null +++ b/src/data/NotesProvider.java @@ -0,0 +1,305 @@ +/* + * 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.data;//标注该文件所属的软件包 + + +import android.app.SearchManager; +import android.content.ContentProvider; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Intent; +import android.content.UriMatcher; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.net.Uri; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE;// SearchManager 的作用是提供对系统搜索服务的访问 + + +public class NotesProvider extends ContentProvider {//为存储和获取数据提供接口。可以在不同的应用程序之间共享数据 + private static final UriMatcher mMatcher;//UriMatcher是Android提供的用来操作Uri的工具类 + + private NotesDatabaseHelper mHelper;//数据库辅助类的实例化 + + private static final String TAG = "NotesProvider"; + + private static final int URI_NOTE = 1; + private static final int URI_NOTE_ITEM = 2; + private static final int URI_DATA = 3; + private static final int URI_DATA_ITEM = 4; + + private static final int URI_SEARCH = 5; + private static final int URI_SEARCH_SUGGEST = 6; + + static {//初始化mMatcher UriMatcher类 + mMatcher = new UriMatcher(UriMatcher.NO_MATCH);//创建UriMatcher时,调用UriMatcher。UriMatcher.NO_MATCH表示不匹配任何路径 + mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); + mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); + mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); + mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); + mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);//SUGGEST_URI_PATH_QUERY 并不属于URI的一部分,而应是用于指向此路径的常量。 + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); + }//注册完需要匹配的Uri后,就可以使用sMatcher.match(uri)方法对输入的Uri进行匹配 + + /** + * x'0A' represents the '\n' character in sqlite. For title and content in the search result, + * we will trim '\n' and white space in order to show more information. + */ + private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","//声明 NOTES_SEARCH_PROJECTION + + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","//设置表明额外数据、推荐显示的文本、图标、操作、数据 + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","//TEXT_1是将该字段作为安卓搜索框中建议显示的文本。如果每个建议想显示两行数据,还有SearchManager.SUGGEST_COLUMN_TEXT_2 + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," + + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," + + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + + private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION//构造数据库查询语句,用于通过notes的片段查询notes + + " FROM " + TABLE.NOTE//在特定表中某一字段检索特定子串 + + " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + + @Override + public boolean onCreate() {//创建一个便签数据库助手helper + mHelper = NotesDatabaseHelper.getInstance(getContext());//对mHelper进行实例化 + return true; + } + + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,//在数据库中查询uri,然后返回uri的位置 + String sortOrder) { + Cursor c = null; + SQLiteDatabase db = mHelper.getReadableDatabase(); + String id = null; + switch (mMatcher.match(uri)) { + case URI_NOTE: + c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_NOTE_ITEM://查询便签条目 + id = uri.getPathSegments().get(1);//获取uri中1号描述符 + c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_DATA://根据日期进行查询 + c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_DATA_ITEM://查询id对应的具体数据 + id = uri.getPathSegments().get(1); + c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_SEARCH://匹配到搜索 + case URI_SEARCH_SUGGEST: + if (sortOrder != null || projection != null) { + throw new IllegalArgumentException( + "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");//在查询时不能指定排序参数(sortOrder)、查询条件(selection)、占位符(selectionArgs)、要查询的表(projection) + } + + String searchString = null;//搜索所得的内容 + if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { + if (uri.getPathSegments().size() > 1) { + searchString = uri.getPathSegments().get(1); + } + } else {//利用URI的getQueryParameter方法可以获取字符串参数 + searchString = uri.getQueryParameter("pattern"); + } + + if (TextUtils.isEmpty(searchString)) {//格式化搜索的字符串 + return null; + } + + try {//非法状态异常 + searchString = String.format("%%%s%%", searchString); + c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, + new String[] { searchString }); + } catch (IllegalStateException ex) { + Log.e(TAG, "got exception: " + ex.toString()); + } + break; + default://如果以上多个case均不命中,则抛出未知uri的异常 + throw new IllegalArgumentException("Unknown URI " + uri); + } + if (c != null) {//若getContentResolver发生变化,就接收通知 + c.setNotificationUri(getContext().getContentResolver(), uri); + } + return c; + } + + @Override + public Uri insert(Uri uri, ContentValues values) {//插入一个uri,uri是一个用于标识某一互联网资源名称的字符串 + SQLiteDatabase db = mHelper.getWritableDatabase();//获得可写的数据库 + long dataId = 0, noteId = 0, insertedId = 0; + switch (mMatcher.match(uri)) {//数据库的插入,用来存放数据 + case URI_NOTE: + insertedId = noteId = db.insert(TABLE.NOTE, null, values); + break; + case URI_DATA://如果是数据类型,且其id能对应于某个便签id,则插入 + if (values.containsKey(DataColumns.NOTE_ID)) { + noteId = values.getAsLong(DataColumns.NOTE_ID); + } else {//错误的数据格式,没有note的id + Log.d(TAG, "Wrong data format without note id:" + values.toString()); + } + insertedId = dataId = db.insert(TABLE.DATA, null, values); + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri);//未知uri异常 + } + // Notify the note uri + if (noteId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);//把noteId加到URI的尾部,连接成新的URI + } + + // Notify the data uri + if (dataId > 0) {//更新data + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);//返回插入的uri的路径 + } + + return ContentUris.withAppendedId(uri, insertedId);//返回插入的uri的路径 + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) {//从数据库中删除uri + int count = 0; + String id = null; + SQLiteDatabase db = mHelper.getWritableDatabase(); + boolean deleteData = false; + switch (mMatcher.match(uri)) { + case URI_NOTE://查找到不同类型的相应的uri后在数据库中删除 + selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; + count = db.delete(TABLE.NOTE, selection, selectionArgs); + break; + case URI_NOTE_ITEM://如果是便签条目,获取对应id,且对应id非系统文件夹,则删除 + id = uri.getPathSegments().get(1); + /** + * ID that smaller than 0 is system folder which is not allowed to + * trash + */ + long noteId = Long.valueOf(id);//.语句:将string类型转换为long类型 + if (noteId <= 0) { + break; + } + count = db.delete(TABLE.NOTE, + NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + break; + case URI_DATA: + count = db.delete(TABLE.DATA, selection, selectionArgs);//删除数据 + deleteData = true; + break; + case URI_DATA_ITEM://删除uri标识的指定数据 + id = uri.getPathSegments().get(1); + count = db.delete(TABLE.DATA, + DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + deleteData = true; + break; + default://匹配失败,则报错 + throw new IllegalArgumentException("Unknown URI " + uri); + } + if (count > 0) {//对上述的操作进行判断,上述更改发生,count>0 + if (deleteData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null);//对所有修改进行通知 + } + return count; + } + + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {//数据库更新uri + int count = 0; + String id = null; + SQLiteDatabase db = mHelper.getWritableDatabase(); + boolean updateData = false; + switch (mMatcher.match(uri)) { + case URI_NOTE: + increaseNoteVersion(-1, selection, selectionArgs);//升级note版本 + count = db.update(TABLE.NOTE, values, selection, selectionArgs); + break; + case URI_NOTE_ITEM: + id = uri.getPathSegments().get(1); + increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); + count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id//对notes item uri进行更新 + + parseSelection(selection), selectionArgs); + break; + case URI_DATA://对多个数据进行修改 + count = db.update(TABLE.DATA, values, selection, selectionArgs); + updateData = true; + break; + case URI_DATA_ITEM: + id = uri.getPathSegments().get(1);//获取该项目id并将其uri更新 + count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); + updateData = true; + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + + if (count > 0) {//代码段:通知观察者,数据更新 + if (updateData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } +//将字符串解析成规定格式 + private String parseSelection(String selection) { + return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); + } + + private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { + StringBuilder sql = new StringBuilder(120); + sql.append("UPDATE "); + sql.append(TABLE.NOTE); + sql.append(" SET "); + sql.append(NoteColumns.VERSION); + sql.append("=" + NoteColumns.VERSION + "+1 "); + + if (id > 0 || !TextUtils.isEmpty(selection)) {//操作条件selection不为空或者ID>0,增加WHERE语句 + sql.append(" WHERE "); + } + if (id > 0) {//如果id为正,更新id + sql.append(NoteColumns.ID + "=" + String.valueOf(id)); + } + if (!TextUtils.isEmpty(selection)) {//输入的文本非空的条件下输入到数据库中 + String selectString = id > 0 ? parseSelection(selection) : selection; + for (String args : selectionArgs) { + selectString = selectString.replaceFirst("\\?", args);//用args替换掉?的占位符 + } + sql.append(selectString);//增加selectString语句 + } + + mHelper.getWritableDatabase().execSQL(sql.toString());//execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句 + } + + @Override + public String getType(Uri uri) { + // TODO Auto-generated method stub + return null;//初始化,返回一个空指针 + } + +} diff --git a/src/gatsk/ActionFailureException.java b/src/gatsk/ActionFailureException.java new file mode 100644 index 0000000..32e5cab --- /dev/null +++ b/src/gatsk/ActionFailureException.java @@ -0,0 +1,34 @@ +/* + * 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.exception; + +public class ActionFailureException extends RuntimeException {//用来验证版本一致性,如果不一致会导致反序列化的时候版本不一致的异常。 + private static final long serialVersionUID = 4425249765923293627L; +// 函数:交给父类的构造函数(包括下面的两个构造函数) + public ActionFailureException() { + super(); + }//super是指向父类的一个指针,与其相对的还有this,指向当前类。 +//调用父类具有相同形参paramString的构造方法 + public ActionFailureException(String paramString) { + super(paramString); + } +//函数:第三种形式的构造函数 + public ActionFailureException(String paramString, Throwable paramThrowable) { + super(paramString, paramThrowable); + } +} diff --git a/src/gatsk/GTaskASyncTask.java b/src/gatsk/GTaskASyncTask.java new file mode 100644 index 0000000..08a48a3 --- /dev/null +++ b/src/gatsk/GTaskASyncTask.java @@ -0,0 +1,127 @@ + +/* + * 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.remote; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.os.AsyncTask; + +import net.micode.notes.R; +import net.micode.notes.ui.NotesListActivity; +import net.micode.notes.ui.NotesPreferenceActivity; + + +public class GTaskASyncTask extends AsyncTask {/*异步操作类,实现GTask的异步操作过程 + private void showNotification(int tickerId, String content) 向用户提示当前同步的状态,是一个用于交互的方法*/ + + private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; +//初始化异步功能 + public interface OnCompleteListener { + void onComplete(); + } + private Context mContext;//文本内容 + + private NotificationManager mNotifiManager;//对象: 通知管理器类的实例化 + + private GTaskManager mTaskManager;//实例化任务管理器 + + private OnCompleteListener mOnCompleteListener; + + public GTaskASyncTask(Context context, OnCompleteListener listener) {//函数: GTaskASyncTask类的构造函数 + mContext = context; + mOnCompleteListener = listener; + mNotifiManager = (NotificationManager) mContext + .getSystemService(Context.NOTIFICATION_SERVICE); + mTaskManager = GTaskManager.getInstance(); + } + + public void cancelSync() {//取消同步 + mTaskManager.cancelSync(); + } + + public void publishProgess(String message) {//显示消息 + publishProgress(new String[] { + message + }); + } + + private void showNotification(int tickerId, String content) { + PendingIntent pendingIntent; + if (tickerId != R.string.ticker_success) { + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, + NotesPreferenceActivity.class), 0); + + } else {//点击清除按钮或点击通知后会自动消失 + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, + NotesListActivity.class), 0); + } + +//若同步成功,就从系统取得一个来启动一个NotesListActivity的对象 + Notification.Builder builder = new Notification.Builder(mContext) + .setAutoCancel(true) + .setContentTitle(mContext.getString(R.string.app_name))//设置最新事件信息 + .setContentText(content) + .setContentIntent(pendingIntent) + .setWhen(System.currentTimeMillis()) + .setOngoing(true); + Notification notification=builder.getNotification(); + mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//执行后台操作 + } + + @Override + protected Integer doInBackground(Void... unused) { + publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity + .getSyncAccountName(mContext))); + return mTaskManager.sync(mContext, this);//显示进度的更新 + } + + @Override + protected void onProgressUpdate(String... progress) { + showNotification(R.string.ticker_syncing, progress[0]); + if (mContext instanceof GTaskSyncService) { + ((GTaskSyncService) mContext).sendBroadcast(progress[0]); + } + } + + @Override + protected void onPostExecute(Integer result) { + if (result == GTaskManager.STATE_SUCCESS) {//设置任务,比如在用户界面显示一个进度条 + showNotification(R.string.ticker_success, mContext.getString( + R.string.success_sync_account, mTaskManager.getSyncAccount())); + NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); + } else if (result == GTaskManager.STATE_NETWORK_ERROR) { + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); + } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); + } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { + showNotification(R.string.ticker_cancel, mContext + .getString(R.string.error_sync_cancelled)); + } + if (mOnCompleteListener != null) {//若监听器为空,则创建新进程 + new Thread(new Runnable() { + + public void run() {//执行完后调用然后返回主线程中 + mOnCompleteListener.onComplete(); + } + }).start(); + } + } +} diff --git a/src/gatsk/GTaskClient.java b/src/gatsk/GTaskClient.java new file mode 100644 index 0000000..7cbc0dc --- /dev/null +++ b/src/gatsk/GTaskClient.java @@ -0,0 +1,585 @@ +/* + * 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.remote; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AccountManagerFuture; +import android.app.Activity; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.GTaskStringUtils; +import net.micode.notes.ui.NotesPreferenceActivity; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.cookie.Cookie; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpConnectionParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.Inflater; +import java.util.zip.InflaterInputStream; + + +public class GTaskClient {//GTaskClient类:实现GTask的登录以及创建GTask任务和任务列表,从网络上获取任务内容 + private static final String TAG = GTaskClient.class.getSimpleName();//Google邮箱指定URL + + private static final String GTASK_URL = "https://mail.google.com/tasks/";//获得URL + + private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";//传递URL + + private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; + + private static GTaskClient mInstance = null;//后续使用的参数以及变量 + + private DefaultHttpClient mHttpClient; + + private String mGetUrl; +//构造函数:初始化各属性 + private String mPostUrl; + + private long mClientVersion; + + private boolean mLoggedin; + + private long mLastLoginTime; + + private int mActionId; + + private Account mAccount; + + private JSONArray mUpdateArray; + + private GTaskClient() {//初始化客户端,如果没有就new一个,否则就用当前的。 + mHttpClient = null; + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + mClientVersion = -1; + mLoggedin = false; + mLastLoginTime = 0; + mActionId = 1; + mAccount = null; + mUpdateArray = null; + } + + public static synchronized GTaskClient getInstance() {//获取实例,如果当前没有示例,则新建一个登陆的gtask,如果有直接返回 + if (mInstance == null) { + mInstance = new GTaskClient(); + } + return mInstance; + } + + public boolean login(Activity activity) {//login:用于实现登录的方法,以activity作为参数 + // we suppose that the cookie would expire after 5 minutes + // then we need to re-login + final long interval = 1000 * 60 * 5; + if (mLastLoginTime + interval < System.currentTimeMillis()) { + mLoggedin = false; + } + + // need to re-login after account switch + if (mLoggedin//在登陆成功的情况下检测到用户名和密码不匹配时登录失败 + && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity + .getSyncAccountName(activity))) { + mLoggedin = false; + } + + if (mLoggedin) {//代码块,如果登录的时候符合上面的要求则让其显示已登录登陆 + Log.d(TAG, "already logged in"); + return true; + } + + mLastLoginTime = System.currentTimeMillis(); + String authToken = loginGoogleAccount(activity, false); + if (authToken == null) {//登录失败的情况 + Log.e(TAG, "login google account failed"); + return false; + } + + // login with custom domain if necessary + if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()//使用用户域名进行登录 + .endsWith("googlemail.com"))) { + StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); + int index = mAccount.name.indexOf('@') + 1;//返回@第一次出现的位置并把位置+1后记录在index里 + String suffix = mAccount.name.substring(index); + url.append(suffix + "/"); + mGetUrl = url.toString() + "ig"; + mPostUrl = url.toString() + "r/ig"; + + if (tryToLoginGtask(activity, authToken)) {//成功登入 + mLoggedin = true; + } + } + + // try to login with google official url + if (!mLoggedin) {//代码块: 若前面的尝试失败,则尝试使用官方的域名登陆 + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + if (!tryToLoginGtask(activity, authToken)) {//第二次登录失败,返回false + return false; + } + } + + mLoggedin = true; + return true; + } + + private String loginGoogleAccount(Activity activity, boolean invalidateToken) {//登录谷歌账号的主函数,在登陆成功后获取认证令牌 + String authToken; + AccountManager accountManager = AccountManager.get(activity); + Account[] accounts = accountManager.getAccountsByType("com.google"); + + if (accounts.length == 0) {//如果没有这样的账号,输出日志信息“无有效的google账户” + Log.e(TAG, "there is no available google account"); + return null; + } + + String accountName = NotesPreferenceActivity.getSyncAccountName(activity); + Account account = null; + for (Account a : accounts) {//找到后,为属性赋值 + if (a.name.equals(accountName)) { + account = a; + break; + } + } + if (account != null) {//判断设置里有无该账号 + mAccount = account; + } else { + Log.e(TAG, "unable to get an account with the same name in the settings"); + return null; + } + + // get the token now + AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, + "goanna_mobile", null, activity, null, null); + try { + Bundle authTokenBundle = accountManagerFuture.getResult(); + authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); + if (invalidateToken) {//如果是非法的令牌,那么废除这个账号,取消登录状态 + accountManager.invalidateAuthToken("com.google", authToken); + loginGoogleAccount(activity, false); + } + } catch (Exception e) { + Log.e(TAG, "get auth token failed"); + authToken = null; + } + + return authToken; + } + + private boolean tryToLoginGtask(Activity activity, String authToken) {//方法:用于判断令牌对于登陆gtask账号是否有效 + if (!loginGtask(authToken)) { + // maybe the auth token is out of date, now let's invalidate the + // token and try again + authToken = loginGoogleAccount(activity, true); + if (authToken == null) { + Log.e(TAG, "login google account failed"); + return false; + } + + if (!loginGtask(authToken)) {//代码块: 重新获取的令牌再次失效 + Log.e(TAG, "login gtask failed"); + return false; + } + } + return true; + } + + private boolean loginGtask(String authToken) {//.loginGtask:实现登录Gtask的方法 + int timeoutConnection = 10000; + int timeoutSocket = 15000; + HttpParams httpParameters = new BasicHttpParams(); + HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); + HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); + mHttpClient = new DefaultHttpClient(httpParameters); + BasicCookieStore localBasicCookieStore = new BasicCookieStore(); + mHttpClient.setCookieStore(localBasicCookieStore); + HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); + + // login gtask + try {//登录Gtask + String loginUrl = mGetUrl + "?auth=" + authToken; + HttpGet httpGet = new HttpGet(loginUrl); + HttpResponse response = null; + response = mHttpClient.execute(httpGet); + + // get the cookie now + List cookies = mHttpClient.getCookieStore().getCookies(); + boolean hasAuthCookie = false; + for (Cookie cookie : cookies) { + if (cookie.getName().contains("GTL")) {//验证cookie信息,这里通过GTL标志来验证 + hasAuthCookie = true; + } + } + if (!hasAuthCookie) { + Log.w(TAG, "it seems that there is no auth cookie"); + } + + // get the client version + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin != -1 && end != -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + mClientVersion = js.getLong("v");//验证cookie信息,这里通过GTL标志来验证 + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return false; + } catch (Exception e) { + // simply catch all exceptions + Log.e(TAG, "httpget gtask_url failed"); + return false; + } + + return true; + } + + private int getActionId() { + return mActionId++; + }//获取动作的id号码 + + private HttpPost createHttpPost() { + HttpPost httpPost = new HttpPost(mPostUrl); + httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); + httpPost.setHeader("AT", "1"); + return httpPost; + } + + private String getResponseContent(HttpEntity entity) throws IOException {//getResponseContent:获取服务器响应的数据,主要通过方法getContentEncoding来获取网上资源,返回这些资源 + String contentEncoding = null; + if (entity.getContentEncoding() != null) { + contentEncoding = entity.getContentEncoding().getValue(); + Log.d(TAG, "encoding: " + contentEncoding); + } + + InputStream input = entity.getContent(); + if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { + input = new GZIPInputStream(entity.getContent()); + } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { + Inflater inflater = new Inflater(true); + input = new InflaterInputStream(entity.getContent(), inflater); + } + + try {//完成将字节流数据内容进行存储的功能 + InputStreamReader isr = new InputStreamReader(input); + BufferedReader br = new BufferedReader(isr); + StringBuilder sb = new StringBuilder(); + + while (true) { + String buff = br.readLine(); + if (buff == null) { + return sb.toString(); + } + sb = sb.append(buff); + } + } finally { + input.close(); + } + } + + private JSONObject postRequest(JSONObject js) throws NetworkFailureException {//获取客户端资源的函数 + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + HttpPost httpPost = createHttpPost(); + try {//.实例化一个对象,用于与服务器交互和发送请求 + LinkedList list = new LinkedList(); + list.add(new BasicNameValuePair("r", js.toString())); + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); + httpPost.setEntity(entity); + + // execute the post + HttpResponse response = mHttpClient.execute(httpPost); + String jsString = getResponseContent(response.getEntity()); + return new JSONObject(jsString); + + } catch (ClientProtocolException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed"); + } catch (IOException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("unable to convert response content to jsonobject"); + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("error occurs when posting request"); + } + } + + public void createTask(Task task) throws NetworkFailureException {//创建单个任务,通过json获取TASK中的内容并创建对应的jsPost,通过postRequest方法获取任务的返回信息,使用setGid方法设置task的new_id + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // action_list + actionList.put(task.getCreateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // post + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) {//对异常情况的处理 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("create task: handing jsonobject failed"); + } + } + + public void createTaskList(TaskList tasklist) throws NetworkFailureException {//创建一个任务列表 + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // action_list + actionList.put(tasklist.getCreateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // post + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) {//创建失败 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("create tasklist: handing jsonobject failed"); + } + } + + public void commitUpdate() throws NetworkFailureException {//更新时出现异常 + if (mUpdateArray != null) { + try { + JSONObject jsPost = new JSONObject(); + + // action_list + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + mUpdateArray = null; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("commit update: handing jsonobject failed"); + } + } + } + + public void addUpdateNode(Node node) throws NetworkFailureException {//添加更新节点,主要利用commitUpdate + if (node != null) { + // too many update items may result in an error + // set max to 10 items + if (mUpdateArray != null && mUpdateArray.length() > 10) { + commitUpdate(); + } + + if (mUpdateArray == null) + mUpdateArray = new JSONArray(); + mUpdateArray.put(node.getUpdateAction(getActionId())); + } + } + + public void moveTask(Task task, TaskList preParent, TaskList curParent)//移动一个任务,通过getGid获取task所属的Id,还是通过JSONObject和postRequest实现 + throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + // action_list + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); + if (preParent == curParent && task.getPriorSibling() != null) {//只有当移动是发生在任务列表中且不是第一个时设置优先级 + // put prioring_sibing_id only if moving within the tasklist and + // it is not the first one + action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); + } + action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); + action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); + if (preParent != curParent) {//当移动发生在不同的任务列表之间,设置为dest_list + // put the dest_list only if moving between tasklists + action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); + } + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("move task: handing jsonobject failed"); + } + } + + public void deleteNode(Node node) throws NetworkFailureException {//删除节点,过程类似移动 + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // action_list + node.setDeleted(true); + actionList.put(node.getUpdateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + mUpdateArray = null; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("delete node: handing jsonobject failed"); + } + } + + public JSONArray getTaskLists() throws NetworkFailureException {//获取任务列表,首先通过getURI在网上获取数据,在截取所需部分内容返回 + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + try { + HttpGet httpGet = new HttpGet(mGetUrl); + HttpResponse response = null; + response = mHttpClient.execute(httpGet); + + // get the task list + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin != -1 && end != -1 && begin < end) {//带参数的获取指定的任务列表 + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); + } catch (ClientProtocolException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (IOException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task lists: handing jasonobject failed"); + } + } + + public JSONArray getTaskList(String listGid) throws NetworkFailureException {//方法:对于已经获取的任务列表,可以通过其id来获取到 + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + // action_list 通过action.pu()t对JSONObject对象action添加元素,通过jsPost.put()对jsPost添加相关元素,然后通过postRequest()提交更新后的请求并返回一个JSONObject的对象,最后使用jsResponse.getJSONArray( )获取jsResponse中的JSONArray值并作为函数返回值 + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); + action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + JSONObject jsResponse = postRequest(jsPost); + return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); + } catch (JSONException e) {//处理异常 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task list: handing jsonobject failed"); + } + } + + public Account getSyncAccount() { + return mAccount; + }//获得同步账户 + + public void resetUpdateArray() { + mUpdateArray = null; + }//重置更新内容 +} diff --git a/src/gatsk/GTaskManager.java b/src/gatsk/GTaskManager.java new file mode 100644 index 0000000..ebfd7ca --- /dev/null +++ b/src/gatsk/GTaskManager.java @@ -0,0 +1,800 @@ +/* + * 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.remote; + +import android.app.Activity; +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.R; +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.data.MetaData; +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.SqlNote; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + + +public class GTaskManager {//GTask管理类,封装了对GTask进行管理的一些方法 + private static final String TAG = GTaskManager.class.getSimpleName(); + + public static final int STATE_SUCCESS = 0;//成功 + + public static final int STATE_NETWORK_ERROR = 1;//网络错误 + + public static final int STATE_INTERNAL_ERROR = 2; + + public static final int STATE_SYNC_IN_PROGRESS = 3; + + public static final int STATE_SYNC_CANCELLED = 4; + + private static GTaskManager mInstance = null;//private 定义一系列不可被外部的类访问的量 + + private Activity mActivity; + + private Context mContext;//构造函数 + + private ContentResolver mContentResolver; + + private boolean mSyncing; + + private boolean mCancelled; + + private HashMap mGTaskListHashMap; + + private HashMap mGTaskHashMap; + + private HashMap mMetaHashMap; + + private TaskList mMetaList; + + private HashSet mLocalDeleteIdMap; + + private HashMap mGidToNid; + + private HashMap mNidToGid; + + private GTaskManager() {//类的构造函数,对其内部变量进行初始化 + mSyncing = false;//正在同步标识,false代表未同步 + mCancelled = false; + mGTaskListHashMap = new HashMap(); + mGTaskHashMap = new HashMap(); + mMetaHashMap = new HashMap(); + mMetaList = null; + mLocalDeleteIdMap = new HashSet(); + mGidToNid = new HashMap(); + mNidToGid = new HashMap(); + } + + public static synchronized GTaskManager getInstance() {//synchronized指明该函数可以运行在多线程下 + if (mInstance == null) { + mInstance = new GTaskManager(); + } + return mInstance; + } + + public synchronized void setActivityContext(Activity activity) {//对类的当前实例进行加锁,防止其他线程同时访问该类的该实例的所有synchronized块 + // used for getting authtoken + mActivity = activity; + } + + public int sync(Context context, GTaskASyncTask asyncTask) {//实现本地和远程同步的操作 + if (mSyncing) { + Log.d(TAG, "Sync is in progress"); + return STATE_SYNC_IN_PROGRESS; + } + mContext = context; + mContentResolver = mContext.getContentResolver(); + mSyncing = true; + mCancelled = false; + mGTaskListHashMap.clear(); + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + + try {//异常处理程序 + GTaskClient client = GTaskClient.getInstance(); + client.resetUpdateArray(); + + // login google task + if (!mCancelled) { + if (!client.login(mActivity)) { + throw new NetworkFailureException("login google task failed"); + }//登录 google 任务失败 + } + + // get the task list from google + asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); + initGTaskList();//调用下面自定义的方法,初始化GTaskList + + // do content sync work + asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); + syncContent();//同步便签内容 + } catch (NetworkFailureException e) { + Log.e(TAG, e.toString()); + return STATE_NETWORK_ERROR; + } catch (ActionFailureException e) { + Log.e(TAG, e.toString()); + return STATE_INTERNAL_ERROR; + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return STATE_INTERNAL_ERROR; + } finally {//结束后清空环境 + mGTaskListHashMap.clear(); + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + mSyncing = false; + } + + return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;//若在同步时操作未取消,则说明同步成功,否则返回同步操作取消 + } + + private void initGTaskList() throws NetworkFailureException {//初始化GTask列表,将google上的JSONTaskList转为本地任务列表 + if (mCancelled) + return; + GTaskClient client = GTaskClient.getInstance(); + try {//客户端获取任务列表 + JSONArray jsTaskLists = client.getTaskLists(); + + // init meta list first + mMetaList = null; + for (int i = 0; i < jsTaskLists.length(); i++) { + JSONObject object = jsTaskLists.getJSONObject(i); + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); + + if (name//如果 name 等于 字符串 "[MIUI_Notes]" + "METADATA",执行if语句块 + .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { + mMetaList = new TaskList(); + mMetaList.setContentByRemoteJSON(object); + + // load meta data + JSONArray jsMetas = client.getTaskList(gid); + for (int j = 0; j < jsMetas.length(); j++) { + object = (JSONObject) jsMetas.getJSONObject(j); + MetaData metaData = new MetaData(); + metaData.setContentByRemoteJSON(object); + if (metaData.isWorthSaving()) { + mMetaList.addChildTask(metaData); + if (metaData.getGid() != null) { + mMetaHashMap.put(metaData.getRelatedGid(), metaData);//把元数据放到哈希表中 + } + } + } + } + } + + // create meta list if not existed + if (mMetaList == null) {//若元数据列表不存在则创建一个 + mMetaList = new TaskList(); + mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META); + GTaskClient.getInstance().createTaskList(mMetaList); + } + + // init task list + for (int i = 0; i < jsTaskLists.length(); i++) {//以下循环用于初始化任务列表 + JSONObject object = jsTaskLists.getJSONObject(i); + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); + + if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) + && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META)) { + TaskList tasklist = new TaskList();//创建一个新的任务列表 + tasklist.setContentByRemoteJSON(object); + mGTaskListHashMap.put(gid, tasklist); + mGTaskHashMap.put(gid, tasklist); + + // load tasks + JSONArray jsTasks = client.getTaskList(gid); + for (int j = 0; j < jsTasks.length(); j++) {//任务id号 + object = (JSONObject) jsTasks.getJSONObject(j); + gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + Task task = new Task(); + task.setContentByRemoteJSON(object); + if (task.isWorthSaving()) {//判断该任务有无价值保存 + task.setMetaInfo(mMetaHashMap.get(gid)); + tasklist.addChildTask(task); + mGTaskHashMap.put(gid, task); + } + } + } + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("initGTaskList: handing JSONObject failed"); + } + } + + private void syncContent() throws NetworkFailureException {//实现内容同步 + int syncType; + Cursor c = null; + String gid; + Node node; + + mLocalDeleteIdMap.clear(); + + if (mCancelled) {//对于本地已删除的便签采取的动作 + return; + } + + // for local deleted note + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type<>? AND parent_id=?)", new String[] { + String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) + }, null); + if (c != null) { + while (c.moveToNext()) { + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); + } + + mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); + } + } else { + Log.w(TAG, "failed to query trash folder"); + } + } finally {//最后把c关闭并重置 + if (c != null) { + c.close(); + c = null; + } + } + + // sync folder first + syncFolder(); + + // for note existing in database + try {//对于数据库中已经存在的便签,采取以下操作 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type=? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c != null) { + while (c.moveToNext()) { + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); + syncType = node.getSyncAction(c); + } else { + if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { + // local add + syncType = Node.SYNC_ACTION_ADD_REMOTE; + } else { + // remote delete + syncType = Node.SYNC_ACTION_DEL_LOCAL; + } + } + doContentSync(syncType, node, c); + } + } else { + Log.w(TAG, "failed to query existing note in database"); + } + + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // go through remaining items//访问保留的项目 + Iterator> iter = mGTaskHashMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + node = entry.getValue(); + doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); + } + + // mCancelled can be set by another thread, so we neet to check one by + // one + // clear local delete table + if (!mCancelled) {//终止标识有可能被其他进程改变,因此需要一个个进行检查 + if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { + throw new ActionFailureException("failed to batch-delete local deleted notes"); + } + } + + // refresh local sync id + if (!mCancelled) {//更新同步表 + GTaskClient.getInstance().commitUpdate(); + refreshLocalSyncId(); + } + + } + + private void syncFolder() throws NetworkFailureException {//初始化文件夹。放在第一种情况之后是因为第一种情况不需要初始化文件夹 + Cursor c = null; + String gid; + Node node; + int syncType; + + if (mCancelled) { + return; + } + + // for root folder + try { + c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, + Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); + if (c != null) { + c.moveToNext(); + gid = c.getString(SqlNote.GTASK_ID_COLUMN);//获取指针指向内容对应的gid + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); + mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); + // for system folder, only update remote name if necessary + if (!node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) + doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); + } else { + doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); + } + } else { + Log.w(TAG, "failed to query root folder");//出现异常时,在日志中写回出错信息 + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // for call-note folder + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", + new String[] { + String.valueOf(Notes.ID_CALL_RECORD_FOLDER) + }, null); + if (c != null) { + if (c.moveToNext()) { + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); + mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); + // for system folder, only update remote name if + // necessary + if (!node.getName().equals(//若当前访问的文件夹是系统文件夹则只需要更新 + GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_CALL_NOTE)) + doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); + } else { + doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); + } + } + } else { + Log.w(TAG, "failed to query call note folder"); + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // for local existing folders + try {//对于本地已存在的文件的操作 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type=? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c != null) { + while (c.moveToNext()) {//使指针遍历所有的文件夹 + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); + syncType = node.getSyncAction(c); + } else { + if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { + // local add + syncType = Node.SYNC_ACTION_ADD_REMOTE; + } else { + // remote delete + syncType = Node.SYNC_ACTION_DEL_LOCAL; + } + } + doContentSync(syncType, node, c); + } + } else {//进行同步操作 + Log.w(TAG, "failed to query existing folder"); + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + + // for remote add folders + Iterator> iter = mGTaskListHashMap.entrySet().iterator(); + while (iter.hasNext()) {//使用迭代器对远程增添的内容进行遍历 + Map.Entry entry = iter.next(); + gid = entry.getKey(); + node = entry.getValue(); + if (mGTaskHashMap.containsKey(gid)) { + mGTaskHashMap.remove(gid); + doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); + } + } + + if (!mCancelled) + GTaskClient.getInstance().commitUpdate(); + } + + private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {//内容同步,同步同步类型、节点以及数据库指针 + if (mCancelled) { + return; + } + + MetaData meta; + switch (syncType) { + case Node.SYNC_ACTION_ADD_LOCAL: + addLocalNode(node); + break; + case Node.SYNC_ACTION_ADD_REMOTE: + addRemoteNode(node, c); + break; + case Node.SYNC_ACTION_DEL_LOCAL: + meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN)); + if (meta != null) { + GTaskClient.getInstance().deleteNode(meta); + } + mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); + break; + case Node.SYNC_ACTION_DEL_REMOTE: + meta = mMetaHashMap.get(node.getGid()); + if (meta != null) { + GTaskClient.getInstance().deleteNode(meta); + } + GTaskClient.getInstance().deleteNode(node); + break; + case Node.SYNC_ACTION_UPDATE_LOCAL: + updateLocalNode(node, c); + break; + case Node.SYNC_ACTION_UPDATE_REMOTE: + updateRemoteNode(node, c); + break; + case Node.SYNC_ACTION_UPDATE_CONFLICT: + // merging both modifications maybe a good idea + // right now just use local update simply + updateRemoteNode(node, c); + break; + case Node.SYNC_ACTION_NONE: + break; + case Node.SYNC_ACTION_ERROR: + default: + throw new ActionFailureException("unkown sync action type"); + }//抛出异常 + } + + private void addLocalNode(Node node) throws NetworkFailureException { + if (mCancelled) { + return; + } + + SqlNote sqlNote; + if (node instanceof TaskList) { + if (node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { + sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); + } else if (node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { + sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); + } else { + sqlNote = new SqlNote(mContext); + sqlNote.setContent(node.getLocalJSONFromContent()); + sqlNote.setParentId(Notes.ID_ROOT_FOLDER); + } + } else {//代码块:若待增添节点不是任务列表中的节点,进一步操作 + sqlNote = new SqlNote(mContext); + JSONObject js = node.getLocalJSONFromContent(); + try { + if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + if (note.has(NoteColumns.ID)) { + long id = note.getLong(NoteColumns.ID); + if (DataUtils.existInNoteDatabase(mContentResolver, id)) { + // the id is not available, have to create a new one + note.remove(NoteColumns.ID); + } + } + } + + if (js.has(GTaskStringUtils.META_HEAD_DATA)) {//以下为判断便签中的数据条目 + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + if (data.has(DataColumns.ID)) { + long dataId = data.getLong(DataColumns.ID); + if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { + // the data id is not available, have to create + // a new one + data.remove(DataColumns.ID); + } + } + } + + } + } catch (JSONException e) {//出现异常时,打印异常信息 + Log.w(TAG, e.toString()); + e.printStackTrace(); + } + sqlNote.setContent(js); + + Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); + if (parentId == null) { + Log.e(TAG, "cannot find task's parent id locally"); + throw new ActionFailureException("cannot add local node"); + } + sqlNote.setParentId(parentId.longValue()); + } + + // create the local node + sqlNote.setGtaskId(node.getGid()); + sqlNote.commit(false); + + // update gid-nid mapping + mGidToNid.put(node.getGid(), sqlNote.getId()); + mNidToGid.put(sqlNote.getId(), node.getGid()); + + // update meta + updateRemoteMeta(node.getGid(), sqlNote); + } + + private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {//更新本地节点,两个传入参数,一个是待更新的节点,一个是指向待增加位置的指针 + if (mCancelled) { + return; + } + + SqlNote sqlNote; + // update the note locally + sqlNote = new SqlNote(mContext, c); + sqlNote.setContent(node.getLocalJSONFromContent()); + + Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) + : new Long(Notes.ID_ROOT_FOLDER); + if (parentId == null) { + Log.e(TAG, "cannot find task's parent id locally"); + throw new ActionFailureException("cannot update local node"); + } + sqlNote.setParentId(parentId.longValue()); + sqlNote.commit(true); + + // update meta info + updateRemoteMeta(node.getGid(), sqlNote); + } + + private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {//添加远程节点 + if (mCancelled) { + return; + } + + SqlNote sqlNote = new SqlNote(mContext, c); + Node n; + + // update remotely + if (sqlNote.isNoteType()) { + Task task = new Task(); + task.setContentByLocalJSON(sqlNote.getContent()); + + String parentGid = mNidToGid.get(sqlNote.getParentId()); + if (parentGid == null) { + Log.e(TAG, "cannot find task's parent tasklist"); + throw new ActionFailureException("cannot add remote task"); + } + mGTaskListHashMap.get(parentGid).addChildTask(task); + + GTaskClient.getInstance().createTask(task); + n = (Node) task; + + // add meta + updateRemoteMeta(task.getGid(), sqlNote); + } else { + TaskList tasklist = null; + + // we need to skip folder if it has already existed//当文件夹存在则跳过,若不存在则创建新的文件夹 + String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX; + if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) + folderName += GTaskStringUtils.FOLDER_DEFAULT; + else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER) + folderName += GTaskStringUtils.FOLDER_CALL_NOTE; + else + folderName += sqlNote.getSnippet(); + + Iterator> iter = mGTaskListHashMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + String gid = entry.getKey(); + TaskList list = entry.getValue(); + + if (list.getName().equals(folderName)) { + tasklist = list; + if (mGTaskHashMap.containsKey(gid)) { + mGTaskHashMap.remove(gid); + } + break; + } + } + + // no match we can add now + if (tasklist == null) {//直接新建一个任务链 + tasklist = new TaskList(); + tasklist.setContentByLocalJSON(sqlNote.getContent()); + GTaskClient.getInstance().createTaskList(tasklist); + mGTaskListHashMap.put(tasklist.getGid(), tasklist); + } + n = (Node) tasklist; + } + + // update local note + sqlNote.setGtaskId(n.getGid()); + sqlNote.commit(false); + sqlNote.resetLocalModified(); + sqlNote.commit(true); + + // gid-id mapping + mGidToNid.put(n.getGid(), sqlNote.getId()); + mNidToGid.put(sqlNote.getId(), n.getGid()); + } + + private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {//更新远程结点,参数node是要更新的结点,c是数据库的指针 + if (mCancelled) { + return; + } + + SqlNote sqlNote = new SqlNote(mContext, c); + + // update remotely + node.setContentByLocalJSON(sqlNote.getContent()); + GTaskClient.getInstance().addUpdateNode(node); + + // update meta + updateRemoteMeta(node.getGid(), sqlNote); + + // move task if necessary + if (sqlNote.isNoteType()) {//判断节点类型是否符合要求 + Task task = (Task) node; + TaskList preParentList = task.getParent(); + + String curParentGid = mNidToGid.get(sqlNote.getParentId()); + if (curParentGid == null) { + Log.e(TAG, "cannot find task's parent tasklist"); + throw new ActionFailureException("cannot update remote task"); + } + TaskList curParentList = mGTaskListHashMap.get(curParentGid); + + if (preParentList != curParentList) { + preParentList.removeChildTask(task); + curParentList.addChildTask(task); + GTaskClient.getInstance().moveTask(task, preParentList, curParentList); + } + } + + // clear local modified flag + sqlNote.resetLocalModified(); + sqlNote.commit(true); + } + + private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {//更新远程结点的数据,与上一个函数不同的是这里只更新数据,因此只用将metadata复制上去即可。参数gid是要更新的数据对应的在数据库中的结点id,sqlnote是用于获得数据内容 + if (sqlNote != null && sqlNote.isNoteType()) { + MetaData metaData = mMetaHashMap.get(gid); + if (metaData != null) { + metaData.setMeta(gid, sqlNote.getContent()); + GTaskClient.getInstance().addUpdateNode(metaData); + } else { + metaData = new MetaData(); + metaData.setMeta(gid, sqlNote.getContent()); + mMetaList.addChildTask(metaData); + mMetaHashMap.put(gid, metaData); + GTaskClient.getInstance().createTask(metaData); + } + } + } + + private void refreshLocalSyncId() throws NetworkFailureException {//刷新本地便签id,从远程同步 + if (mCancelled) { + return; + } + + // get the latest gtask list + mGTaskHashMap.clear(); + mGTaskListHashMap.clear(); + mMetaHashMap.clear(); + initGTaskList(); + + Cursor c = null; + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type<>? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c != null) { + while (c.moveToNext()) { + String gid = c.getString(SqlNote.GTASK_ID_COLUMN); + Node node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + ContentValues values = new ContentValues(); + values.put(NoteColumns.SYNC_ID, node.getLastModified()); + mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,//进行批量更改,选择参数为NULL,应该可以用insert替换,参数分别为表名和需要更新的value对象。 + c.getLong(SqlNote.ID_COLUMN)), values, null, null); + } else { + Log.e(TAG, "something is missed"); + throw new ActionFailureException( + "some local items don't have gid after sync"); + } + } + } else { + Log.w(TAG, "failed to query local note to refresh sync id"); + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + } + + public String getSyncAccount() { + return GTaskClient.getInstance().getSyncAccount().name; + }//获取同步账号 + + public void cancelSync() { + mCancelled = true; + }//取消同步,置mCancelled为true +}//若需要取消同步,则将mCancelled值设置为真 diff --git a/src/gatsk/GTaskSyncService.java b/src/gatsk/GTaskSyncService.java new file mode 100644 index 0000000..522bdb9 --- /dev/null +++ b/src/gatsk/GTaskSyncService.java @@ -0,0 +1,128 @@ +/* + * 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.remote; + +import android.app.Activity; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.IBinder; + +public class GTaskSyncService extends Service {//service通常用作在后台处理耗时的逻辑,不用与用户进行交互,即使应用被销毁依然可以继续工作。 + public final static String ACTION_STRING_NAME = "sync_action_type";//定义一系列静态变量 + + public final static int ACTION_START_SYNC = 0;//开始同步 + + public final static int ACTION_CANCEL_SYNC = 1; + + public final static int ACTION_INVALID = 2; + + public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";//服务广播的名称 + + public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; + + public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";//进程消息 + + private static GTaskASyncTask mSyncTask = null; + + private static String mSyncProgress = ""; + + private void startSync() {//开始同步 + if (mSyncTask == null) { + mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { + public void onComplete() {//实现了在GTaskASyncTask类中定义的接口onComplete( ) + mSyncTask = null; + sendBroadcast(""); + stopSelf(); + } + }); + sendBroadcast(""); + mSyncTask.execute(); + } + } + + private void cancelSync() {//取消同步 + if (mSyncTask != null) { + mSyncTask.cancelSync(); + } + } + + @Override + public void onCreate() { + mSyncTask = null; + }//初始化一个service + + @Override + public int onStartCommand(Intent intent, int flags, int startId) {//充当重启便签指令 + Bundle bundle = intent.getExtras(); + if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { + switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { + case ACTION_START_SYNC: + startSync(); + break; + case ACTION_CANCEL_SYNC:// 两种情况,开始同步或者取消同步 + cancelSync(); + break; + default: + break; + } + return START_STICKY; + } + return super.onStartCommand(intent, flags, startId); + } + + @Override + public void onLowMemory() {//发送广播 + if (mSyncTask != null) { + mSyncTask.cancelSync(); + } + } + + public IBinder onBind(Intent intent) { + return null; + }//service服务中的绑定操作 + + public void sendBroadcast(String msg) {//发送广播内容 + mSyncProgress = msg; + Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); + intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); + intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); + sendBroadcast(intent); + } + + public static void startSync(Activity activity) {//启动同步 + GTaskManager.getInstance().setActivityContext(activity); + Intent intent = new Intent(activity, GTaskSyncService.class); + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); + activity.startService(intent); + } + + public static void cancelSync(Context context) {//取消同步 + Intent intent = new Intent(context, GTaskSyncService.class); + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); + context.startService(intent); + } + + public static boolean isSyncing() { + return mSyncTask != null; + }//判断当前是否处于同步状态 + + public static String getProgressString() { + return mSyncProgress; + }//返回当前同步状态 +} diff --git a/src/gatsk/MetaData.java b/src/gatsk/MetaData.java new file mode 100644 index 0000000..df043ae --- /dev/null +++ b/src/gatsk/MetaData.java @@ -0,0 +1,82 @@ +/* + * 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;//包名,继承于Task,主要用于记录数据的变化。 + +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONException; +import org.json.JSONObject; + + +public class MetaData extends Task {//创建一个继承 Task 的类MataData + private final static String TAG = MetaData.class.getSimpleName();//调用getSimpleName ()函数,得到类的简写名称存入字符串TAG中 + + private String mRelatedGid = null;//创建私有变量mRelatedGid,并初始化为null + + public void setMeta(String gid, JSONObject metaInfo) {//调用JSONObject库函数put (),Task类中的setNotes ()和setName ()函数,设置数据,即生成元数据库 + try { + metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); + } catch (JSONException e) {//捕捉异常 + Log.e(TAG, "failed to put related gid"); + } + setNotes(metaInfo.toString()); + setName(GTaskStringUtils.META_NOTE_NAME);//设置gtask的名字 + } + + public String getRelatedGid() { + return mRelatedGid; + }//获取相关联的Gid + + @Override + public boolean isWorthSaving() { + return getNotes() != null; + }//判断是否值得存放,即当前数据是否有效,若数据非空则返回真值 + + @Override + public void setContentByRemoteJSON(JSONObject js) {//使用远程json数据对象设置元数据内容 + super.setContentByRemoteJSON(js); + if (getNotes() != null) {//如果数据非空,获取jsono metainfo和相关gid + try { + JSONObject metaInfo = new JSONObject(getNotes().trim()); + mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); + } catch (JSONException e) {//catch中的代码是进行异常处理的 + Log.w(TAG, "failed to get related gid"); + mRelatedGid = null; + } + } + } + + @Override + public void setContentByLocalJSON(JSONObject js) {//使用本地json数据对象设置元数据内容,一般不会用到,若用到,则抛出异常 + // this function should not be called + throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); + } + + @Override + public JSONObject getLocalJSONFromContent() {//从元数据内容中获取本地json对象,抛出异常 + 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/gatsk/NetworkFailureException.java b/src/gatsk/NetworkFailureException.java new file mode 100644 index 0000000..2e4ae44 --- /dev/null +++ b/src/gatsk/NetworkFailureException.java @@ -0,0 +1,33 @@ +/* + * 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.exception;//小米便签网络异常处理包,该源文件里定义的所有类都属于这个包 + +public class NetworkFailureException extends Exception { + private static final long serialVersionUID = 2107610287180234136L; +//serialVersionUID相当于java类的身份证。主要用于版本控制。 + public NetworkFailureException() { + super(); + } + + public NetworkFailureException(String paramString) { + super(paramString); + }//调用父类具有相同形参paramString的构造方法 + + public NetworkFailureException(String paramString, Throwable paramThrowable) { + super(paramString, paramThrowable);// 调用父类具有相同形参paramString和paramThrowable的构造方法 + } +} diff --git a/src/gatsk/Node.java b/src/gatsk/Node.java new file mode 100644 index 0000000..f52992d --- /dev/null +++ b/src/gatsk/Node.java @@ -0,0 +1,101 @@ +/* + * 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 org.json.JSONObject; + +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; + + private String mGid;//记录最后一次修改时间 + + private String mName;//记录是否被删除 + + private long mLastModified;//记录最后一次修改时间 + + private boolean mDeleted; + + public Node() {//构造函数,进行初始化,界面没有,名字为空,最后一次修改时间为0(没有修改),表征是否删除。 + mGid = null; + mName = ""; + mLastModified = 0; + mDeleted = false; + } + + public abstract JSONObject getCreateAction(int actionId);//获取创建信息 + + public abstract JSONObject getUpdateAction(int actionId);//获取需要更新活动的ID + + public abstract void setContentByRemoteJSON(JSONObject js);//创建相应的对象,并且实现远端与本地的同步操作 + + public abstract void setContentByLocalJSON(JSONObject js);//创建相应对象进行本地操作 + + public abstract JSONObject getLocalJSONFromContent();//声明JSONObject对象抽象类,从目录中获取本地JSON + + public abstract int getSyncAction(Cursor c);//声明int抽象类,获取同步行为代号 + + 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; + }//函数:返回mGid + + public String getName() { + return this.mName; + }//获取名称 + + public long getLastModified() { + return this.mLastModified; + }//获取最近创建时间标识 + + public boolean getDeleted() { + return this.mDeleted; + }//获取删除标识 + +} diff --git a/src/gatsk/SqlData.java b/src/gatsk/SqlData.java new file mode 100644 index 0000000..c330d58 --- /dev/null +++ b/src/gatsk/SqlData.java @@ -0,0 +1,189 @@ +/* + * 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.content.ContentResolver; +import android.content.ContentUris; +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.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE; +import net.micode.notes.gtask.exception.ActionFailureException; + +import org.json.JSONException; +import org.json.JSONObject; + + +public class SqlData {//数据库中基本数据类:读取数据、获取数据库中数据、提交数据到数据库 + private static final String TAG = SqlData.class.getSimpleName();//调用getSimpleName ()函数来得到类的简写名称存入字符串TAG中 + + private static final int INVALID_ID = -99999;//将得到类的简写名称存入字符串TAG中,为mDataId置初始值-99999 + + public static final String[] PROJECTION_DATA = new String[] {//新建一个字符串数组,集合了interface DataColumns中所有SF常量 + DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,//获得数据列id,mime类型,内容,1类型数据,3类型数据 + DataColumns.DATA3 + }; + + public static final int DATA_ID_COLUMN = 0;//以下五个变量作为sql表中5列的编号 + + 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;//定义的一些私有全局变量,可以与sqlNote中的变量相对应分析 + + 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) {//第一种SQLData的构造方式,只从上下文获取,初始化其中的变量 + mContentResolver = context.getContentResolver(); + mIsCreate = true; + mDataId = INVALID_ID; + mDataMimeType = DataConstants.NOTE; + mDataContent = ""; + mDataContentData1 = 0; + mDataContentData3 = "";//数据类型 + mDiffDataValues = new ContentValues();//创建内容 + } + + public SqlData(Context context, Cursor c) {//构造函数,初始化数据,参数类型分别为 Context 和 Cursor + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(c); + mDiffDataValues = new ContentValues(); + } + + private void loadFromCursor(Cursor c) {//构造函数,初始化数据,参数类型分别为 Context 和 Cursor + mDataId = c.getLong(DATA_ID_COLUMN);//调用cursor类的方法,获取数据id,参数为id长度 + 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); + } + + public void setContent(JSONObject js) throws JSONException {//设置共享数据,并且抛出JSON类型的异常与处理机制 + long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;//设置数据 id,如果传入的 JSONObject 对象中存在DataColumns.ID则获取并设置,否则设为INVALID_ID + if (mIsCreate || mDataId != dataId) {//如果是根据目录创建的或者当前数据的ID与元数据的ID不符,那么发送更新此ID 的请求 + mDiffDataValues.put(DataColumns.ID, dataId); + } + mDataId = dataId;//与共享数据库同步后,共享数据ID就等于数据ID + + String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)//若json中有MIME_TYPE这一项,则将其获取,否则,将其定义为notes类中定义的文本类型 + : DataConstants.NOTE; + if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {//如果共享数据文本类型与数据文本类型不同,则将原有的数据类型,放入共享库中 + mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); + } + mDataMimeType = dataMimeType; + + String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; + if (mIsCreate || !mDataContent.equals(dataContent)) {//对比DataContent,并更新contentValue中的DataContent + mDiffDataValues.put(DataColumns.CONTENT, dataContent); + } + mDataContent = dataContent;//共享数据同步后,共享数据内容等于该数据内容 + + long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;// 如果传入的JSONObject对象有DataColumn.DATA1一项,那么将其获取,否则。将其设置为0。 + if (mIsCreate || mDataContentData1 != dataContentData1) { + mDiffDataValues.put(DataColumns.DATA1, dataContentData1); + } + mDataContentData1 = dataContentData1; + + String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; + if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { + mDiffDataValues.put(DataColumns.DATA3, dataContentData3); + } + mDataContentData3 = dataContentData3; + } +//获取共享数据内容及提供异常抛出与处理机制 + public JSONObject getContent() throws JSONException { + if (mIsCreate) { + Log.e(TAG, "it seems that we haven't created this in database yet");//判断是否创建数据表 + return null; + } + JSONObject js = new JSONObject();//将相关数据放入新创建的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; + } +//将当前数据提交到数据库 + public void commit(long noteId, boolean validateVersion, long version) {//commit 函数用于把当前所做的修改保存到数据库 + + if (mIsCreate) {//判断是否是第一种SqlData构造方式 + if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {//如果该id是无效id且在共享数据中不存在该数据id对应的键,则从共享数据中移除 + mDiffDataValues.remove(DataColumns.ID);//删除数据 + } + + mDiffDataValues.put(DataColumns.NOTE_ID, noteId);//加入的ID有效,也就是操作有效,则数据库加入这个note的ID,这条data对应在这个note的ID下 + Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);//在note的资源标识下加入data数据 + try {//上一句实现的是URI到Uri的转换/将路径转换为Long型,附识给当前id + mDataId = Long.valueOf(uri.getPathSegments().get(1));//获取有效便签id并创建 + } catch (NumberFormatException e) {//如果转换出错则日志中显示错误“获取note的ID出错” + Log.e(TAG, "Get note id error :" + e.toString());//获取note id错误,e.toString()获取异常类型和异常详细消息 + throw new ActionFailureException("create note failed"); + } + } else { + if (mDiffDataValues.size() > 0) {//若共享数据存在,则通过内容解析器更新关于新URI的共享数据 + int result = 0; + if (!validateVersion) { + result = mContentResolver.update(ContentUris.withAppendedId(//如果版本已确认,则结果还记录下所在note的Id,以及版本号 + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); + } else {//如果版本确认了,则从数据库中选取对应版本的id进行更新 + result = mContentResolver.update(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, + " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { + String.valueOf(noteId), String.valueOf(version) + });//更新不存在,可能是用户在同步时已更新 + } + if (result == 0) { + Log.w(TAG, "there is no update. maybe user updates note when syncing"); + } + } + } + + mDiffDataValues.clear();//回到初始化,清空,表示已经更新 + mIsCreate = false; + } + + public long getId() { + return mDataId; + } +} diff --git a/src/gatsk/SqlNote.java b/src/gatsk/SqlNote.java new file mode 100644 index 0000000..689b1be --- /dev/null +++ b/src/gatsk/SqlNote.java @@ -0,0 +1,505 @@ +/* + * 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; + + +public class SqlNote {//调用getSimpleName ()函数得到类的简写名称存入字符串TAG中 + private static final String TAG = SqlNote.class.getSimpleName(); + + private static final int INVALID_ID = -99999;//将INVALID_ID 初始化为-99999 + + public static final String[] PROJECTION_NOTE = new String[] {//集合了interface NoteColumns中所有17个SF常量 + 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 + };//以下设置17个列的编号 + + public static final int ID_COLUMN = 0;//提醒时间 + + public static final int ALERTED_DATE_COLUMN = 1;//note的背景颜色 + + 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; + + public static final int PARENT_ID_COLUMN = 7; + + public static final int SNIPPET_COLUMN = 8; + + public static final int TYPE_COLUMN = 9; + + public static final int WIDGET_ID_COLUMN = 10; + + public static final int WIDGET_TYPE_COLUMN = 11; + + public static final int SYNC_ID_COLUMN = 12; + + public static final int LOCAL_MODIFIED_COLUMN = 13; + + public static final int ORIGIN_PARENT_ID_COLUMN = 14; + + public static final int GTASK_ID_COLUMN = 15; + + public static final int VERSION_COLUMN = 16; + + private Context mContext;//以下定义了17个内部变量,其中12个可以由content获得,5个需要初始化为0或者new + + private ContentResolver mContentResolver; + + private boolean mIsCreate; + + private long mId;//通过ArrayList记录note中的data + + 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) {//构造函数,参数只有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();//新建一个data的列表 + } + + public SqlNote(Context context, Cursor c) {//构造函数,参数有context和cursor,对cursor指向的对象进行初始化 + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(c); + mDataList = new ArrayList(); + if (mType == Notes.TYPE_NOTE)//如果是note类型,则调用下面的 loadDataContent()函数,加载数据内容 + loadDataContent(); + mDiffNoteValues = new ContentValues(); + } + + public SqlNote(Context context, long id) {//第三种构造方式,采用context和id + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; + loadFromCursor(id);//调用下面的 loadFromCursor函数,通过ID从光标处加载数据 + mDataList = new ArrayList(); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + mDiffNoteValues = new ContentValues(); + + } + + private void loadFromCursor(long id) {//通过id从光标处加载数据 + Cursor c = null; + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",//通过id获取ContentResolver中的相应内容,并赋给cursor + new String[] { + String.valueOf(id) + }, null);//如果获取成功,则cursor移动到下一条记录,并加载该记录 + 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); + } +//获取ID对应content内容,如果查询到该note的id确实有对应项,即cursor有对应,获取ID对应content内容 + private void loadDataContent() {//通过content机制获取共享数据并加载到数据库当前游标处 + Cursor c = null; + mDataList.clear(); + try {//获取ID对应content内容 + c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,//获得该ID对应的数据内容 + "(note_id=?)", new String[] { + String.valueOf(mId) + }, null);//查询到该note的id确实有对应项,即cursor有对应 + if (c != null) { + if (c.getCount() == 0) { + Log.w(TAG, "it seems that the note has not data"); + return; + } + while (c.moveToNext()) {//记录数量不为0,则循环直到记录不存在,不断地取出记录放到DataList中 + SqlData data = new SqlData(mContext, c); + mDataList.add(data); + } + } else { + Log.w(TAG, "loadDataContent: cursor = null"); + } + } finally {//论如何,最后需要关闭数据库游标 + if (c != null) + c.close(); + } + } + + public boolean setContent(JSONObject js) {//设置通过content机制共享的数据信息 + 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) {//文件夹只能更新摘要和类型 + // for folder we can only update the snnipet and type + String snippet = note.has(NoteColumns.SNIPPET) ? note//语句:如果共享数据存在摘要,则将其赋给snippet变量,否则该变量为空 + .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)//以下操作都和上面对snippet的操作一样,一起根据共享的数据设置SqlNote内容的上述17项 + : Notes.TYPE_NOTE; + if (mIsCreate || mType != type) {//如果是新建的或 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; + + int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note//获取数据的背景颜色 + .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); + if (mIsCreate || mBgColorId != bgColorId) {//如果只是通过上下文对note进行数据库操作,或者该背景颜色与原背景颜色不相同, + 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) {//如果只是通过上下文对note进行数据库操作,或者该创建日期与原创建日期不相同, + mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);//将该创建日期保存在mDiffNoteValue这个变量中,说明这两个值不相同 + } + mCreatedDate = createDate;//将该创建日期覆盖原创建日期 + + int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note + .getInt(NoteColumns.HAS_ATTACHMENT) : 0; + if (mIsCreate || mHasAttachment != hasAttachment) {//如果只是通过上下文对note进行数据库操作,或者该有无附件的布尔值与原有无附件的布尔值不相同, + 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) {//如果只是通过上下文对note进行数据库操作,或者该修改日期与原修改日期不相同, + mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); + } + mModifiedDate = modifiedDate; + + 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)) {//如果只是通过上下文对note进行数据库操作,或者该文本片段与原文本片段不相同, + 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; + + 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);//将该小部件ID保存在mDiffNoteValue这个变量中,说明这两个值不相同 + } + 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) {//如果只是通过上下文对note进行数据库操作,或者该原始父文件夹ID与原原始父文件夹ID不相同, + mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); + } + mOriginParent = originParent; + + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + SqlData sqlData = null; + if (data.has(DataColumns.ID)) {//该数据ID对应的数据如果存在,将对应的数据存在数据库中 + long dataId = data.getLong(DataColumns.ID); + for (SqlData temp : mDataList) { + if (dataId == temp.getId()) { + sqlData = temp; + } + } + } + + if (sqlData == null) { + sqlData = new SqlData(mContext); + mDataList.add(sqlData); + } + + sqlData.setContent(data);//最后为数据库数据进行设置 + } + } + } catch (JSONException e) {//出现JSONException时,日志显示错误,同时打印堆栈轨迹 + Log.e(TAG, e.toString());//获取异常类型和异常详细消息 + e.printStackTrace(); + return false; + } + return true; + } +//获取content机制提供的数据并加载到note中 + public JSONObject getContent() {//获取content机制提供的数据并加载到note中 + try { + JSONObject js = new JSONObject(); + + if (mIsCreate) { + Log.e(TAG, "it seems that we haven't created this in database yet"); + return null; + } + + JSONObject note = new JSONObject();//新建变量note用于传输共享数据 + if (mType == Notes.TYPE_NOTE) {//note类型 + note.put(NoteColumns.ID, mId); + note.put(NoteColumns.ALERTED_DATE, mAlertDate); + note.put(NoteColumns.BG_COLOR_ID, mBgColorId);//背景颜色ID + 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) {//将note中的data全部存入JSONArray中 + JSONObject data = sqlData.getContent(); + if (data != null) { + dataArray.put(data);//再将这个JSONArray对应共享数据mata,按键值对存入共享 + } + } + js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);//将元数据存入数组中 + } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {//类型为系统文件或目录文件时 + note.put(NoteColumns.ID, mId);//将id,类型,以及摘要,存入jsonobject,然后对应META_HEAD_NOTE键,存入共享 + 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; + } + + public void setParentId(long id) { + mParentId = id; + mDiffNoteValues.put(NoteColumns.PARENT_ID, id); + } +//设置当前ID的gtask的ID + public void setGtaskId(String gid) { + mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); + } +//同步id + public void setSyncId(long syncId) { + mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); + } + + public void resetLocalModified() { + mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); + }//初始化本地修改,即撤销所有当前修改 + + public long getId() { + return mId; + }//获得当前id + + public long getParentId() { + return mParentId; + }//获得当前id的父id + + 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);//那么就把这个ID移出便签列 + } + + Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);//插入该便签的uri + try { + mId = Long.valueOf(uri.getPathSegments().get(1)); + } catch (NumberFormatException e) {//捕获异常,转换出错,显示错误“获取note的id出现错误” + Log.e(TAG, "Get note id error :" + e.toString()); + throw new ActionFailureException("create note failed");//抛出异常,创建 note 失败 + } + if (mId == 0) { + throw new IllegalStateException("Create thread id failed"); + } + + if (mType == Notes.TYPE_NOTE) {//对于note类型,引用sqlData.commit方法操作 + 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");//尝试以无效 id 更新 note + } + 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) + }); + } + if (result == 0) {//如果内容解析器没有更新,那么报错:没有更新,或许用户在同步时进行更新 + Log.w(TAG, "there is no update. maybe user updates note when syncing"); + } + } + + if (mType == Notes.TYPE_NOTE) {//对note类型,还是对其中的data引用commit,从而实现目的 + 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/gatsk/Task.java b/src/gatsk/Task.java new file mode 100644 index 0000000..db1aa72 --- /dev/null +++ b/src/gatsk/Task.java @@ -0,0 +1,351 @@ +/* + * 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; + + +public class Task extends Node {//一个task类(任务),继承自Node类 + private static final String TAG = Task.class.getSimpleName();//调用 getSimpleName ()函数来得到类的简写名称并存入字符串TAG中 + + private boolean mCompleted;//以下四个变量用于Task构造,mCompleted判断是否完成 + + private String mNotes;//将在实例中存储数据的类型 + + private JSONObject mMetaInfo; + + private Task mPriorSibling;//优先兄弟task的指针 + + private TaskList mParent;//任务列表的指针 + + public Task() {//Task类的构造函数,对对象进行初始化 + super(); + mCompleted = false; + mNotes = null; + mPriorSibling = null; + mParent = null; + mMetaInfo = null;//对类的变量进行初始化 + } + + public JSONObject getCreateAction(int actionId) {//对操作号即actionId 进行一些操作的公用函数 + JSONObject js = new JSONObject(); + + 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();//创建实体数据并将name,创建者id,实体类型存入数据 + 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); + if (getNotes() != null) {//如果有文本输入 + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); + } + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + // parent_id + js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); + + // dest_parent_type + js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,//所在列表的id存入父id + GTaskStringUtils.GTASK_JSON_TYPE_GROUP); + + // list_id + js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());//存入列表id + + // prior_sibling_id + if (mPriorSibling != null) { + js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());//那么将其存入优先ID序列中 + } + + } 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) {//接收更新action + JSONObject js = new JSONObject(); + + try {//同样是使用try和catch进行异常处理操作,跟上面的差不多就不再赘述了 + // 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()); + if (getNotes() != null) {//如果存在 notes ,则将其也放入 entity 中 + 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 {//用try和catch进行异常处理操作 + // 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)) {//设置notes + setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); + } + + // name + if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {//设置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) {//通过本地的json设置内容 + if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) + || !js.has(GTaskStringUtils.META_HEAD_DATA)) { + Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");//那么反馈给用户出错信息 + } + + try {//否则进行try和catch的异常处理操作 + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + + if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {//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)) {//遍历 dataArray 查找与数据库中DataConstants.NOTE 记录信息一致的 data + setName(data.getString(DataColumns.CONTENT)); + break; + } + } + + } catch (JSONException e) {//异常处理操作 + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + } + + public JSONObject getLocalJSONFromContent() {//从content获取本地json + 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 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);//获取metainfo中的head_note + return js; + } else { + // synced task + JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);//定义一个数组并进行初始化 + + for (int i = 0; i < dataArray.length(); i++) {//遍历 dataArray 查找与数据库中DataConstants.NOTE 记录信息一致的 data + JSONObject data = dataArray.getJSONObject(i); + if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { + data.put(DataColumns.CONTENT, getName()); + break; + } + } + + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + return mMetaInfo; + } + } catch (JSONException e) { + Log.e(TAG, e.toString());//e.toString()获取异常类型和异常详细消息 + e.printStackTrace(); + return null; + } + } + + public void setMetaInfo(MetaData metaData) { + 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; + if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { + noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);//便签元数据已被删除,不存在,返回更新云端数据的同步行为 + } + + if (noteInfo == null) {//云端便签 id 已被删除,不存在,返回更新本地数据的同步行为 + Log.w(TAG, "it seems that note meta has been deleted"); + return SYNC_ACTION_UPDATE_REMOTE; + } + + if (!noteInfo.has(NoteColumns.ID)) {//便签 id 不匹配,返回更新本地数据的同步行为 + Log.w(TAG, "remote note id seems to be deleted"); + return SYNC_ACTION_UPDATE_LOCAL; + } + + // 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; + } + + 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())) {//判断gtask的id与获取的id是否匹配 + Log.e(TAG, "gtask id doesn't match"); + return SYNC_ACTION_ERROR; + } + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {//本地id与云端id一致,即更新云端 + // 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; + }//设定是note成员变量 + + public void setPriorSibling(Task priorSibling) { + this.mPriorSibling = priorSibling; + }//设置优先兄弟 task 的优先级 + + public void setParent(TaskList parent) { + this.mParent = parent; + }//设置这个任务的父节点 + + public boolean getCompleted() { + return this.mCompleted; + }//获取 task 是否修改完毕的记录 + + public String getNotes() { + return this.mNotes; + }//获取成员变量 mNotes 的信息 + + public Task getPriorSibling() { + return this.mPriorSibling; + }//获取优先兄弟 task + + public TaskList getParent() { + return this.mParent; + }//获取父节点列表 + +} diff --git a/src/gatsk/TaskList.java b/src/gatsk/TaskList.java new file mode 100644 index 0000000..0bf3642 --- /dev/null +++ b/src/gatsk/TaskList.java @@ -0,0 +1,343 @@ +/* + * 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.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; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + + +public class TaskList extends Node {//创建继承 Node的任务表类 + private static final String TAG = TaskList.class.getSimpleName();//调用getSimpleName ()函数得到类的简称存入字符串TAG中 + + private int mIndex;//当前Tasklist的指针 + + private ArrayList mChildren;//类中主要的保存数据的单元,用来实现一个以Task为元素的ArrayList + + public TaskList() {//TaskList 的构造函数 + super(); + mChildren = new ArrayList(); + mIndex = 1; + } + + public JSONObject getCreateAction(int actionId) {//生成并返回一个包含了一定数据的JSONObject实体 + JSONObject js = new JSONObject(); + + 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, mIndex); + + // entity_delta + JSONObject entity = new JSONObject();//.新建一个 JSONObject 对象,名为实体,将 name,creator id,entity type 三个信息存在一起 + 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_GROUP); + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);//将实体类型设置为“GROUP” + + } catch (JSONException e) { + Log.e(TAG, e.toString());//获取异常类型和异常详细消息 + e.printStackTrace(); + throw new ActionFailureException("fail to generate tasklist-create jsonobject"); + } + + return js; + } + + public JSONObject getUpdateAction(int actionId) {//接受更新action,返回jsonobject + JSONObject js = new JSONObject(); + + try {// 初始化 js 中的数据 + // 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(实体) + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); + 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 tasklist-update jsonobject"); + } + + return js; + } + + public void setContentByRemoteJSON(JSONObject js) {//通过云端 JSON 数据设置实例化对象 js 的内容 + if (js != null) { + try { + // id + if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {//如果传入的对象中含有GTASK_JSON_ID,说明动作的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)) {//语句块:对任务的name进行设置 + setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to get tasklist content from jsonobject");//通过 JSONObeject 获取任务表内容失败 + } + } + } + + public void setContentByLocalJSON(JSONObject js) {//通过本地 JSON 数据设置对象 js 内容 + if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { + Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); + } + + try { + JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);//NullPointerException这个异常出现在处理对象时对象不存在但又没有捕捉到进行处理的时候 + + if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {//若为一般类型的文件夹 + String name = folder.getString(NoteColumns.SNIPPET);//获取文件夹片段字符串作为文件夹名称 + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);//设置名称:MIUI系统文件夹前缀+文件夹名称 + } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { + if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)//若为根目录文件夹 + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);//MIUI系统文件夹前缀+默认文件夹名称 + else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) + 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) { + Log.e(TAG, e.toString());//获取异常类型和异常详细消息 + e.printStackTrace(); + } + } + + public JSONObject getLocalJSONFromContent() { + try { + JSONObject js = new JSONObject(); + JSONObject folder = new JSONObject();//创建一个 JSONObject 的实例化对象 folder + + String folderName = getName(); + if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) + folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), + folderName.length()); + 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); + + js.put(GTaskStringUtils.META_HEAD_NOTE, folder); + + return js; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + 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()) {//最近一次修改的 id 匹配成功,返回无的同步行为 + // 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())) {//如果获取的ID不匹配,返回同步动作失败 + 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) { + boolean ret = false; + if (task != null && !mChildren.contains(task)) { + ret = mChildren.add(task); + if (ret) {//若添加成功,则设置优先兄弟和父节点 + // need to set prior sibling and parent + task.setPriorSibling(mChildren.isEmpty() ? null : mChildren + .get(mChildren.size() - 1)); + task.setParent(this); + } + } + return ret;//返回值为是否成功添加任务 + } + + public boolean addChildTask(Task task, int index) {//在当前任务表的指定位置添加新的任务,index是指针。 + if (index < 0 || index > mChildren.size()) { + Log.e(TAG, "add child task: invalid index"); + return false; + } + + int pos = mChildren.indexOf(task);//获取要添加的任务在任务表中的位置 + if (task != null && pos == -1) { + mChildren.add(index, task); + + // update the task list + Task preTask = null;//更新任务表 + Task afterTask = null; + if (index != 0) + preTask = mChildren.get(index - 1); + if (index != mChildren.size() - 1) + afterTask = mChildren.get(index + 1); + + task.setPriorSibling(preTask);//使得三个任务前后连在一块 + if (afterTask != null)//下一个任务设置兄弟任务优先级 + afterTask.setPriorSibling(task); + } + + return true; + } + + public boolean removeChildTask(Task task) {//删除TaskList中的一个Task + boolean ret = false; + int index = mChildren.indexOf(task); + if (index != -1) { + ret = mChildren.remove(task);//删除mChildren中的任务。 + + if (ret) { + // reset prior sibling and parent + task.setPriorSibling(null); + task.setParent(null); + + // update the task list + if (index != mChildren.size()) {//代码块:删除成功后,要对任务列表进行更新 + mChildren.get(index).setPriorSibling( + index == 0 ? null : mChildren.get(index - 1)); + } + } + } + return ret; + } + + public boolean moveChildTask(Task task, int index) {//以下为对子任务的移动,直接查找,获取任务索引,依据索引查找,依据坐标查找以及设定和获取索引的操作 + + if (index < 0 || index >= mChildren.size()) { + Log.e(TAG, "move child task: invalid index"); + return false; + } + + int pos = mChildren.indexOf(task);//所要查找的子任务不存在,返回假值 + if (pos == -1) { + Log.e(TAG, "move child task: the task should in the list"); + return false; + } + + if (pos == index) + return true; + return (removeChildTask(task) && addChildTask(task, index)); + } + + public Task findChildTaskByGid(String gid) {//按gid寻找Task + for (int i = 0; i < mChildren.size(); i++) { + Task t = mChildren.get(i); + if (t.getGid().equals(gid)) { + return t; + } + } + return null; + } + + public int getChildTaskIndex(Task task) { + return mChildren.indexOf(task); + }//返回指定Task的index + + public Task getChildTaskByIndex(int index) { + if (index < 0 || index >= mChildren.size()) { + Log.e(TAG, "getTaskByIndex: invalid index"); + return null; + } + return mChildren.get(index); + } + + public Task getChilTaskByGid(String gid) {//通过索引获取子任务 + for (Task task : mChildren) { + if (task.getGid().equals(gid)) + return task; + } + return null; + } + + public ArrayList getChildTaskList() { + return this.mChildren; + }//获取子任务列表 + + public void setIndex(int index) { + this.mIndex = index; + }//设置任务索引 + + public int getIndex() { + return this.mIndex; + }//获取任务指针。 +}