blob: 03e606fb4305faa1275fbdc30df5ad16eb6ab7af [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080017package android.content;
18
Dianne Hackborn231cc602009-04-27 17:10:36 -070019import com.android.internal.os.AtomicFile;
20import com.android.internal.util.ArrayUtils;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080021import com.android.internal.util.FastXmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022
Dianne Hackborn231cc602009-04-27 17:10:36 -070023import org.xmlpull.v1.XmlPullParser;
24import org.xmlpull.v1.XmlPullParserException;
25import org.xmlpull.v1.XmlSerializer;
26
Fred Quintanad9d2f112009-04-23 13:36:27 -070027import android.accounts.Account;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070030import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.os.Bundle;
33import android.os.Environment;
34import android.os.Handler;
35import android.os.Message;
36import android.os.Parcel;
37import android.os.RemoteCallbackList;
38import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.util.Log;
Dianne Hackborn231cc602009-04-27 17:10:36 -070040import android.util.SparseArray;
41import android.util.Xml;
Fred Quintana307da1a2010-01-21 14:24:20 -080042import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
Dianne Hackborn231cc602009-04-27 17:10:36 -070044import java.io.File;
45import java.io.FileInputStream;
46import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070048import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070050import java.util.Iterator;
51import java.util.TimeZone;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080052import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053
54/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070055 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070057 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 * @hide
59 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070060public class SyncStorageEngine extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061 private static final String TAG = "SyncManager";
Dianne Hackborn231cc602009-04-27 17:10:36 -070062 private static final boolean DEBUG = false;
63 private static final boolean DEBUG_FILE = false;
Costin Manolache360e4542009-09-04 13:36:04 -070064
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080065 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
66
Dianne Hackborn231cc602009-04-27 17:10:36 -070067 // @VisibleForTesting
68 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
Dianne Hackborn231cc602009-04-27 17:10:36 -070070 /** Enum value for a sync start event. */
71 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
Dianne Hackborn231cc602009-04-27 17:10:36 -070073 /** Enum value for a sync stop event. */
74 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075
Dianne Hackborn231cc602009-04-27 17:10:36 -070076 // TODO: i18n -- grab these out of resources.
77 /** String names for the sync event types. */
78 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
Dianne Hackborn231cc602009-04-27 17:10:36 -070080 /** Enum value for a server-initiated sync. */
81 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
Dianne Hackborn231cc602009-04-27 17:10:36 -070083 /** Enum value for a local-initiated sync. */
84 public static final int SOURCE_LOCAL = 1;
85 /**
86 * Enum value for a poll-based sync (e.g., upon connection to
87 * network)
88 */
89 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
Dianne Hackborn231cc602009-04-27 17:10:36 -070091 /** Enum value for a user-initiated sync. */
92 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080094 /** Enum value for a periodic sync. */
95 public static final int SOURCE_PERIODIC = 4;
96
Fred Quintana307da1a2010-01-21 14:24:20 -080097 public static final long NOT_IN_BACKOFF_MODE = -1;
98
Fred Quintanaac9385e2009-06-22 18:00:59 -070099 private static final Intent SYNC_CONNECTION_SETTING_CHANGED_INTENT =
100 new Intent("com.android.sync.SYNC_CONN_STATUS_CHANGED");
101
Dianne Hackborn231cc602009-04-27 17:10:36 -0700102 // TODO: i18n -- grab these out of resources.
103 /** String names for the sync source types. */
104 public static final String[] SOURCES = { "SERVER",
105 "LOCAL",
106 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800107 "USER",
108 "PERIODIC" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109
Dianne Hackborn231cc602009-04-27 17:10:36 -0700110 // The MESG column will contain one of these or one of the Error types.
111 public static final String MESG_SUCCESS = "success";
112 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700114 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700115
Dianne Hackborn231cc602009-04-27 17:10:36 -0700116 private static final int MSG_WRITE_STATUS = 1;
117 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700118
Dianne Hackborn231cc602009-04-27 17:10:36 -0700119 private static final int MSG_WRITE_STATISTICS = 2;
120 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700121
122 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700123
Fred Quintanac2e46912010-03-15 16:10:44 -0700124 // the version of the accounts xml file format
125 private static final int ACCOUNTS_VERSION = 1;
126
Dianne Hackborn231cc602009-04-27 17:10:36 -0700127 public static class PendingOperation {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700128 final Account account;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700129 final int syncSource;
130 final String authority;
131 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800132 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700133
Dianne Hackborn231cc602009-04-27 17:10:36 -0700134 int authorityId;
135 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700136
Dianne Hackborn7a135592009-05-06 00:28:37 -0700137 PendingOperation(Account account, int source,
Fred Quintana307da1a2010-01-21 14:24:20 -0800138 String authority, Bundle extras, boolean expedited) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700139 this.account = account;
140 this.syncSource = source;
141 this.authority = authority;
142 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800143 this.expedited = expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700144 this.authorityId = -1;
145 }
146
147 PendingOperation(PendingOperation other) {
148 this.account = other.account;
149 this.syncSource = other.syncSource;
150 this.authority = other.authority;
151 this.extras = other.extras;
152 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800153 this.expedited = other.expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 }
Costin Manolache360e4542009-09-04 13:36:04 -0700156
Dianne Hackborn231cc602009-04-27 17:10:36 -0700157 static class AccountInfo {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700158 final Account account;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700159 final HashMap<String, AuthorityInfo> authorities =
160 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700161
Dianne Hackborn7a135592009-05-06 00:28:37 -0700162 AccountInfo(Account account) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700163 this.account = account;
164 }
165 }
Costin Manolache360e4542009-09-04 13:36:04 -0700166
Dianne Hackborn231cc602009-04-27 17:10:36 -0700167 public static class AuthorityInfo {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700168 final Account account;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700169 final String authority;
170 final int ident;
171 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700172 int syncable;
Fred Quintana307da1a2010-01-21 14:24:20 -0800173 long backoffTime;
174 long backoffDelay;
175 long delayUntil;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800176 final ArrayList<Pair<Bundle, Long>> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700177
Dianne Hackborn7a135592009-05-06 00:28:37 -0700178 AuthorityInfo(Account account, String authority, int ident) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700179 this.account = account;
180 this.authority = authority;
181 this.ident = ident;
Joe Onorato8294fad2009-07-15 16:08:44 -0700182 enabled = SYNC_ENABLED_DEFAULT;
Fred Quintana4a6679b2009-08-17 13:05:39 -0700183 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800184 backoffTime = -1; // if < 0 then we aren't in backoff mode
185 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800186 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
187 periodicSyncs.add(Pair.create(new Bundle(), DEFAULT_POLL_FREQUENCY_SECONDS));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700188 }
189 }
Costin Manolache360e4542009-09-04 13:36:04 -0700190
Dianne Hackborn231cc602009-04-27 17:10:36 -0700191 public static class SyncHistoryItem {
192 int authorityId;
193 int historyId;
194 long eventTime;
195 long elapsedTime;
196 int source;
197 int event;
198 long upstreamActivity;
199 long downstreamActivity;
200 String mesg;
201 }
Costin Manolache360e4542009-09-04 13:36:04 -0700202
Dianne Hackborn231cc602009-04-27 17:10:36 -0700203 public static class DayStats {
204 public final int day;
205 public int successCount;
206 public long successTime;
207 public int failureCount;
208 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700209
Dianne Hackborn231cc602009-04-27 17:10:36 -0700210 public DayStats(int day) {
211 this.day = day;
212 }
213 }
Costin Manolache360e4542009-09-04 13:36:04 -0700214
Dianne Hackborn231cc602009-04-27 17:10:36 -0700215 // Primary list of all syncable authorities. Also our global lock.
216 private final SparseArray<AuthorityInfo> mAuthorities =
217 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700218
Dianne Hackborn7a135592009-05-06 00:28:37 -0700219 private final HashMap<Account, AccountInfo> mAccounts =
220 new HashMap<Account, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
Dianne Hackborn231cc602009-04-27 17:10:36 -0700222 private final ArrayList<PendingOperation> mPendingOperations =
223 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700224
Dianne Hackborn231cc602009-04-27 17:10:36 -0700225 private ActiveSyncInfo mActiveSync;
Costin Manolache360e4542009-09-04 13:36:04 -0700226
Dianne Hackborn231cc602009-04-27 17:10:36 -0700227 private final SparseArray<SyncStatusInfo> mSyncStatus =
228 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700229
Dianne Hackborn231cc602009-04-27 17:10:36 -0700230 private final ArrayList<SyncHistoryItem> mSyncHistory =
231 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700232
Dianne Hackborn231cc602009-04-27 17:10:36 -0700233 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
234 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700235
Dianne Hackborn231cc602009-04-27 17:10:36 -0700236 // We keep 4 weeks of stats.
237 private final DayStats[] mDayStats = new DayStats[7*4];
238 private final Calendar mCal;
239 private int mYear;
240 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700241
Dianne Hackborn231cc602009-04-27 17:10:36 -0700242 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800243
Dianne Hackborn231cc602009-04-27 17:10:36 -0700244 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700245
Dianne Hackborn231cc602009-04-27 17:10:36 -0700246 /**
247 * This file contains the core engine state: all accounts and the
248 * settings for them. It must never be lost, and should be changed
249 * infrequently, so it is stored as an XML file.
250 */
251 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700252
Dianne Hackborn231cc602009-04-27 17:10:36 -0700253 /**
254 * This file contains the current sync status. We would like to retain
255 * it across boots, but its loss is not the end of the world, so we store
256 * this information as binary data.
257 */
258 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700259
Dianne Hackborn231cc602009-04-27 17:10:36 -0700260 /**
261 * This file contains sync statistics. This is purely debugging information
262 * so is written infrequently and can be thrown away at any time.
263 */
264 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700265
Dianne Hackborn231cc602009-04-27 17:10:36 -0700266 /**
267 * This file contains the pending sync operations. It is a binary file,
268 * which must be updated every time an operation is added or removed,
269 * so we have special handling of it.
270 */
271 private final AtomicFile mPendingFile;
272 private static final int PENDING_FINISH_TO_WRITE = 4;
273 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700274
Dianne Hackborn231cc602009-04-27 17:10:36 -0700275 private int mNextHistoryId = 0;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700276 private boolean mMasterSyncAutomatically = true;
Costin Manolache360e4542009-09-04 13:36:04 -0700277
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800278 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700281
Dianne Hackborn231cc602009-04-27 17:10:36 -0700282 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700283
Dianne Hackborn231cc602009-04-27 17:10:36 -0700284 File systemDir = new File(dataDir, "system");
285 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800286 syncDir.mkdirs();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700287 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
288 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
289 mPendingFile = new AtomicFile(new File(syncDir, "pending.bin"));
290 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700291
Dianne Hackborn231cc602009-04-27 17:10:36 -0700292 readAccountInfoLocked();
293 readStatusLocked();
294 readPendingOperationsLocked();
295 readStatisticsLocked();
296 readLegacyAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 }
298
299 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800300 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 }
302
303 public static void init(Context context) {
304 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800305 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800307 // This call will return the correct directory whether Encrypted File Systems is
308 // enabled or not.
309 File dataDir = Environment.getSecureDataDirectory();
310 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 }
312
313 public static SyncStorageEngine getSingleton() {
314 if (sSyncStorageEngine == null) {
315 throw new IllegalStateException("not initialized");
316 }
317 return sSyncStorageEngine;
318 }
319
Dianne Hackborn231cc602009-04-27 17:10:36 -0700320 @Override public void handleMessage(Message msg) {
321 if (msg.what == MSG_WRITE_STATUS) {
322 synchronized (mAccounts) {
323 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700324 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700325 } else if (msg.what == MSG_WRITE_STATISTICS) {
326 synchronized (mAccounts) {
327 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 }
329 }
330 }
Costin Manolache360e4542009-09-04 13:36:04 -0700331
Dianne Hackborn231cc602009-04-27 17:10:36 -0700332 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
333 synchronized (mAuthorities) {
334 mChangeListeners.register(callback, mask);
335 }
336 }
Costin Manolache360e4542009-09-04 13:36:04 -0700337
Dianne Hackborn231cc602009-04-27 17:10:36 -0700338 public void removeStatusChangeListener(ISyncStatusObserver callback) {
339 synchronized (mAuthorities) {
340 mChangeListeners.unregister(callback);
341 }
342 }
Costin Manolache360e4542009-09-04 13:36:04 -0700343
Dianne Hackborn231cc602009-04-27 17:10:36 -0700344 private void reportChange(int which) {
345 ArrayList<ISyncStatusObserver> reports = null;
346 synchronized (mAuthorities) {
347 int i = mChangeListeners.beginBroadcast();
348 while (i > 0) {
349 i--;
350 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
351 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 continue;
353 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700354 if (reports == null) {
355 reports = new ArrayList<ISyncStatusObserver>(i);
356 }
357 reports.add(mChangeListeners.getBroadcastItem(i));
358 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700359 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700360 }
Costin Manolache360e4542009-09-04 13:36:04 -0700361
Dianne Hackborn231cc602009-04-27 17:10:36 -0700362 if (DEBUG) Log.v(TAG, "reportChange " + which + " to: " + reports);
Costin Manolache360e4542009-09-04 13:36:04 -0700363
Dianne Hackborn231cc602009-04-27 17:10:36 -0700364 if (reports != null) {
365 int i = reports.size();
366 while (i > 0) {
367 i--;
368 try {
369 reports.get(i).onStatusChanged(which);
370 } catch (RemoteException e) {
371 // The remote callback list will take care of this for us.
372 }
373 }
374 }
375 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700376
Fred Quintanaac9385e2009-06-22 18:00:59 -0700377 public boolean getSyncAutomatically(Account account, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700378 synchronized (mAuthorities) {
379 if (account != null) {
380 AuthorityInfo authority = getAuthorityLocked(account, providerName,
Fred Quintanaac9385e2009-06-22 18:00:59 -0700381 "getSyncAutomatically");
382 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700383 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700384
Dianne Hackborn231cc602009-04-27 17:10:36 -0700385 int i = mAuthorities.size();
386 while (i > 0) {
387 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700388 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700389 if (authority.authority.equals(providerName)
390 && authority.enabled) {
391 return true;
392 }
393 }
394 return false;
395 }
396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397
Fred Quintanaac9385e2009-06-22 18:00:59 -0700398 public void setSyncAutomatically(Account account, String providerName, boolean sync) {
Joe Onorato8294fad2009-07-15 16:08:44 -0700399 boolean wasEnabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700400 synchronized (mAuthorities) {
Joe Onorato8294fad2009-07-15 16:08:44 -0700401 AuthorityInfo authority = getOrCreateAuthorityLocked(account, providerName, -1, false);
402 wasEnabled = authority.enabled;
403 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700404 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700406
407 if (!wasEnabled && sync) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800408 ContentResolver.requestSync(account, providerName, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700409 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700410 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 }
412
Fred Quintana5e787c42009-08-16 23:13:53 -0700413 public int getIsSyncable(Account account, String providerName) {
414 synchronized (mAuthorities) {
415 if (account != null) {
416 AuthorityInfo authority = getAuthorityLocked(account, providerName,
417 "getIsSyncable");
418 if (authority == null) {
419 return -1;
420 }
421 return authority.syncable;
422 }
423
424 int i = mAuthorities.size();
425 while (i > 0) {
426 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700427 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintana5e787c42009-08-16 23:13:53 -0700428 if (authority.authority.equals(providerName)) {
429 return authority.syncable;
430 }
431 }
432 return -1;
433 }
434 }
435
436 public void setIsSyncable(Account account, String providerName, int syncable) {
437 int oldState;
Fred Quintanab763ab22009-08-18 18:07:30 -0700438 if (syncable > 1) {
439 syncable = 1;
440 } else if (syncable < -1) {
441 syncable = -1;
442 }
443 Log.d(TAG, "setIsSyncable: " + account + ", provider " + providerName + " -> " + syncable);
Fred Quintana5e787c42009-08-16 23:13:53 -0700444 synchronized (mAuthorities) {
445 AuthorityInfo authority = getOrCreateAuthorityLocked(account, providerName, -1, false);
446 oldState = authority.syncable;
447 authority.syncable = syncable;
448 writeAccountInfoLocked();
449 }
450
451 if (oldState <= 0 && syncable > 0) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800452 ContentResolver.requestSync(account, providerName, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700453 }
454 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
455 }
456
Fred Quintana307da1a2010-01-21 14:24:20 -0800457 public Pair<Long, Long> getBackoff(Account account, String providerName) {
458 synchronized (mAuthorities) {
459 AuthorityInfo authority = getAuthorityLocked(account, providerName, "getBackoff");
460 if (authority == null || authority.backoffTime < 0) {
461 return null;
462 }
463 return Pair.create(authority.backoffTime, authority.backoffDelay);
464 }
465 }
466
467 public void setBackoff(Account account, String providerName,
468 long nextSyncTime, long nextDelay) {
469 if (Log.isLoggable(TAG, Log.VERBOSE)) {
470 Log.v(TAG, "setBackoff: " + account + ", provider " + providerName
471 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
472 }
473 boolean changed = false;
474 synchronized (mAuthorities) {
475 if (account == null || providerName == null) {
476 for (AccountInfo accountInfo : mAccounts.values()) {
477 if (account != null && !account.equals(accountInfo.account)) continue;
478 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
479 if (providerName != null && !providerName.equals(authorityInfo.authority)) {
480 continue;
481 }
482 if (authorityInfo.backoffTime != nextSyncTime
483 || authorityInfo.backoffDelay != nextDelay) {
484 authorityInfo.backoffTime = nextSyncTime;
485 authorityInfo.backoffDelay = nextDelay;
486 changed = true;
487 }
488 }
489 }
490 } else {
491 AuthorityInfo authority =
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800492 getOrCreateAuthorityLocked(account, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800493 if (authority.backoffTime == nextSyncTime && authority.backoffDelay == nextDelay) {
494 return;
495 }
496 authority.backoffTime = nextSyncTime;
497 authority.backoffDelay = nextDelay;
498 changed = true;
499 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800500 }
501
502 if (changed) {
503 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
504 }
505 }
506
507 public void setDelayUntilTime(Account account, String providerName, long delayUntil) {
508 if (Log.isLoggable(TAG, Log.VERBOSE)) {
509 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
510 + " -> delayUntil " + delayUntil);
511 }
512 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800513 AuthorityInfo authority = getOrCreateAuthorityLocked(
514 account, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800515 if (authority.delayUntil == delayUntil) {
516 return;
517 }
518 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800519 }
520
521 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
522 }
523
524 public long getDelayUntilTime(Account account, String providerName) {
525 synchronized (mAuthorities) {
526 AuthorityInfo authority = getAuthorityLocked(account, providerName, "getDelayUntil");
527 if (authority == null) {
528 return 0;
529 }
530 return authority.delayUntil;
531 }
532 }
533
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800534 private void updateOrRemovePeriodicSync(Account account, String providerName, Bundle extras,
535 long period, boolean add) {
536 if (period <= 0) {
537 period = 0;
538 }
539 if (extras == null) {
540 extras = new Bundle();
541 }
542 if (Log.isLoggable(TAG, Log.VERBOSE)) {
543 Log.v(TAG, "addOrRemovePeriodicSync: " + account + ", provider " + providerName
544 + " -> period " + period + ", extras " + extras);
545 }
546 synchronized (mAuthorities) {
547 AuthorityInfo authority = getOrCreateAuthorityLocked(account, providerName, -1, false);
548 if (add) {
549 boolean alreadyPresent = false;
550 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
551 Pair<Bundle, Long> syncInfo = authority.periodicSyncs.get(i);
552 final Bundle existingExtras = syncInfo.first;
553 if (equals(existingExtras, extras)) {
554 if (syncInfo.second == period) {
555 return;
556 }
557 authority.periodicSyncs.set(i, Pair.create(extras, period));
558 alreadyPresent = true;
559 break;
560 }
561 }
562 if (!alreadyPresent) {
563 authority.periodicSyncs.add(Pair.create(extras, period));
564 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
565 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
566 }
567 } else {
568 SyncStatusInfo status = mSyncStatus.get(authority.ident);
569 boolean changed = false;
570 Iterator<Pair<Bundle, Long>> iterator = authority.periodicSyncs.iterator();
571 int i = 0;
572 while (iterator.hasNext()) {
573 Pair<Bundle, Long> syncInfo = iterator.next();
574 if (equals(syncInfo.first, extras)) {
575 iterator.remove();
576 changed = true;
577 if (status != null) {
578 status.removePeriodicSyncTime(i);
579 }
580 } else {
581 i++;
582 }
583 }
584 if (!changed) {
585 return;
586 }
587 }
588 writeAccountInfoLocked();
589 writeStatusLocked();
590 }
591
592 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
593 }
594
595 public void addPeriodicSync(Account account, String providerName, Bundle extras,
596 long pollFrequency) {
597 updateOrRemovePeriodicSync(account, providerName, extras, pollFrequency, true /* add */);
598 }
599
600 public void removePeriodicSync(Account account, String providerName, Bundle extras) {
601 updateOrRemovePeriodicSync(account, providerName, extras, 0 /* period, ignored */,
602 false /* remove */);
603 }
604
605 public List<PeriodicSync> getPeriodicSyncs(Account account, String providerName) {
606 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
607 synchronized (mAuthorities) {
608 AuthorityInfo authority = getAuthorityLocked(account, providerName, "getPeriodicSyncs");
609 if (authority != null) {
610 for (Pair<Bundle, Long> item : authority.periodicSyncs) {
611 syncs.add(new PeriodicSync(account, providerName, item.first, item.second));
612 }
613 }
614 }
615 return syncs;
616 }
617
Fred Quintanaac9385e2009-06-22 18:00:59 -0700618 public void setMasterSyncAutomatically(boolean flag) {
Joe Onorato8294fad2009-07-15 16:08:44 -0700619 boolean old;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700620 synchronized (mAuthorities) {
Joe Onorato8294fad2009-07-15 16:08:44 -0700621 old = mMasterSyncAutomatically;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700622 mMasterSyncAutomatically = flag;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700623 writeAccountInfoLocked();
624 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700625 if (!old && flag) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800626 ContentResolver.requestSync(null, null, new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700627 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700628 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
629 mContext.sendBroadcast(SYNC_CONNECTION_SETTING_CHANGED_INTENT);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631
Fred Quintanaac9385e2009-06-22 18:00:59 -0700632 public boolean getMasterSyncAutomatically() {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700633 synchronized (mAuthorities) {
Fred Quintanaac9385e2009-06-22 18:00:59 -0700634 return mMasterSyncAutomatically;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700635 }
636 }
Costin Manolache360e4542009-09-04 13:36:04 -0700637
Fred Quintana1bbcd102010-02-10 10:04:33 -0800638 public AuthorityInfo getOrCreateAuthority(Account account, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700639 synchronized (mAuthorities) {
Fred Quintana1bbcd102010-02-10 10:04:33 -0800640 return getOrCreateAuthorityLocked(account, authority,
641 -1 /* assign a new identifier if creating a new authority */,
642 true /* write to storage if this results in a change */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700643 }
644 }
Costin Manolache360e4542009-09-04 13:36:04 -0700645
Fred Quintana7620f1a2010-03-16 15:58:44 -0700646 public void removeAuthority(Account account, String authority) {
647 synchronized (mAuthorities) {
648 removeAuthorityLocked(account, authority);
649 }
650 }
651
Dianne Hackborn231cc602009-04-27 17:10:36 -0700652 public AuthorityInfo getAuthority(int authorityId) {
653 synchronized (mAuthorities) {
654 return mAuthorities.get(authorityId);
655 }
656 }
Costin Manolache360e4542009-09-04 13:36:04 -0700657
Dianne Hackborn231cc602009-04-27 17:10:36 -0700658 /**
659 * Returns true if there is currently a sync operation for the given
660 * account or authority in the pending list, or actively being processed.
661 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700662 public boolean isSyncActive(Account account, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700663 synchronized (mAuthorities) {
664 int i = mPendingOperations.size();
665 while (i > 0) {
666 i--;
667 // TODO(fredq): this probably shouldn't be considering
668 // pending operations.
669 PendingOperation op = mPendingOperations.get(i);
670 if (op.account.equals(account) && op.authority.equals(authority)) {
671 return true;
672 }
673 }
Costin Manolache360e4542009-09-04 13:36:04 -0700674
Dianne Hackborn231cc602009-04-27 17:10:36 -0700675 if (mActiveSync != null) {
Fred Quintana1b487ec2010-02-26 10:57:55 -0800676 AuthorityInfo ainfo = getAuthority(mActiveSync.getAuthorityId());
Dianne Hackborn231cc602009-04-27 17:10:36 -0700677 if (ainfo != null && ainfo.account.equals(account)
678 && ainfo.authority.equals(authority)) {
679 return true;
680 }
681 }
682 }
Costin Manolache360e4542009-09-04 13:36:04 -0700683
Dianne Hackborn231cc602009-04-27 17:10:36 -0700684 return false;
685 }
Costin Manolache360e4542009-09-04 13:36:04 -0700686
Dianne Hackborn231cc602009-04-27 17:10:36 -0700687 public PendingOperation insertIntoPending(PendingOperation op) {
688 synchronized (mAuthorities) {
689 if (DEBUG) Log.v(TAG, "insertIntoPending: account=" + op.account
690 + " auth=" + op.authority
691 + " src=" + op.syncSource
692 + " extras=" + op.extras);
Costin Manolache360e4542009-09-04 13:36:04 -0700693
Dianne Hackborn231cc602009-04-27 17:10:36 -0700694 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account,
695 op.authority,
696 -1 /* desired identifier */,
697 true /* write accounts to storage */);
698 if (authority == null) {
699 return null;
700 }
Costin Manolache360e4542009-09-04 13:36:04 -0700701
Dianne Hackborn231cc602009-04-27 17:10:36 -0700702 op = new PendingOperation(op);
703 op.authorityId = authority.ident;
704 mPendingOperations.add(op);
705 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700706
Dianne Hackborn231cc602009-04-27 17:10:36 -0700707 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
708 status.pending = true;
709 }
Costin Manolache360e4542009-09-04 13:36:04 -0700710
Fred Quintanaac9385e2009-06-22 18:00:59 -0700711 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700712 return op;
713 }
714
715 public boolean deleteFromPending(PendingOperation op) {
716 boolean res = false;
717 synchronized (mAuthorities) {
718 if (DEBUG) Log.v(TAG, "deleteFromPending: account=" + op.account
719 + " auth=" + op.authority
720 + " src=" + op.syncSource
721 + " extras=" + op.extras);
722 if (mPendingOperations.remove(op)) {
723 if (mPendingOperations.size() == 0
724 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
725 writePendingOperationsLocked();
726 mNumPendingFinished = 0;
727 } else {
728 mNumPendingFinished++;
729 }
Costin Manolache360e4542009-09-04 13:36:04 -0700730
Dianne Hackborn231cc602009-04-27 17:10:36 -0700731 AuthorityInfo authority = getAuthorityLocked(op.account, op.authority,
732 "deleteFromPending");
733 if (authority != null) {
734 if (DEBUG) Log.v(TAG, "removing - " + authority);
735 final int N = mPendingOperations.size();
736 boolean morePending = false;
737 for (int i=0; i<N; i++) {
738 PendingOperation cur = mPendingOperations.get(i);
739 if (cur.account.equals(op.account)
740 && cur.authority.equals(op.authority)) {
741 morePending = true;
742 break;
743 }
744 }
Costin Manolache360e4542009-09-04 13:36:04 -0700745
Dianne Hackborn231cc602009-04-27 17:10:36 -0700746 if (!morePending) {
747 if (DEBUG) Log.v(TAG, "no more pending!");
748 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
749 status.pending = false;
750 }
751 }
Costin Manolache360e4542009-09-04 13:36:04 -0700752
Dianne Hackborn231cc602009-04-27 17:10:36 -0700753 res = true;
754 }
755 }
Costin Manolache360e4542009-09-04 13:36:04 -0700756
Fred Quintanaac9385e2009-06-22 18:00:59 -0700757 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700758 return res;
759 }
760
761 public int clearPending() {
762 int num;
763 synchronized (mAuthorities) {
764 if (DEBUG) Log.v(TAG, "clearPending");
765 num = mPendingOperations.size();
766 mPendingOperations.clear();
767 final int N = mSyncStatus.size();
768 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -0700769 mSyncStatus.valueAt(i).pending = false;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700770 }
771 writePendingOperationsLocked();
772 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700773 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700774 return num;
775 }
776
777 /**
778 * Return a copy of the current array of pending operations. The
779 * PendingOperation objects are the real objects stored inside, so that
780 * they can be used with deleteFromPending().
781 */
782 public ArrayList<PendingOperation> getPendingOperations() {
783 synchronized (mAuthorities) {
784 return new ArrayList<PendingOperation>(mPendingOperations);
785 }
786 }
Costin Manolache360e4542009-09-04 13:36:04 -0700787
Dianne Hackborn231cc602009-04-27 17:10:36 -0700788 /**
789 * Return the number of currently pending operations.
790 */
791 public int getPendingOperationCount() {
792 synchronized (mAuthorities) {
793 return mPendingOperations.size();
794 }
795 }
Costin Manolache360e4542009-09-04 13:36:04 -0700796
Dianne Hackborn231cc602009-04-27 17:10:36 -0700797 /**
798 * Called when the set of account has changed, given the new array of
799 * active accounts.
800 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700801 public void doDatabaseCleanup(Account[] accounts) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700802 synchronized (mAuthorities) {
803 if (DEBUG) Log.w(TAG, "Updating for new accounts...");
804 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
805 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
806 while (accIt.hasNext()) {
807 AccountInfo acc = accIt.next();
808 if (!ArrayUtils.contains(accounts, acc.account)) {
809 // This account no longer exists...
810 if (DEBUG) Log.w(TAG, "Account removed: " + acc.account);
811 for (AuthorityInfo auth : acc.authorities.values()) {
812 removing.put(auth.ident, auth);
813 }
814 accIt.remove();
815 }
816 }
Costin Manolache360e4542009-09-04 13:36:04 -0700817
Dianne Hackborn231cc602009-04-27 17:10:36 -0700818 // Clean out all data structures.
819 int i = removing.size();
820 if (i > 0) {
821 while (i > 0) {
822 i--;
823 int ident = removing.keyAt(i);
824 mAuthorities.remove(ident);
825 int j = mSyncStatus.size();
826 while (j > 0) {
827 j--;
828 if (mSyncStatus.keyAt(j) == ident) {
829 mSyncStatus.remove(mSyncStatus.keyAt(j));
830 }
831 }
832 j = mSyncHistory.size();
833 while (j > 0) {
834 j--;
835 if (mSyncHistory.get(j).authorityId == ident) {
836 mSyncHistory.remove(j);
837 }
838 }
839 }
840 writeAccountInfoLocked();
841 writeStatusLocked();
842 writePendingOperationsLocked();
843 writeStatisticsLocked();
844 }
845 }
846 }
847
848 /**
849 * Called when the currently active sync is changing (there can only be
850 * one at a time). Either supply a valid ActiveSyncContext with information
851 * about the sync, or null to stop the currently active sync.
852 */
853 public void setActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
854 synchronized (mAuthorities) {
855 if (activeSyncContext != null) {
856 if (DEBUG) Log.v(TAG, "setActiveSync: account="
857 + activeSyncContext.mSyncOperation.account
858 + " auth=" + activeSyncContext.mSyncOperation.authority
859 + " src=" + activeSyncContext.mSyncOperation.syncSource
860 + " extras=" + activeSyncContext.mSyncOperation.extras);
861 if (mActiveSync != null) {
862 Log.w(TAG, "setActiveSync called with existing active sync!");
863 }
864 AuthorityInfo authority = getAuthorityLocked(
865 activeSyncContext.mSyncOperation.account,
866 activeSyncContext.mSyncOperation.authority,
867 "setActiveSync");
868 if (authority == null) {
869 return;
870 }
871 mActiveSync = new ActiveSyncInfo(authority.ident,
872 authority.account, authority.authority,
873 activeSyncContext.mStartTime);
874 } else {
875 if (DEBUG) Log.v(TAG, "setActiveSync: null");
876 mActiveSync = null;
877 }
878 }
Costin Manolache360e4542009-09-04 13:36:04 -0700879
Fred Quintanaac9385e2009-06-22 18:00:59 -0700880 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700881 }
882
883 /**
884 * To allow others to send active change reports, to poke clients.
885 */
886 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -0700887 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700888 }
Costin Manolache360e4542009-09-04 13:36:04 -0700889
Dianne Hackborn231cc602009-04-27 17:10:36 -0700890 /**
891 * Note that sync has started for the given account and authority.
892 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700893 public long insertStartSyncEvent(Account accountName, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700894 long now, int source) {
895 long id;
896 synchronized (mAuthorities) {
897 if (DEBUG) Log.v(TAG, "insertStartSyncEvent: account=" + accountName
898 + " auth=" + authorityName + " source=" + source);
899 AuthorityInfo authority = getAuthorityLocked(accountName, authorityName,
900 "insertStartSyncEvent");
901 if (authority == null) {
902 return -1;
903 }
904 SyncHistoryItem item = new SyncHistoryItem();
905 item.authorityId = authority.ident;
906 item.historyId = mNextHistoryId++;
907 if (mNextHistoryId < 0) mNextHistoryId = 0;
908 item.eventTime = now;
909 item.source = source;
910 item.event = EVENT_START;
911 mSyncHistory.add(0, item);
912 while (mSyncHistory.size() > MAX_HISTORY) {
913 mSyncHistory.remove(mSyncHistory.size()-1);
914 }
915 id = item.historyId;
916 if (DEBUG) Log.v(TAG, "returning historyId " + id);
917 }
Costin Manolache360e4542009-09-04 13:36:04 -0700918
Fred Quintanaac9385e2009-06-22 18:00:59 -0700919 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700920 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 }
922
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800923 public static boolean equals(Bundle b1, Bundle b2) {
924 if (b1.size() != b2.size()) {
925 return false;
926 }
927 if (b1.isEmpty()) {
928 return true;
929 }
930 for (String key : b1.keySet()) {
931 if (!b2.containsKey(key)) {
932 return false;
933 }
934 if (!b1.get(key).equals(b2.get(key))) {
935 return false;
936 }
937 }
938 return true;
939 }
940
941 public void stopSyncEvent(long historyId, Bundle extras, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700943 synchronized (mAuthorities) {
944 if (DEBUG) Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
945 SyncHistoryItem item = null;
946 int i = mSyncHistory.size();
947 while (i > 0) {
948 i--;
949 item = mSyncHistory.get(i);
950 if (item.historyId == historyId) {
951 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700953 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
Costin Manolache360e4542009-09-04 13:36:04 -0700955
Dianne Hackborn231cc602009-04-27 17:10:36 -0700956 if (item == null) {
957 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
958 return;
959 }
Costin Manolache360e4542009-09-04 13:36:04 -0700960
Dianne Hackborn231cc602009-04-27 17:10:36 -0700961 item.elapsedTime = elapsedTime;
962 item.event = EVENT_STOP;
963 item.mesg = resultMessage;
964 item.downstreamActivity = downstreamActivity;
965 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -0700966
Dianne Hackborn231cc602009-04-27 17:10:36 -0700967 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -0700968
Dianne Hackborn231cc602009-04-27 17:10:36 -0700969 status.numSyncs++;
970 status.totalElapsedTime += elapsedTime;
971 switch (item.source) {
972 case SOURCE_LOCAL:
973 status.numSourceLocal++;
974 break;
975 case SOURCE_POLL:
976 status.numSourcePoll++;
977 break;
978 case SOURCE_USER:
979 status.numSourceUser++;
980 break;
981 case SOURCE_SERVER:
982 status.numSourceServer++;
983 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800984 case SOURCE_PERIODIC:
985 status.numSourcePeriodic++;
986 AuthorityInfo authority = mAuthorities.get(item.authorityId);
987 for (int periodicSyncIndex = 0;
988 periodicSyncIndex < authority.periodicSyncs.size();
989 periodicSyncIndex++) {
990 if (equals(extras, authority.periodicSyncs.get(periodicSyncIndex).first)) {
991 status.setPeriodicSyncTime(periodicSyncIndex, item.eventTime);
992 }
993 }
994 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700995 }
Costin Manolache360e4542009-09-04 13:36:04 -0700996
Dianne Hackborn231cc602009-04-27 17:10:36 -0700997 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -0700998 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700999 if (mDayStats[0] == null) {
1000 mDayStats[0] = new DayStats(day);
1001 } else if (day != mDayStats[0].day) {
1002 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1003 mDayStats[0] = new DayStats(day);
1004 writeStatisticsNow = true;
1005 } else if (mDayStats[0] == null) {
1006 }
1007 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001008
Dianne Hackborn231cc602009-04-27 17:10:36 -07001009 final long lastSyncTime = (item.eventTime + elapsedTime);
1010 boolean writeStatusNow = false;
1011 if (MESG_SUCCESS.equals(resultMessage)) {
1012 // - if successful, update the successful columns
1013 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1014 writeStatusNow = true;
1015 }
1016 status.lastSuccessTime = lastSyncTime;
1017 status.lastSuccessSource = item.source;
1018 status.lastFailureTime = 0;
1019 status.lastFailureSource = -1;
1020 status.lastFailureMesg = null;
1021 status.initialFailureTime = 0;
1022 ds.successCount++;
1023 ds.successTime += elapsedTime;
1024 } else if (!MESG_CANCELED.equals(resultMessage)) {
1025 if (status.lastFailureTime == 0) {
1026 writeStatusNow = true;
1027 }
1028 status.lastFailureTime = lastSyncTime;
1029 status.lastFailureSource = item.source;
1030 status.lastFailureMesg = resultMessage;
1031 if (status.initialFailureTime == 0) {
1032 status.initialFailureTime = lastSyncTime;
1033 }
1034 ds.failureCount++;
1035 ds.failureTime += elapsedTime;
1036 }
Costin Manolache360e4542009-09-04 13:36:04 -07001037
Dianne Hackborn231cc602009-04-27 17:10:36 -07001038 if (writeStatusNow) {
1039 writeStatusLocked();
1040 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1041 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1042 WRITE_STATUS_DELAY);
1043 }
1044 if (writeStatisticsNow) {
1045 writeStatisticsLocked();
1046 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1047 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1048 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001049 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001050 }
Costin Manolache360e4542009-09-04 13:36:04 -07001051
Fred Quintanaac9385e2009-06-22 18:00:59 -07001052 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001053 }
1054
1055 /**
1056 * Return the currently active sync information, or null if there is no
1057 * active sync. Note that the returned object is the real, live active
1058 * sync object, so be careful what you do with it.
1059 */
1060 public ActiveSyncInfo getActiveSync() {
1061 synchronized (mAuthorities) {
1062 return mActiveSync;
1063 }
1064 }
Costin Manolache360e4542009-09-04 13:36:04 -07001065
Dianne Hackborn231cc602009-04-27 17:10:36 -07001066 /**
1067 * Return an array of the current sync status for all authorities. Note
1068 * that the objects inside the array are the real, live status objects,
1069 * so be careful what you do with them.
1070 */
1071 public ArrayList<SyncStatusInfo> getSyncStatus() {
1072 synchronized (mAuthorities) {
1073 final int N = mSyncStatus.size();
1074 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1075 for (int i=0; i<N; i++) {
1076 ops.add(mSyncStatus.valueAt(i));
1077 }
1078 return ops;
1079 }
1080 }
Costin Manolache360e4542009-09-04 13:36:04 -07001081
Dianne Hackborn231cc602009-04-27 17:10:36 -07001082 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001083 * Return an array of the current authorities. Note
1084 * that the objects inside the array are the real, live objects,
1085 * so be careful what you do with them.
1086 */
1087 public ArrayList<AuthorityInfo> getAuthorities() {
1088 synchronized (mAuthorities) {
1089 final int N = mAuthorities.size();
1090 ArrayList<AuthorityInfo> infos = new ArrayList<AuthorityInfo>(N);
1091 for (int i=0; i<N; i++) {
1092 infos.add(mAuthorities.valueAt(i));
1093 }
1094 return infos;
1095 }
1096 }
1097
1098 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001099 * Returns the status that matches the authority and account.
1100 *
1101 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001102 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001103 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001104 */
Costin Manolacheb7520982009-09-02 18:03:05 -07001105 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, String authority) {
1106 if (account == null || authority == null) {
1107 throw new IllegalArgumentException();
1108 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001109 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001110 final int N = mSyncStatus.size();
1111 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001112 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001113 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001114
1115 if (ainfo != null && ainfo.authority.equals(authority) &&
1116 account.equals(ainfo.account)) {
1117 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001118 }
1119 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001120 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001121 }
1122 }
Costin Manolache360e4542009-09-04 13:36:04 -07001123
Dianne Hackborn231cc602009-04-27 17:10:36 -07001124 /**
1125 * Return true if the pending status is true of any matching authorities.
1126 */
Fred Quintanaac9385e2009-06-22 18:00:59 -07001127 public boolean isSyncPending(Account account, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001128 synchronized (mAuthorities) {
1129 final int N = mSyncStatus.size();
1130 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001131 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001132 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1133 if (ainfo == null) {
1134 continue;
1135 }
1136 if (account != null && !ainfo.account.equals(account)) {
1137 continue;
1138 }
1139 if (ainfo.authority.equals(authority) && cur.pending) {
1140 return true;
1141 }
1142 }
1143 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
1145 }
1146
1147 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001148 * Return an array of the current sync status for all authorities. Note
1149 * that the objects inside the array are the real, live status objects,
1150 * so be careful what you do with them.
1151 */
1152 public ArrayList<SyncHistoryItem> getSyncHistory() {
1153 synchronized (mAuthorities) {
1154 final int N = mSyncHistory.size();
1155 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1156 for (int i=0; i<N; i++) {
1157 items.add(mSyncHistory.get(i));
1158 }
1159 return items;
1160 }
1161 }
Costin Manolache360e4542009-09-04 13:36:04 -07001162
Dianne Hackborn231cc602009-04-27 17:10:36 -07001163 /**
1164 * Return an array of the current per-day statistics. Note
1165 * that the objects inside the array are the real, live status objects,
1166 * so be careful what you do with them.
1167 */
1168 public DayStats[] getDayStatistics() {
1169 synchronized (mAuthorities) {
1170 DayStats[] ds = new DayStats[mDayStats.length];
1171 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1172 return ds;
1173 }
1174 }
Costin Manolache360e4542009-09-04 13:36:04 -07001175
Dianne Hackborn231cc602009-04-27 17:10:36 -07001176 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 * If sync is failing for any of the provider/accounts then determine the time at which it
1178 * started failing and return the earliest time over all the provider/accounts. If none are
1179 * failing then return 0.
1180 */
1181 public long getInitialSyncFailureTime() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001182 synchronized (mAuthorities) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001183 if (!mMasterSyncAutomatically) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001184 return 0;
1185 }
Costin Manolache360e4542009-09-04 13:36:04 -07001186
Dianne Hackborn231cc602009-04-27 17:10:36 -07001187 long oldest = 0;
1188 int i = mSyncStatus.size();
1189 while (i > 0) {
1190 i--;
1191 SyncStatusInfo stats = mSyncStatus.valueAt(i);
1192 AuthorityInfo authority = mAuthorities.get(stats.authorityId);
1193 if (authority != null && authority.enabled) {
1194 if (oldest == 0 || stats.initialFailureTime < oldest) {
1195 oldest = stats.initialFailureTime;
1196 }
1197 }
1198 }
Costin Manolache360e4542009-09-04 13:36:04 -07001199
Dianne Hackborn231cc602009-04-27 17:10:36 -07001200 return oldest;
1201 }
1202 }
Costin Manolache360e4542009-09-04 13:36:04 -07001203
Dianne Hackborn55280a92009-05-07 15:53:46 -07001204 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001205 mCal.setTimeInMillis(System.currentTimeMillis());
1206 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1207 if (mYear != mCal.get(Calendar.YEAR)) {
1208 mYear = mCal.get(Calendar.YEAR);
1209 mCal.clear();
1210 mCal.set(Calendar.YEAR, mYear);
1211 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1212 }
1213 return dayOfYear + mYearInDays;
1214 }
Costin Manolache360e4542009-09-04 13:36:04 -07001215
Dianne Hackborn231cc602009-04-27 17:10:36 -07001216 /**
1217 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001218 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001219 * @param accountName The name of the account for the authority.
1220 * @param authorityName The name of the authority itself.
1221 * @param tag If non-null, this will be used in a log message if the
1222 * requested authority does not exist.
1223 */
Dianne Hackborn7a135592009-05-06 00:28:37 -07001224 private AuthorityInfo getAuthorityLocked(Account accountName, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001225 String tag) {
1226 AccountInfo account = mAccounts.get(accountName);
1227 if (account == null) {
1228 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001229 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1230 Log.v(TAG, tag + ": unknown account " + accountName);
1231 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001232 }
1233 return null;
1234 }
1235 AuthorityInfo authority = account.authorities.get(authorityName);
1236 if (authority == null) {
1237 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001238 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1239 Log.v(TAG, tag + ": unknown authority " + authorityName);
1240 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001241 }
1242 return null;
1243 }
Costin Manolache360e4542009-09-04 13:36:04 -07001244
Dianne Hackborn231cc602009-04-27 17:10:36 -07001245 return authority;
1246 }
Costin Manolache360e4542009-09-04 13:36:04 -07001247
Dianne Hackborn7a135592009-05-06 00:28:37 -07001248 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001249 String authorityName, int ident, boolean doWrite) {
1250 AccountInfo account = mAccounts.get(accountName);
1251 if (account == null) {
1252 account = new AccountInfo(accountName);
1253 mAccounts.put(accountName, account);
1254 }
1255 AuthorityInfo authority = account.authorities.get(authorityName);
1256 if (authority == null) {
1257 if (ident < 0) {
1258 // Look for a new identifier for this authority.
1259 final int N = mAuthorities.size();
1260 ident = 0;
1261 for (int i=0; i<N; i++) {
1262 if (mAuthorities.valueAt(i).ident > ident) {
1263 break;
1264 }
1265 ident++;
1266 }
1267 }
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -07001268 if (DEBUG) Log.v(TAG, "created a new AuthorityInfo for " + accountName
Fred Quintanab763ab22009-08-18 18:07:30 -07001269 + ", provider " + authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001270 authority = new AuthorityInfo(accountName, authorityName, ident);
1271 account.authorities.put(authorityName, authority);
1272 mAuthorities.put(ident, authority);
1273 if (doWrite) {
1274 writeAccountInfoLocked();
1275 }
1276 }
Costin Manolache360e4542009-09-04 13:36:04 -07001277
Dianne Hackborn231cc602009-04-27 17:10:36 -07001278 return authority;
1279 }
Costin Manolache360e4542009-09-04 13:36:04 -07001280
Fred Quintana7620f1a2010-03-16 15:58:44 -07001281 private void removeAuthorityLocked(Account account, String authorityName) {
1282 AccountInfo accountInfo = mAccounts.get(account);
1283 if (accountInfo != null) {
1284 if (accountInfo.authorities.remove(authorityName) != null) {
1285 writeAccountInfoLocked();
1286 }
1287 }
1288 }
1289
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001290 public SyncStatusInfo getOrCreateSyncStatus(AuthorityInfo authority) {
1291 synchronized (mAuthorities) {
1292 return getOrCreateSyncStatusLocked(authority.ident);
1293 }
1294 }
1295
Dianne Hackborn231cc602009-04-27 17:10:36 -07001296 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1297 SyncStatusInfo status = mSyncStatus.get(authorityId);
1298 if (status == null) {
1299 status = new SyncStatusInfo(authorityId);
1300 mSyncStatus.put(authorityId, status);
1301 }
1302 return status;
1303 }
Costin Manolache360e4542009-09-04 13:36:04 -07001304
Dianne Hackborn55280a92009-05-07 15:53:46 -07001305 public void writeAllState() {
1306 synchronized (mAuthorities) {
1307 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001308
Dianne Hackborn55280a92009-05-07 15:53:46 -07001309 if (mNumPendingFinished > 0) {
1310 // Only write these if they are out of date.
1311 writePendingOperationsLocked();
1312 }
Costin Manolache360e4542009-09-04 13:36:04 -07001313
Dianne Hackborn55280a92009-05-07 15:53:46 -07001314 // Just always write these... they are likely out of date.
1315 writeStatusLocked();
1316 writeStatisticsLocked();
1317 }
1318 }
Costin Manolache360e4542009-09-04 13:36:04 -07001319
Dianne Hackborn231cc602009-04-27 17:10:36 -07001320 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001321 * public for testing
1322 */
1323 public void clearAndReadState() {
1324 synchronized (mAuthorities) {
1325 mAuthorities.clear();
1326 mAccounts.clear();
1327 mPendingOperations.clear();
1328 mSyncStatus.clear();
1329 mSyncHistory.clear();
1330
1331 readAccountInfoLocked();
1332 readStatusLocked();
1333 readPendingOperationsLocked();
1334 readStatisticsLocked();
1335 readLegacyAccountInfoLocked();
1336 }
1337 }
1338
1339 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001340 * Read all account information back in to the initial engine state.
1341 */
1342 private void readAccountInfoLocked() {
Fred Quintanac2e46912010-03-15 16:10:44 -07001343 boolean writeNeeded = false;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001344 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001346 fis = mAccountInfoFile.openRead();
1347 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1348 XmlPullParser parser = Xml.newPullParser();
1349 parser.setInput(fis, null);
1350 int eventType = parser.getEventType();
1351 while (eventType != XmlPullParser.START_TAG) {
1352 eventType = parser.next();
1353 }
1354 String tagName = parser.getName();
1355 if ("accounts".equals(tagName)) {
1356 String listen = parser.getAttributeValue(
1357 null, "listen-for-tickles");
Fred Quintanac2e46912010-03-15 16:10:44 -07001358 String versionString = parser.getAttributeValue(null, "version");
1359 int version;
1360 try {
1361 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1362 } catch (NumberFormatException e) {
1363 version = 0;
1364 }
1365 if (version < ACCOUNTS_VERSION) {
1366 writeNeeded = true;
1367 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001368 mMasterSyncAutomatically = listen == null
Dianne Hackborn231cc602009-04-27 17:10:36 -07001369 || Boolean.parseBoolean(listen);
1370 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001371 AuthorityInfo authority = null;
1372 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001373 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001374 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001375 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001376 if (parser.getDepth() == 2) {
1377 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001378 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001379 periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001380 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001381 } else if (parser.getDepth() == 3) {
1382 if ("periodicSync".equals(tagName) && authority != null) {
1383 periodicSync = parsePeriodicSync(parser, authority);
1384 }
1385 } else if (parser.getDepth() == 4 && periodicSync != null) {
1386 if ("extra".equals(tagName)) {
1387 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001388 }
1389 }
1390 }
1391 eventType = parser.next();
1392 } while (eventType != XmlPullParser.END_DOCUMENT);
1393 }
1394 } catch (XmlPullParserException e) {
1395 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001396 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001397 } catch (java.io.IOException e) {
1398 if (fis == null) Log.i(TAG, "No initial accounts");
1399 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001400 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001401 } finally {
1402 if (fis != null) {
1403 try {
1404 fis.close();
1405 } catch (java.io.IOException e1) {
1406 }
1407 }
1408 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001409
1410 if (writeNeeded) {
1411 writeAccountInfoLocked();
1412 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001413 }
Costin Manolache360e4542009-09-04 13:36:04 -07001414
Fred Quintanac2e46912010-03-15 16:10:44 -07001415 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001416 AuthorityInfo authority = null;
1417 int id = -1;
1418 try {
1419 id = Integer.parseInt(parser.getAttributeValue(
1420 null, "id"));
1421 } catch (NumberFormatException e) {
1422 Log.e(TAG, "error parsing the id of the authority", e);
1423 } catch (NullPointerException e) {
1424 Log.e(TAG, "the id of the authority is null", e);
1425 }
1426 if (id >= 0) {
1427 String accountName = parser.getAttributeValue(null, "account");
1428 String accountType = parser.getAttributeValue(null, "type");
1429 if (accountType == null) {
1430 accountType = "com.google";
1431 }
1432 String authorityName = parser.getAttributeValue(null, "authority");
1433 String enabled = parser.getAttributeValue(null, "enabled");
1434 String syncable = parser.getAttributeValue(null, "syncable");
1435 authority = mAuthorities.get(id);
1436 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1437 + accountName + " auth=" + authorityName
1438 + " enabled=" + enabled
1439 + " syncable=" + syncable);
1440 if (authority == null) {
1441 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1442 authority = getOrCreateAuthorityLocked(
1443 new Account(accountName, accountType), authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001444 // If the version is 0 then we are upgrading from a file format that did not
1445 // know about periodic syncs. In that case don't clear the list since we
1446 // want the default, which is a daily periodioc sync.
1447 // Otherwise clear out this default list since we will populate it later with
1448 // the periodic sync descriptions that are read from the configuration file.
1449 if (version > 0) {
1450 authority.periodicSyncs.clear();
1451 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001452 }
1453 if (authority != null) {
1454 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1455 if ("unknown".equals(syncable)) {
1456 authority.syncable = -1;
1457 } else {
1458 authority.syncable =
1459 (syncable == null || Boolean.parseBoolean(enabled)) ? 1 : 0;
1460 }
1461 } else {
1462 Log.w(TAG, "Failure adding authority: account="
1463 + accountName + " auth=" + authorityName
1464 + " enabled=" + enabled
1465 + " syncable=" + syncable);
1466 }
1467 }
1468
1469 return authority;
1470 }
1471
1472 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1473 Bundle extras = new Bundle();
1474 String periodValue = parser.getAttributeValue(null, "period");
1475 final long period;
1476 try {
1477 period = Long.parseLong(periodValue);
1478 } catch (NumberFormatException e) {
1479 Log.e(TAG, "error parsing the period of a periodic sync", e);
1480 return null;
1481 } catch (NullPointerException e) {
1482 Log.e(TAG, "the period of a periodic sync is null", e);
1483 return null;
1484 }
1485 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1486 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001487
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001488 return periodicSync;
1489 }
1490
1491 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1492 final Bundle extras = periodicSync.first;
1493 String name = parser.getAttributeValue(null, "name");
1494 String type = parser.getAttributeValue(null, "type");
1495 String value1 = parser.getAttributeValue(null, "value1");
1496 String value2 = parser.getAttributeValue(null, "value2");
1497
1498 try {
1499 if ("long".equals(type)) {
1500 extras.putLong(name, Long.parseLong(value1));
1501 } else if ("integer".equals(type)) {
1502 extras.putInt(name, Integer.parseInt(value1));
1503 } else if ("double".equals(type)) {
1504 extras.putDouble(name, Double.parseDouble(value1));
1505 } else if ("float".equals(type)) {
1506 extras.putFloat(name, Float.parseFloat(value1));
1507 } else if ("boolean".equals(type)) {
1508 extras.putBoolean(name, Boolean.parseBoolean(value1));
1509 } else if ("string".equals(type)) {
1510 extras.putString(name, value1);
1511 } else if ("account".equals(type)) {
1512 extras.putParcelable(name, new Account(value1, value2));
1513 }
1514 } catch (NumberFormatException e) {
1515 Log.e(TAG, "error parsing bundle value", e);
1516 } catch (NullPointerException e) {
1517 Log.e(TAG, "error parsing bundle value", e);
1518 }
1519 }
1520
Dianne Hackborn231cc602009-04-27 17:10:36 -07001521 /**
1522 * Write all account information to the account file.
1523 */
1524 private void writeAccountInfoLocked() {
1525 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1526 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001527
Dianne Hackborn231cc602009-04-27 17:10:36 -07001528 try {
1529 fos = mAccountInfoFile.startWrite();
1530 XmlSerializer out = new FastXmlSerializer();
1531 out.setOutput(fos, "utf-8");
1532 out.startDocument(null, true);
1533 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001534
Dianne Hackborn231cc602009-04-27 17:10:36 -07001535 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001536 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Fred Quintanaac9385e2009-06-22 18:00:59 -07001537 if (!mMasterSyncAutomatically) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001538 out.attribute(null, "listen-for-tickles", "false");
1539 }
Costin Manolache360e4542009-09-04 13:36:04 -07001540
Dianne Hackborn231cc602009-04-27 17:10:36 -07001541 final int N = mAuthorities.size();
1542 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001543 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001544 out.startTag(null, "authority");
1545 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001546 out.attribute(null, "account", authority.account.name);
1547 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001548 out.attribute(null, "authority", authority.authority);
1549 if (!authority.enabled) {
1550 out.attribute(null, "enabled", "false");
Fred Quintana7620f1a2010-03-16 15:58:44 -07001551 }
Fred Quintana5e787c42009-08-16 23:13:53 -07001552 if (authority.syncable < 0) {
1553 out.attribute(null, "syncable", "unknown");
1554 } else if (authority.syncable == 0) {
1555 out.attribute(null, "syncable", "false");
1556 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001557 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1558 out.startTag(null, "periodicSync");
1559 out.attribute(null, "period", Long.toString(periodicSync.second));
1560 final Bundle extras = periodicSync.first;
1561 for (String key : extras.keySet()) {
1562 out.startTag(null, "extra");
1563 out.attribute(null, "name", key);
1564 final Object value = extras.get(key);
1565 if (value instanceof Long) {
1566 out.attribute(null, "type", "long");
1567 out.attribute(null, "value1", value.toString());
1568 } else if (value instanceof Integer) {
1569 out.attribute(null, "type", "integer");
1570 out.attribute(null, "value1", value.toString());
1571 } else if (value instanceof Boolean) {
1572 out.attribute(null, "type", "boolean");
1573 out.attribute(null, "value1", value.toString());
1574 } else if (value instanceof Float) {
1575 out.attribute(null, "type", "float");
1576 out.attribute(null, "value1", value.toString());
1577 } else if (value instanceof Double) {
1578 out.attribute(null, "type", "double");
1579 out.attribute(null, "value1", value.toString());
1580 } else if (value instanceof String) {
1581 out.attribute(null, "type", "string");
1582 out.attribute(null, "value1", value.toString());
1583 } else if (value instanceof Account) {
1584 out.attribute(null, "type", "account");
1585 out.attribute(null, "value1", ((Account)value).name);
1586 out.attribute(null, "value2", ((Account)value).type);
1587 }
1588 out.endTag(null, "extra");
1589 }
1590 out.endTag(null, "periodicSync");
1591 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001592 out.endTag(null, "authority");
1593 }
Costin Manolache360e4542009-09-04 13:36:04 -07001594
Dianne Hackborn231cc602009-04-27 17:10:36 -07001595 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001596
Dianne Hackborn231cc602009-04-27 17:10:36 -07001597 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001598
Dianne Hackborn231cc602009-04-27 17:10:36 -07001599 mAccountInfoFile.finishWrite(fos);
1600 } catch (java.io.IOException e1) {
1601 Log.w(TAG, "Error writing accounts", e1);
1602 if (fos != null) {
1603 mAccountInfoFile.failWrite(fos);
1604 }
1605 }
1606 }
Costin Manolache360e4542009-09-04 13:36:04 -07001607
Dianne Hackborn231cc602009-04-27 17:10:36 -07001608 static int getIntColumn(Cursor c, String name) {
1609 return c.getInt(c.getColumnIndex(name));
1610 }
Costin Manolache360e4542009-09-04 13:36:04 -07001611
Dianne Hackborn231cc602009-04-27 17:10:36 -07001612 static long getLongColumn(Cursor c, String name) {
1613 return c.getLong(c.getColumnIndex(name));
1614 }
Costin Manolache360e4542009-09-04 13:36:04 -07001615
Dianne Hackborn231cc602009-04-27 17:10:36 -07001616 /**
1617 * Load sync engine state from the old syncmanager database, and then
1618 * erase it. Note that we don't deal with pending operations, active
1619 * sync, or history.
1620 */
1621 private void readLegacyAccountInfoLocked() {
1622 // Look for old database to initialize from.
1623 File file = mContext.getDatabasePath("syncmanager.db");
1624 if (!file.exists()) {
1625 return;
1626 }
1627 String path = file.getPath();
1628 SQLiteDatabase db = null;
1629 try {
1630 db = SQLiteDatabase.openDatabase(path, null,
1631 SQLiteDatabase.OPEN_READONLY);
1632 } catch (SQLiteException e) {
1633 }
Costin Manolache360e4542009-09-04 13:36:04 -07001634
Dianne Hackborn231cc602009-04-27 17:10:36 -07001635 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001636 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001637
Dianne Hackborn231cc602009-04-27 17:10:36 -07001638 // Copy in all of the status information, as well as accounts.
1639 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1640 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1641 qb.setTables("stats, status");
1642 HashMap<String,String> map = new HashMap<String,String>();
1643 map.put("_id", "status._id as _id");
1644 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001645 if (hasType) {
1646 map.put("account_type", "stats.account_type as account_type");
1647 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001648 map.put("authority", "stats.authority as authority");
1649 map.put("totalElapsedTime", "totalElapsedTime");
1650 map.put("numSyncs", "numSyncs");
1651 map.put("numSourceLocal", "numSourceLocal");
1652 map.put("numSourcePoll", "numSourcePoll");
1653 map.put("numSourceServer", "numSourceServer");
1654 map.put("numSourceUser", "numSourceUser");
1655 map.put("lastSuccessSource", "lastSuccessSource");
1656 map.put("lastSuccessTime", "lastSuccessTime");
1657 map.put("lastFailureSource", "lastFailureSource");
1658 map.put("lastFailureTime", "lastFailureTime");
1659 map.put("lastFailureMesg", "lastFailureMesg");
1660 map.put("pending", "pending");
1661 qb.setProjectionMap(map);
1662 qb.appendWhere("stats._id = status.stats_id");
1663 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001665 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001666 String accountType = hasType
1667 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001668 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001669 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001671 String authorityName = c.getString(c.getColumnIndex("authority"));
1672 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Dianne Hackborn7a135592009-05-06 00:28:37 -07001673 new Account(accountName, accountType),
1674 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001675 if (authority != null) {
1676 int i = mSyncStatus.size();
1677 boolean found = false;
1678 SyncStatusInfo st = null;
1679 while (i > 0) {
1680 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001681 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001682 if (st.authorityId == authority.ident) {
1683 found = true;
1684 break;
1685 }
1686 }
1687 if (!found) {
1688 st = new SyncStatusInfo(authority.ident);
1689 mSyncStatus.put(authority.ident, st);
1690 }
1691 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1692 st.numSyncs = getIntColumn(c, "numSyncs");
1693 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1694 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1695 st.numSourceServer = getIntColumn(c, "numSourceServer");
1696 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001697 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001698 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1699 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1700 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1701 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1702 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1703 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
Costin Manolache360e4542009-09-04 13:36:04 -07001706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001708
Dianne Hackborn231cc602009-04-27 17:10:36 -07001709 // Retrieve the settings.
1710 qb = new SQLiteQueryBuilder();
1711 qb.setTables("settings");
1712 c = qb.query(db, null, null, null, null, null, null);
1713 while (c.moveToNext()) {
1714 String name = c.getString(c.getColumnIndex("name"));
1715 String value = c.getString(c.getColumnIndex("value"));
1716 if (name == null) continue;
1717 if (name.equals("listen_for_tickles")) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001718 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001719 } else if (name.startsWith("sync_provider_")) {
1720 String provider = name.substring("sync_provider_".length(),
1721 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001722 int i = mAuthorities.size();
1723 while (i > 0) {
1724 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001725 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001726 if (authority.authority.equals(provider)) {
1727 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001728 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001729 }
1730 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 }
Costin Manolache360e4542009-09-04 13:36:04 -07001733
Dianne Hackborn231cc602009-04-27 17:10:36 -07001734 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001735
Dianne Hackborn231cc602009-04-27 17:10:36 -07001736 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001737
Dianne Hackborn231cc602009-04-27 17:10:36 -07001738 writeAccountInfoLocked();
1739 writeStatusLocked();
1740 (new File(path)).delete();
1741 }
1742 }
Costin Manolache360e4542009-09-04 13:36:04 -07001743
Dianne Hackborn231cc602009-04-27 17:10:36 -07001744 public static final int STATUS_FILE_END = 0;
1745 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001746
Dianne Hackborn231cc602009-04-27 17:10:36 -07001747 /**
1748 * Read all sync status back in to the initial engine state.
1749 */
1750 private void readStatusLocked() {
1751 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
1752 try {
1753 byte[] data = mStatusFile.readFully();
1754 Parcel in = Parcel.obtain();
1755 in.unmarshall(data, 0, data.length);
1756 in.setDataPosition(0);
1757 int token;
1758 while ((token=in.readInt()) != STATUS_FILE_END) {
1759 if (token == STATUS_FILE_ITEM) {
1760 SyncStatusInfo status = new SyncStatusInfo(in);
1761 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1762 status.pending = false;
1763 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
1764 + status.authorityId);
1765 mSyncStatus.put(status.authorityId, status);
1766 }
1767 } else {
1768 // Ooops.
1769 Log.w(TAG, "Unknown status token: " + token);
1770 break;
1771 }
1772 }
1773 } catch (java.io.IOException e) {
1774 Log.i(TAG, "No initial status");
1775 }
1776 }
Costin Manolache360e4542009-09-04 13:36:04 -07001777
Dianne Hackborn231cc602009-04-27 17:10:36 -07001778 /**
1779 * Write all sync status to the sync status file.
1780 */
1781 private void writeStatusLocked() {
1782 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07001783
Dianne Hackborn231cc602009-04-27 17:10:36 -07001784 // The file is being written, so we don't need to have a scheduled
1785 // write until the next change.
1786 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07001787
Dianne Hackborn231cc602009-04-27 17:10:36 -07001788 FileOutputStream fos = null;
1789 try {
1790 fos = mStatusFile.startWrite();
1791 Parcel out = Parcel.obtain();
1792 final int N = mSyncStatus.size();
1793 for (int i=0; i<N; i++) {
1794 SyncStatusInfo status = mSyncStatus.valueAt(i);
1795 out.writeInt(STATUS_FILE_ITEM);
1796 status.writeToParcel(out, 0);
1797 }
1798 out.writeInt(STATUS_FILE_END);
1799 fos.write(out.marshall());
1800 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07001801
Dianne Hackborn231cc602009-04-27 17:10:36 -07001802 mStatusFile.finishWrite(fos);
1803 } catch (java.io.IOException e1) {
1804 Log.w(TAG, "Error writing status", e1);
1805 if (fos != null) {
1806 mStatusFile.failWrite(fos);
1807 }
1808 }
1809 }
Costin Manolache360e4542009-09-04 13:36:04 -07001810
Fred Quintana307da1a2010-01-21 14:24:20 -08001811 public static final int PENDING_OPERATION_VERSION = 2;
Costin Manolache360e4542009-09-04 13:36:04 -07001812
Dianne Hackborn231cc602009-04-27 17:10:36 -07001813 /**
1814 * Read all pending operations back in to the initial engine state.
1815 */
1816 private void readPendingOperationsLocked() {
1817 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
1818 try {
1819 byte[] data = mPendingFile.readFully();
1820 Parcel in = Parcel.obtain();
1821 in.unmarshall(data, 0, data.length);
1822 in.setDataPosition(0);
1823 final int SIZE = in.dataSize();
1824 while (in.dataPosition() < SIZE) {
1825 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08001826 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001827 Log.w(TAG, "Unknown pending operation version "
1828 + version + "; dropping all ops");
1829 break;
1830 }
1831 int authorityId = in.readInt();
1832 int syncSource = in.readInt();
1833 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08001834 boolean expedited;
1835 if (version == PENDING_OPERATION_VERSION) {
1836 expedited = in.readInt() != 0;
1837 } else {
1838 expedited = false;
1839 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001840 AuthorityInfo authority = mAuthorities.get(authorityId);
1841 if (authority != null) {
1842 Bundle extras = null;
1843 if (flatExtras != null) {
1844 extras = unflattenBundle(flatExtras);
1845 }
1846 PendingOperation op = new PendingOperation(
1847 authority.account, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08001848 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001849 op.authorityId = authorityId;
1850 op.flatExtras = flatExtras;
1851 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
1852 + " auth=" + op.authority
1853 + " src=" + op.syncSource
Fred Quintana307da1a2010-01-21 14:24:20 -08001854 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07001855 + " extras=" + op.extras);
1856 mPendingOperations.add(op);
1857 }
1858 }
1859 } catch (java.io.IOException e) {
1860 Log.i(TAG, "No initial pending operations");
1861 }
1862 }
Costin Manolache360e4542009-09-04 13:36:04 -07001863
Dianne Hackborn231cc602009-04-27 17:10:36 -07001864 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
1865 out.writeInt(PENDING_OPERATION_VERSION);
1866 out.writeInt(op.authorityId);
1867 out.writeInt(op.syncSource);
1868 if (op.flatExtras == null && op.extras != null) {
1869 op.flatExtras = flattenBundle(op.extras);
1870 }
1871 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08001872 out.writeInt(op.expedited ? 1 : 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001873 }
Costin Manolache360e4542009-09-04 13:36:04 -07001874
Dianne Hackborn231cc602009-04-27 17:10:36 -07001875 /**
1876 * Write all currently pending ops to the pending ops file.
1877 */
1878 private void writePendingOperationsLocked() {
1879 final int N = mPendingOperations.size();
1880 FileOutputStream fos = null;
1881 try {
1882 if (N == 0) {
1883 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
1884 mPendingFile.truncate();
1885 return;
1886 }
Costin Manolache360e4542009-09-04 13:36:04 -07001887
Dianne Hackborn231cc602009-04-27 17:10:36 -07001888 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
1889 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07001890
Dianne Hackborn231cc602009-04-27 17:10:36 -07001891 Parcel out = Parcel.obtain();
1892 for (int i=0; i<N; i++) {
1893 PendingOperation op = mPendingOperations.get(i);
1894 writePendingOperationLocked(op, out);
1895 }
1896 fos.write(out.marshall());
1897 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07001898
Dianne Hackborn231cc602009-04-27 17:10:36 -07001899 mPendingFile.finishWrite(fos);
1900 } catch (java.io.IOException e1) {
1901 Log.w(TAG, "Error writing pending operations", e1);
1902 if (fos != null) {
1903 mPendingFile.failWrite(fos);
1904 }
1905 }
1906 }
Costin Manolache360e4542009-09-04 13:36:04 -07001907
Dianne Hackborn231cc602009-04-27 17:10:36 -07001908 /**
1909 * Append the given operation to the pending ops file; if unable to,
1910 * write all pending ops.
1911 */
1912 private void appendPendingOperationLocked(PendingOperation op) {
1913 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
1914 FileOutputStream fos = null;
1915 try {
1916 fos = mPendingFile.openAppend();
1917 } catch (java.io.IOException e) {
1918 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
1919 writePendingOperationsLocked();
1920 return;
1921 }
Costin Manolache360e4542009-09-04 13:36:04 -07001922
Dianne Hackborn231cc602009-04-27 17:10:36 -07001923 try {
1924 Parcel out = Parcel.obtain();
1925 writePendingOperationLocked(op, out);
1926 fos.write(out.marshall());
1927 out.recycle();
1928 } catch (java.io.IOException e1) {
1929 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001931 try {
1932 fos.close();
1933 } catch (java.io.IOException e2) {
1934 }
1935 }
1936 }
Costin Manolache360e4542009-09-04 13:36:04 -07001937
Dianne Hackborn231cc602009-04-27 17:10:36 -07001938 static private byte[] flattenBundle(Bundle bundle) {
1939 byte[] flatData = null;
1940 Parcel parcel = Parcel.obtain();
1941 try {
1942 bundle.writeToParcel(parcel, 0);
1943 flatData = parcel.marshall();
1944 } finally {
1945 parcel.recycle();
1946 }
1947 return flatData;
1948 }
Costin Manolache360e4542009-09-04 13:36:04 -07001949
Dianne Hackborn231cc602009-04-27 17:10:36 -07001950 static private Bundle unflattenBundle(byte[] flatData) {
1951 Bundle bundle;
1952 Parcel parcel = Parcel.obtain();
1953 try {
1954 parcel.unmarshall(flatData, 0, flatData.length);
1955 parcel.setDataPosition(0);
1956 bundle = parcel.readBundle();
1957 } catch (RuntimeException e) {
1958 // A RuntimeException is thrown if we were unable to parse the parcel.
1959 // Create an empty parcel in this case.
1960 bundle = new Bundle();
1961 } finally {
1962 parcel.recycle();
1963 }
1964 return bundle;
1965 }
Costin Manolache360e4542009-09-04 13:36:04 -07001966
Dianne Hackborn231cc602009-04-27 17:10:36 -07001967 public static final int STATISTICS_FILE_END = 0;
1968 public static final int STATISTICS_FILE_ITEM_OLD = 100;
1969 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07001970
Dianne Hackborn231cc602009-04-27 17:10:36 -07001971 /**
1972 * Read all sync statistics back in to the initial engine state.
1973 */
1974 private void readStatisticsLocked() {
1975 try {
1976 byte[] data = mStatisticsFile.readFully();
1977 Parcel in = Parcel.obtain();
1978 in.unmarshall(data, 0, data.length);
1979 in.setDataPosition(0);
1980 int token;
1981 int index = 0;
1982 while ((token=in.readInt()) != STATISTICS_FILE_END) {
1983 if (token == STATISTICS_FILE_ITEM
1984 || token == STATISTICS_FILE_ITEM_OLD) {
1985 int day = in.readInt();
1986 if (token == STATISTICS_FILE_ITEM_OLD) {
1987 day = day - 2009 + 14245; // Magic!
1988 }
1989 DayStats ds = new DayStats(day);
1990 ds.successCount = in.readInt();
1991 ds.successTime = in.readLong();
1992 ds.failureCount = in.readInt();
1993 ds.failureTime = in.readLong();
1994 if (index < mDayStats.length) {
1995 mDayStats[index] = ds;
1996 index++;
1997 }
1998 } else {
1999 // Ooops.
2000 Log.w(TAG, "Unknown stats token: " + token);
2001 break;
2002 }
2003 }
2004 } catch (java.io.IOException e) {
2005 Log.i(TAG, "No initial statistics");
2006 }
2007 }
Costin Manolache360e4542009-09-04 13:36:04 -07002008
Dianne Hackborn231cc602009-04-27 17:10:36 -07002009 /**
2010 * Write all sync statistics to the sync status file.
2011 */
2012 private void writeStatisticsLocked() {
2013 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002014
Dianne Hackborn231cc602009-04-27 17:10:36 -07002015 // The file is being written, so we don't need to have a scheduled
2016 // write until the next change.
2017 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002018
Dianne Hackborn231cc602009-04-27 17:10:36 -07002019 FileOutputStream fos = null;
2020 try {
2021 fos = mStatisticsFile.startWrite();
2022 Parcel out = Parcel.obtain();
2023 final int N = mDayStats.length;
2024 for (int i=0; i<N; i++) {
2025 DayStats ds = mDayStats[i];
2026 if (ds == null) {
2027 break;
2028 }
2029 out.writeInt(STATISTICS_FILE_ITEM);
2030 out.writeInt(ds.day);
2031 out.writeInt(ds.successCount);
2032 out.writeLong(ds.successTime);
2033 out.writeInt(ds.failureCount);
2034 out.writeLong(ds.failureTime);
2035 }
2036 out.writeInt(STATISTICS_FILE_END);
2037 fos.write(out.marshall());
2038 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002039
Dianne Hackborn231cc602009-04-27 17:10:36 -07002040 mStatisticsFile.finishWrite(fos);
2041 } catch (java.io.IOException e1) {
2042 Log.w(TAG, "Error writing stats", e1);
2043 if (fos != null) {
2044 mStatisticsFile.failWrite(fos);
2045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 }
2047 }
2048}