blob: 0ec24530e7f6908abb62b43e31f09bb02ef2fab1 [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
Dianne Hackborn231cc602009-04-27 17:10:36 -0700646 public AuthorityInfo getAuthority(int authorityId) {
647 synchronized (mAuthorities) {
648 return mAuthorities.get(authorityId);
649 }
650 }
Costin Manolache360e4542009-09-04 13:36:04 -0700651
Dianne Hackborn231cc602009-04-27 17:10:36 -0700652 /**
653 * Returns true if there is currently a sync operation for the given
654 * account or authority in the pending list, or actively being processed.
655 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700656 public boolean isSyncActive(Account account, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700657 synchronized (mAuthorities) {
658 int i = mPendingOperations.size();
659 while (i > 0) {
660 i--;
661 // TODO(fredq): this probably shouldn't be considering
662 // pending operations.
663 PendingOperation op = mPendingOperations.get(i);
664 if (op.account.equals(account) && op.authority.equals(authority)) {
665 return true;
666 }
667 }
Costin Manolache360e4542009-09-04 13:36:04 -0700668
Dianne Hackborn231cc602009-04-27 17:10:36 -0700669 if (mActiveSync != null) {
Fred Quintana1b487ec2010-02-26 10:57:55 -0800670 AuthorityInfo ainfo = getAuthority(mActiveSync.getAuthorityId());
Dianne Hackborn231cc602009-04-27 17:10:36 -0700671 if (ainfo != null && ainfo.account.equals(account)
672 && ainfo.authority.equals(authority)) {
673 return true;
674 }
675 }
676 }
Costin Manolache360e4542009-09-04 13:36:04 -0700677
Dianne Hackborn231cc602009-04-27 17:10:36 -0700678 return false;
679 }
Costin Manolache360e4542009-09-04 13:36:04 -0700680
Dianne Hackborn231cc602009-04-27 17:10:36 -0700681 public PendingOperation insertIntoPending(PendingOperation op) {
682 synchronized (mAuthorities) {
683 if (DEBUG) Log.v(TAG, "insertIntoPending: account=" + op.account
684 + " auth=" + op.authority
685 + " src=" + op.syncSource
686 + " extras=" + op.extras);
Costin Manolache360e4542009-09-04 13:36:04 -0700687
Dianne Hackborn231cc602009-04-27 17:10:36 -0700688 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account,
689 op.authority,
690 -1 /* desired identifier */,
691 true /* write accounts to storage */);
692 if (authority == null) {
693 return null;
694 }
Costin Manolache360e4542009-09-04 13:36:04 -0700695
Dianne Hackborn231cc602009-04-27 17:10:36 -0700696 op = new PendingOperation(op);
697 op.authorityId = authority.ident;
698 mPendingOperations.add(op);
699 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700700
Dianne Hackborn231cc602009-04-27 17:10:36 -0700701 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
702 status.pending = true;
703 }
Costin Manolache360e4542009-09-04 13:36:04 -0700704
Fred Quintanaac9385e2009-06-22 18:00:59 -0700705 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700706 return op;
707 }
708
709 public boolean deleteFromPending(PendingOperation op) {
710 boolean res = false;
711 synchronized (mAuthorities) {
712 if (DEBUG) Log.v(TAG, "deleteFromPending: account=" + op.account
713 + " auth=" + op.authority
714 + " src=" + op.syncSource
715 + " extras=" + op.extras);
716 if (mPendingOperations.remove(op)) {
717 if (mPendingOperations.size() == 0
718 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
719 writePendingOperationsLocked();
720 mNumPendingFinished = 0;
721 } else {
722 mNumPendingFinished++;
723 }
Costin Manolache360e4542009-09-04 13:36:04 -0700724
Dianne Hackborn231cc602009-04-27 17:10:36 -0700725 AuthorityInfo authority = getAuthorityLocked(op.account, op.authority,
726 "deleteFromPending");
727 if (authority != null) {
728 if (DEBUG) Log.v(TAG, "removing - " + authority);
729 final int N = mPendingOperations.size();
730 boolean morePending = false;
731 for (int i=0; i<N; i++) {
732 PendingOperation cur = mPendingOperations.get(i);
733 if (cur.account.equals(op.account)
734 && cur.authority.equals(op.authority)) {
735 morePending = true;
736 break;
737 }
738 }
Costin Manolache360e4542009-09-04 13:36:04 -0700739
Dianne Hackborn231cc602009-04-27 17:10:36 -0700740 if (!morePending) {
741 if (DEBUG) Log.v(TAG, "no more pending!");
742 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
743 status.pending = false;
744 }
745 }
Costin Manolache360e4542009-09-04 13:36:04 -0700746
Dianne Hackborn231cc602009-04-27 17:10:36 -0700747 res = true;
748 }
749 }
Costin Manolache360e4542009-09-04 13:36:04 -0700750
Fred Quintanaac9385e2009-06-22 18:00:59 -0700751 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700752 return res;
753 }
754
755 public int clearPending() {
756 int num;
757 synchronized (mAuthorities) {
758 if (DEBUG) Log.v(TAG, "clearPending");
759 num = mPendingOperations.size();
760 mPendingOperations.clear();
761 final int N = mSyncStatus.size();
762 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -0700763 mSyncStatus.valueAt(i).pending = false;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700764 }
765 writePendingOperationsLocked();
766 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700767 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700768 return num;
769 }
770
771 /**
772 * Return a copy of the current array of pending operations. The
773 * PendingOperation objects are the real objects stored inside, so that
774 * they can be used with deleteFromPending().
775 */
776 public ArrayList<PendingOperation> getPendingOperations() {
777 synchronized (mAuthorities) {
778 return new ArrayList<PendingOperation>(mPendingOperations);
779 }
780 }
Costin Manolache360e4542009-09-04 13:36:04 -0700781
Dianne Hackborn231cc602009-04-27 17:10:36 -0700782 /**
783 * Return the number of currently pending operations.
784 */
785 public int getPendingOperationCount() {
786 synchronized (mAuthorities) {
787 return mPendingOperations.size();
788 }
789 }
Costin Manolache360e4542009-09-04 13:36:04 -0700790
Dianne Hackborn231cc602009-04-27 17:10:36 -0700791 /**
792 * Called when the set of account has changed, given the new array of
793 * active accounts.
794 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700795 public void doDatabaseCleanup(Account[] accounts) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700796 synchronized (mAuthorities) {
797 if (DEBUG) Log.w(TAG, "Updating for new accounts...");
798 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
799 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
800 while (accIt.hasNext()) {
801 AccountInfo acc = accIt.next();
802 if (!ArrayUtils.contains(accounts, acc.account)) {
803 // This account no longer exists...
804 if (DEBUG) Log.w(TAG, "Account removed: " + acc.account);
805 for (AuthorityInfo auth : acc.authorities.values()) {
806 removing.put(auth.ident, auth);
807 }
808 accIt.remove();
809 }
810 }
Costin Manolache360e4542009-09-04 13:36:04 -0700811
Dianne Hackborn231cc602009-04-27 17:10:36 -0700812 // Clean out all data structures.
813 int i = removing.size();
814 if (i > 0) {
815 while (i > 0) {
816 i--;
817 int ident = removing.keyAt(i);
818 mAuthorities.remove(ident);
819 int j = mSyncStatus.size();
820 while (j > 0) {
821 j--;
822 if (mSyncStatus.keyAt(j) == ident) {
823 mSyncStatus.remove(mSyncStatus.keyAt(j));
824 }
825 }
826 j = mSyncHistory.size();
827 while (j > 0) {
828 j--;
829 if (mSyncHistory.get(j).authorityId == ident) {
830 mSyncHistory.remove(j);
831 }
832 }
833 }
834 writeAccountInfoLocked();
835 writeStatusLocked();
836 writePendingOperationsLocked();
837 writeStatisticsLocked();
838 }
839 }
840 }
841
842 /**
843 * Called when the currently active sync is changing (there can only be
844 * one at a time). Either supply a valid ActiveSyncContext with information
845 * about the sync, or null to stop the currently active sync.
846 */
847 public void setActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
848 synchronized (mAuthorities) {
849 if (activeSyncContext != null) {
850 if (DEBUG) Log.v(TAG, "setActiveSync: account="
851 + activeSyncContext.mSyncOperation.account
852 + " auth=" + activeSyncContext.mSyncOperation.authority
853 + " src=" + activeSyncContext.mSyncOperation.syncSource
854 + " extras=" + activeSyncContext.mSyncOperation.extras);
855 if (mActiveSync != null) {
856 Log.w(TAG, "setActiveSync called with existing active sync!");
857 }
858 AuthorityInfo authority = getAuthorityLocked(
859 activeSyncContext.mSyncOperation.account,
860 activeSyncContext.mSyncOperation.authority,
861 "setActiveSync");
862 if (authority == null) {
863 return;
864 }
865 mActiveSync = new ActiveSyncInfo(authority.ident,
866 authority.account, authority.authority,
867 activeSyncContext.mStartTime);
868 } else {
869 if (DEBUG) Log.v(TAG, "setActiveSync: null");
870 mActiveSync = null;
871 }
872 }
Costin Manolache360e4542009-09-04 13:36:04 -0700873
Fred Quintanaac9385e2009-06-22 18:00:59 -0700874 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700875 }
876
877 /**
878 * To allow others to send active change reports, to poke clients.
879 */
880 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -0700881 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700882 }
Costin Manolache360e4542009-09-04 13:36:04 -0700883
Dianne Hackborn231cc602009-04-27 17:10:36 -0700884 /**
885 * Note that sync has started for the given account and authority.
886 */
Dianne Hackborn7a135592009-05-06 00:28:37 -0700887 public long insertStartSyncEvent(Account accountName, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700888 long now, int source) {
889 long id;
890 synchronized (mAuthorities) {
891 if (DEBUG) Log.v(TAG, "insertStartSyncEvent: account=" + accountName
892 + " auth=" + authorityName + " source=" + source);
893 AuthorityInfo authority = getAuthorityLocked(accountName, authorityName,
894 "insertStartSyncEvent");
895 if (authority == null) {
896 return -1;
897 }
898 SyncHistoryItem item = new SyncHistoryItem();
899 item.authorityId = authority.ident;
900 item.historyId = mNextHistoryId++;
901 if (mNextHistoryId < 0) mNextHistoryId = 0;
902 item.eventTime = now;
903 item.source = source;
904 item.event = EVENT_START;
905 mSyncHistory.add(0, item);
906 while (mSyncHistory.size() > MAX_HISTORY) {
907 mSyncHistory.remove(mSyncHistory.size()-1);
908 }
909 id = item.historyId;
910 if (DEBUG) Log.v(TAG, "returning historyId " + id);
911 }
Costin Manolache360e4542009-09-04 13:36:04 -0700912
Fred Quintanaac9385e2009-06-22 18:00:59 -0700913 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700914 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
916
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800917 public static boolean equals(Bundle b1, Bundle b2) {
918 if (b1.size() != b2.size()) {
919 return false;
920 }
921 if (b1.isEmpty()) {
922 return true;
923 }
924 for (String key : b1.keySet()) {
925 if (!b2.containsKey(key)) {
926 return false;
927 }
928 if (!b1.get(key).equals(b2.get(key))) {
929 return false;
930 }
931 }
932 return true;
933 }
934
935 public void stopSyncEvent(long historyId, Bundle extras, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700937 synchronized (mAuthorities) {
938 if (DEBUG) Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
939 SyncHistoryItem item = null;
940 int i = mSyncHistory.size();
941 while (i > 0) {
942 i--;
943 item = mSyncHistory.get(i);
944 if (item.historyId == historyId) {
945 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700947 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
Costin Manolache360e4542009-09-04 13:36:04 -0700949
Dianne Hackborn231cc602009-04-27 17:10:36 -0700950 if (item == null) {
951 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
952 return;
953 }
Costin Manolache360e4542009-09-04 13:36:04 -0700954
Dianne Hackborn231cc602009-04-27 17:10:36 -0700955 item.elapsedTime = elapsedTime;
956 item.event = EVENT_STOP;
957 item.mesg = resultMessage;
958 item.downstreamActivity = downstreamActivity;
959 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -0700960
Dianne Hackborn231cc602009-04-27 17:10:36 -0700961 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -0700962
Dianne Hackborn231cc602009-04-27 17:10:36 -0700963 status.numSyncs++;
964 status.totalElapsedTime += elapsedTime;
965 switch (item.source) {
966 case SOURCE_LOCAL:
967 status.numSourceLocal++;
968 break;
969 case SOURCE_POLL:
970 status.numSourcePoll++;
971 break;
972 case SOURCE_USER:
973 status.numSourceUser++;
974 break;
975 case SOURCE_SERVER:
976 status.numSourceServer++;
977 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800978 case SOURCE_PERIODIC:
979 status.numSourcePeriodic++;
980 AuthorityInfo authority = mAuthorities.get(item.authorityId);
981 for (int periodicSyncIndex = 0;
982 periodicSyncIndex < authority.periodicSyncs.size();
983 periodicSyncIndex++) {
984 if (equals(extras, authority.periodicSyncs.get(periodicSyncIndex).first)) {
985 status.setPeriodicSyncTime(periodicSyncIndex, item.eventTime);
986 }
987 }
988 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700989 }
Costin Manolache360e4542009-09-04 13:36:04 -0700990
Dianne Hackborn231cc602009-04-27 17:10:36 -0700991 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -0700992 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700993 if (mDayStats[0] == null) {
994 mDayStats[0] = new DayStats(day);
995 } else if (day != mDayStats[0].day) {
996 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
997 mDayStats[0] = new DayStats(day);
998 writeStatisticsNow = true;
999 } else if (mDayStats[0] == null) {
1000 }
1001 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001002
Dianne Hackborn231cc602009-04-27 17:10:36 -07001003 final long lastSyncTime = (item.eventTime + elapsedTime);
1004 boolean writeStatusNow = false;
1005 if (MESG_SUCCESS.equals(resultMessage)) {
1006 // - if successful, update the successful columns
1007 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1008 writeStatusNow = true;
1009 }
1010 status.lastSuccessTime = lastSyncTime;
1011 status.lastSuccessSource = item.source;
1012 status.lastFailureTime = 0;
1013 status.lastFailureSource = -1;
1014 status.lastFailureMesg = null;
1015 status.initialFailureTime = 0;
1016 ds.successCount++;
1017 ds.successTime += elapsedTime;
1018 } else if (!MESG_CANCELED.equals(resultMessage)) {
1019 if (status.lastFailureTime == 0) {
1020 writeStatusNow = true;
1021 }
1022 status.lastFailureTime = lastSyncTime;
1023 status.lastFailureSource = item.source;
1024 status.lastFailureMesg = resultMessage;
1025 if (status.initialFailureTime == 0) {
1026 status.initialFailureTime = lastSyncTime;
1027 }
1028 ds.failureCount++;
1029 ds.failureTime += elapsedTime;
1030 }
Costin Manolache360e4542009-09-04 13:36:04 -07001031
Dianne Hackborn231cc602009-04-27 17:10:36 -07001032 if (writeStatusNow) {
1033 writeStatusLocked();
1034 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1035 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1036 WRITE_STATUS_DELAY);
1037 }
1038 if (writeStatisticsNow) {
1039 writeStatisticsLocked();
1040 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1041 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1042 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001043 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001044 }
Costin Manolache360e4542009-09-04 13:36:04 -07001045
Fred Quintanaac9385e2009-06-22 18:00:59 -07001046 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001047 }
1048
1049 /**
1050 * Return the currently active sync information, or null if there is no
1051 * active sync. Note that the returned object is the real, live active
1052 * sync object, so be careful what you do with it.
1053 */
1054 public ActiveSyncInfo getActiveSync() {
1055 synchronized (mAuthorities) {
1056 return mActiveSync;
1057 }
1058 }
Costin Manolache360e4542009-09-04 13:36:04 -07001059
Dianne Hackborn231cc602009-04-27 17:10:36 -07001060 /**
1061 * Return an array of the current sync status for all authorities. Note
1062 * that the objects inside the array are the real, live status objects,
1063 * so be careful what you do with them.
1064 */
1065 public ArrayList<SyncStatusInfo> getSyncStatus() {
1066 synchronized (mAuthorities) {
1067 final int N = mSyncStatus.size();
1068 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1069 for (int i=0; i<N; i++) {
1070 ops.add(mSyncStatus.valueAt(i));
1071 }
1072 return ops;
1073 }
1074 }
Costin Manolache360e4542009-09-04 13:36:04 -07001075
Dianne Hackborn231cc602009-04-27 17:10:36 -07001076 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001077 * Return an array of the current authorities. Note
1078 * that the objects inside the array are the real, live objects,
1079 * so be careful what you do with them.
1080 */
1081 public ArrayList<AuthorityInfo> getAuthorities() {
1082 synchronized (mAuthorities) {
1083 final int N = mAuthorities.size();
1084 ArrayList<AuthorityInfo> infos = new ArrayList<AuthorityInfo>(N);
1085 for (int i=0; i<N; i++) {
1086 infos.add(mAuthorities.valueAt(i));
1087 }
1088 return infos;
1089 }
1090 }
1091
1092 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001093 * Returns the status that matches the authority and account.
1094 *
1095 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001096 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001097 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001098 */
Costin Manolacheb7520982009-09-02 18:03:05 -07001099 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, String authority) {
1100 if (account == null || authority == null) {
1101 throw new IllegalArgumentException();
1102 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001103 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001104 final int N = mSyncStatus.size();
1105 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001106 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001107 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001108
1109 if (ainfo != null && ainfo.authority.equals(authority) &&
1110 account.equals(ainfo.account)) {
1111 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001112 }
1113 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001114 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001115 }
1116 }
Costin Manolache360e4542009-09-04 13:36:04 -07001117
Dianne Hackborn231cc602009-04-27 17:10:36 -07001118 /**
1119 * Return true if the pending status is true of any matching authorities.
1120 */
Fred Quintanaac9385e2009-06-22 18:00:59 -07001121 public boolean isSyncPending(Account account, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001122 synchronized (mAuthorities) {
1123 final int N = mSyncStatus.size();
1124 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001125 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001126 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1127 if (ainfo == null) {
1128 continue;
1129 }
1130 if (account != null && !ainfo.account.equals(account)) {
1131 continue;
1132 }
1133 if (ainfo.authority.equals(authority) && cur.pending) {
1134 return true;
1135 }
1136 }
1137 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 }
1139 }
1140
1141 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001142 * Return an array of the current sync status for all authorities. Note
1143 * that the objects inside the array are the real, live status objects,
1144 * so be careful what you do with them.
1145 */
1146 public ArrayList<SyncHistoryItem> getSyncHistory() {
1147 synchronized (mAuthorities) {
1148 final int N = mSyncHistory.size();
1149 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1150 for (int i=0; i<N; i++) {
1151 items.add(mSyncHistory.get(i));
1152 }
1153 return items;
1154 }
1155 }
Costin Manolache360e4542009-09-04 13:36:04 -07001156
Dianne Hackborn231cc602009-04-27 17:10:36 -07001157 /**
1158 * Return an array of the current per-day statistics. Note
1159 * that the objects inside the array are the real, live status objects,
1160 * so be careful what you do with them.
1161 */
1162 public DayStats[] getDayStatistics() {
1163 synchronized (mAuthorities) {
1164 DayStats[] ds = new DayStats[mDayStats.length];
1165 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1166 return ds;
1167 }
1168 }
Costin Manolache360e4542009-09-04 13:36:04 -07001169
Dianne Hackborn231cc602009-04-27 17:10:36 -07001170 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 * If sync is failing for any of the provider/accounts then determine the time at which it
1172 * started failing and return the earliest time over all the provider/accounts. If none are
1173 * failing then return 0.
1174 */
1175 public long getInitialSyncFailureTime() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001176 synchronized (mAuthorities) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001177 if (!mMasterSyncAutomatically) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001178 return 0;
1179 }
Costin Manolache360e4542009-09-04 13:36:04 -07001180
Dianne Hackborn231cc602009-04-27 17:10:36 -07001181 long oldest = 0;
1182 int i = mSyncStatus.size();
1183 while (i > 0) {
1184 i--;
1185 SyncStatusInfo stats = mSyncStatus.valueAt(i);
1186 AuthorityInfo authority = mAuthorities.get(stats.authorityId);
1187 if (authority != null && authority.enabled) {
1188 if (oldest == 0 || stats.initialFailureTime < oldest) {
1189 oldest = stats.initialFailureTime;
1190 }
1191 }
1192 }
Costin Manolache360e4542009-09-04 13:36:04 -07001193
Dianne Hackborn231cc602009-04-27 17:10:36 -07001194 return oldest;
1195 }
1196 }
Costin Manolache360e4542009-09-04 13:36:04 -07001197
Dianne Hackborn55280a92009-05-07 15:53:46 -07001198 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001199 mCal.setTimeInMillis(System.currentTimeMillis());
1200 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1201 if (mYear != mCal.get(Calendar.YEAR)) {
1202 mYear = mCal.get(Calendar.YEAR);
1203 mCal.clear();
1204 mCal.set(Calendar.YEAR, mYear);
1205 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1206 }
1207 return dayOfYear + mYearInDays;
1208 }
Costin Manolache360e4542009-09-04 13:36:04 -07001209
Dianne Hackborn231cc602009-04-27 17:10:36 -07001210 /**
1211 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001212 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001213 * @param accountName The name of the account for the authority.
1214 * @param authorityName The name of the authority itself.
1215 * @param tag If non-null, this will be used in a log message if the
1216 * requested authority does not exist.
1217 */
Dianne Hackborn7a135592009-05-06 00:28:37 -07001218 private AuthorityInfo getAuthorityLocked(Account accountName, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001219 String tag) {
1220 AccountInfo account = mAccounts.get(accountName);
1221 if (account == null) {
1222 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001223 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1224 Log.v(TAG, tag + ": unknown account " + accountName);
1225 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001226 }
1227 return null;
1228 }
1229 AuthorityInfo authority = account.authorities.get(authorityName);
1230 if (authority == null) {
1231 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001232 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1233 Log.v(TAG, tag + ": unknown authority " + authorityName);
1234 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001235 }
1236 return null;
1237 }
Costin Manolache360e4542009-09-04 13:36:04 -07001238
Dianne Hackborn231cc602009-04-27 17:10:36 -07001239 return authority;
1240 }
Costin Manolache360e4542009-09-04 13:36:04 -07001241
Dianne Hackborn7a135592009-05-06 00:28:37 -07001242 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001243 String authorityName, int ident, boolean doWrite) {
1244 AccountInfo account = mAccounts.get(accountName);
1245 if (account == null) {
1246 account = new AccountInfo(accountName);
1247 mAccounts.put(accountName, account);
1248 }
1249 AuthorityInfo authority = account.authorities.get(authorityName);
1250 if (authority == null) {
1251 if (ident < 0) {
1252 // Look for a new identifier for this authority.
1253 final int N = mAuthorities.size();
1254 ident = 0;
1255 for (int i=0; i<N; i++) {
1256 if (mAuthorities.valueAt(i).ident > ident) {
1257 break;
1258 }
1259 ident++;
1260 }
1261 }
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -07001262 if (DEBUG) Log.v(TAG, "created a new AuthorityInfo for " + accountName
Fred Quintanab763ab22009-08-18 18:07:30 -07001263 + ", provider " + authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001264 authority = new AuthorityInfo(accountName, authorityName, ident);
1265 account.authorities.put(authorityName, authority);
1266 mAuthorities.put(ident, authority);
1267 if (doWrite) {
1268 writeAccountInfoLocked();
1269 }
1270 }
Costin Manolache360e4542009-09-04 13:36:04 -07001271
Dianne Hackborn231cc602009-04-27 17:10:36 -07001272 return authority;
1273 }
Costin Manolache360e4542009-09-04 13:36:04 -07001274
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001275 public SyncStatusInfo getOrCreateSyncStatus(AuthorityInfo authority) {
1276 synchronized (mAuthorities) {
1277 return getOrCreateSyncStatusLocked(authority.ident);
1278 }
1279 }
1280
Dianne Hackborn231cc602009-04-27 17:10:36 -07001281 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1282 SyncStatusInfo status = mSyncStatus.get(authorityId);
1283 if (status == null) {
1284 status = new SyncStatusInfo(authorityId);
1285 mSyncStatus.put(authorityId, status);
1286 }
1287 return status;
1288 }
Costin Manolache360e4542009-09-04 13:36:04 -07001289
Dianne Hackborn55280a92009-05-07 15:53:46 -07001290 public void writeAllState() {
1291 synchronized (mAuthorities) {
1292 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001293
Dianne Hackborn55280a92009-05-07 15:53:46 -07001294 if (mNumPendingFinished > 0) {
1295 // Only write these if they are out of date.
1296 writePendingOperationsLocked();
1297 }
Costin Manolache360e4542009-09-04 13:36:04 -07001298
Dianne Hackborn55280a92009-05-07 15:53:46 -07001299 // Just always write these... they are likely out of date.
1300 writeStatusLocked();
1301 writeStatisticsLocked();
1302 }
1303 }
Costin Manolache360e4542009-09-04 13:36:04 -07001304
Dianne Hackborn231cc602009-04-27 17:10:36 -07001305 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001306 * public for testing
1307 */
1308 public void clearAndReadState() {
1309 synchronized (mAuthorities) {
1310 mAuthorities.clear();
1311 mAccounts.clear();
1312 mPendingOperations.clear();
1313 mSyncStatus.clear();
1314 mSyncHistory.clear();
1315
1316 readAccountInfoLocked();
1317 readStatusLocked();
1318 readPendingOperationsLocked();
1319 readStatisticsLocked();
1320 readLegacyAccountInfoLocked();
1321 }
1322 }
1323
1324 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001325 * Read all account information back in to the initial engine state.
1326 */
1327 private void readAccountInfoLocked() {
Fred Quintanac2e46912010-03-15 16:10:44 -07001328 boolean writeNeeded = false;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001329 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001331 fis = mAccountInfoFile.openRead();
1332 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1333 XmlPullParser parser = Xml.newPullParser();
1334 parser.setInput(fis, null);
1335 int eventType = parser.getEventType();
1336 while (eventType != XmlPullParser.START_TAG) {
1337 eventType = parser.next();
1338 }
1339 String tagName = parser.getName();
1340 if ("accounts".equals(tagName)) {
1341 String listen = parser.getAttributeValue(
1342 null, "listen-for-tickles");
Fred Quintanac2e46912010-03-15 16:10:44 -07001343 String versionString = parser.getAttributeValue(null, "version");
1344 int version;
1345 try {
1346 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1347 } catch (NumberFormatException e) {
1348 version = 0;
1349 }
1350 if (version < ACCOUNTS_VERSION) {
1351 writeNeeded = true;
1352 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001353 mMasterSyncAutomatically = listen == null
Dianne Hackborn231cc602009-04-27 17:10:36 -07001354 || Boolean.parseBoolean(listen);
1355 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001356 AuthorityInfo authority = null;
1357 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001358 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001359 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001360 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001361 if (parser.getDepth() == 2) {
1362 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001363 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001364 periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001365 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001366 } else if (parser.getDepth() == 3) {
1367 if ("periodicSync".equals(tagName) && authority != null) {
1368 periodicSync = parsePeriodicSync(parser, authority);
1369 }
1370 } else if (parser.getDepth() == 4 && periodicSync != null) {
1371 if ("extra".equals(tagName)) {
1372 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001373 }
1374 }
1375 }
1376 eventType = parser.next();
1377 } while (eventType != XmlPullParser.END_DOCUMENT);
1378 }
1379 } catch (XmlPullParserException e) {
1380 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001381 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001382 } catch (java.io.IOException e) {
1383 if (fis == null) Log.i(TAG, "No initial accounts");
1384 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001385 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001386 } finally {
1387 if (fis != null) {
1388 try {
1389 fis.close();
1390 } catch (java.io.IOException e1) {
1391 }
1392 }
1393 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001394
1395 if (writeNeeded) {
1396 writeAccountInfoLocked();
1397 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001398 }
Costin Manolache360e4542009-09-04 13:36:04 -07001399
Fred Quintanac2e46912010-03-15 16:10:44 -07001400 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001401 AuthorityInfo authority = null;
1402 int id = -1;
1403 try {
1404 id = Integer.parseInt(parser.getAttributeValue(
1405 null, "id"));
1406 } catch (NumberFormatException e) {
1407 Log.e(TAG, "error parsing the id of the authority", e);
1408 } catch (NullPointerException e) {
1409 Log.e(TAG, "the id of the authority is null", e);
1410 }
1411 if (id >= 0) {
1412 String accountName = parser.getAttributeValue(null, "account");
1413 String accountType = parser.getAttributeValue(null, "type");
1414 if (accountType == null) {
1415 accountType = "com.google";
1416 }
1417 String authorityName = parser.getAttributeValue(null, "authority");
1418 String enabled = parser.getAttributeValue(null, "enabled");
1419 String syncable = parser.getAttributeValue(null, "syncable");
1420 authority = mAuthorities.get(id);
1421 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1422 + accountName + " auth=" + authorityName
1423 + " enabled=" + enabled
1424 + " syncable=" + syncable);
1425 if (authority == null) {
1426 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1427 authority = getOrCreateAuthorityLocked(
1428 new Account(accountName, accountType), authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001429 // If the version is 0 then we are upgrading from a file format that did not
1430 // know about periodic syncs. In that case don't clear the list since we
1431 // want the default, which is a daily periodioc sync.
1432 // Otherwise clear out this default list since we will populate it later with
1433 // the periodic sync descriptions that are read from the configuration file.
1434 if (version > 0) {
1435 authority.periodicSyncs.clear();
1436 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001437 }
1438 if (authority != null) {
1439 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1440 if ("unknown".equals(syncable)) {
1441 authority.syncable = -1;
1442 } else {
1443 authority.syncable =
1444 (syncable == null || Boolean.parseBoolean(enabled)) ? 1 : 0;
1445 }
1446 } else {
1447 Log.w(TAG, "Failure adding authority: account="
1448 + accountName + " auth=" + authorityName
1449 + " enabled=" + enabled
1450 + " syncable=" + syncable);
1451 }
1452 }
1453
1454 return authority;
1455 }
1456
1457 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1458 Bundle extras = new Bundle();
1459 String periodValue = parser.getAttributeValue(null, "period");
1460 final long period;
1461 try {
1462 period = Long.parseLong(periodValue);
1463 } catch (NumberFormatException e) {
1464 Log.e(TAG, "error parsing the period of a periodic sync", e);
1465 return null;
1466 } catch (NullPointerException e) {
1467 Log.e(TAG, "the period of a periodic sync is null", e);
1468 return null;
1469 }
1470 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1471 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001472
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001473 return periodicSync;
1474 }
1475
1476 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1477 final Bundle extras = periodicSync.first;
1478 String name = parser.getAttributeValue(null, "name");
1479 String type = parser.getAttributeValue(null, "type");
1480 String value1 = parser.getAttributeValue(null, "value1");
1481 String value2 = parser.getAttributeValue(null, "value2");
1482
1483 try {
1484 if ("long".equals(type)) {
1485 extras.putLong(name, Long.parseLong(value1));
1486 } else if ("integer".equals(type)) {
1487 extras.putInt(name, Integer.parseInt(value1));
1488 } else if ("double".equals(type)) {
1489 extras.putDouble(name, Double.parseDouble(value1));
1490 } else if ("float".equals(type)) {
1491 extras.putFloat(name, Float.parseFloat(value1));
1492 } else if ("boolean".equals(type)) {
1493 extras.putBoolean(name, Boolean.parseBoolean(value1));
1494 } else if ("string".equals(type)) {
1495 extras.putString(name, value1);
1496 } else if ("account".equals(type)) {
1497 extras.putParcelable(name, new Account(value1, value2));
1498 }
1499 } catch (NumberFormatException e) {
1500 Log.e(TAG, "error parsing bundle value", e);
1501 } catch (NullPointerException e) {
1502 Log.e(TAG, "error parsing bundle value", e);
1503 }
1504 }
1505
Dianne Hackborn231cc602009-04-27 17:10:36 -07001506 /**
1507 * Write all account information to the account file.
1508 */
1509 private void writeAccountInfoLocked() {
1510 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1511 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001512
Dianne Hackborn231cc602009-04-27 17:10:36 -07001513 try {
1514 fos = mAccountInfoFile.startWrite();
1515 XmlSerializer out = new FastXmlSerializer();
1516 out.setOutput(fos, "utf-8");
1517 out.startDocument(null, true);
1518 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001519
Dianne Hackborn231cc602009-04-27 17:10:36 -07001520 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001521 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Fred Quintanaac9385e2009-06-22 18:00:59 -07001522 if (!mMasterSyncAutomatically) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001523 out.attribute(null, "listen-for-tickles", "false");
1524 }
Costin Manolache360e4542009-09-04 13:36:04 -07001525
Dianne Hackborn231cc602009-04-27 17:10:36 -07001526 final int N = mAuthorities.size();
1527 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001528 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001529 out.startTag(null, "authority");
1530 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001531 out.attribute(null, "account", authority.account.name);
1532 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001533 out.attribute(null, "authority", authority.authority);
1534 if (!authority.enabled) {
1535 out.attribute(null, "enabled", "false");
Fred Quintanac2e46912010-03-15 16:10:44 -07001536 }
Fred Quintana5e787c42009-08-16 23:13:53 -07001537 if (authority.syncable < 0) {
1538 out.attribute(null, "syncable", "unknown");
1539 } else if (authority.syncable == 0) {
1540 out.attribute(null, "syncable", "false");
1541 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001542 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1543 out.startTag(null, "periodicSync");
1544 out.attribute(null, "period", Long.toString(periodicSync.second));
1545 final Bundle extras = periodicSync.first;
1546 for (String key : extras.keySet()) {
1547 out.startTag(null, "extra");
1548 out.attribute(null, "name", key);
1549 final Object value = extras.get(key);
1550 if (value instanceof Long) {
1551 out.attribute(null, "type", "long");
1552 out.attribute(null, "value1", value.toString());
1553 } else if (value instanceof Integer) {
1554 out.attribute(null, "type", "integer");
1555 out.attribute(null, "value1", value.toString());
1556 } else if (value instanceof Boolean) {
1557 out.attribute(null, "type", "boolean");
1558 out.attribute(null, "value1", value.toString());
1559 } else if (value instanceof Float) {
1560 out.attribute(null, "type", "float");
1561 out.attribute(null, "value1", value.toString());
1562 } else if (value instanceof Double) {
1563 out.attribute(null, "type", "double");
1564 out.attribute(null, "value1", value.toString());
1565 } else if (value instanceof String) {
1566 out.attribute(null, "type", "string");
1567 out.attribute(null, "value1", value.toString());
1568 } else if (value instanceof Account) {
1569 out.attribute(null, "type", "account");
1570 out.attribute(null, "value1", ((Account)value).name);
1571 out.attribute(null, "value2", ((Account)value).type);
1572 }
1573 out.endTag(null, "extra");
1574 }
1575 out.endTag(null, "periodicSync");
1576 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001577 out.endTag(null, "authority");
1578 }
Costin Manolache360e4542009-09-04 13:36:04 -07001579
Dianne Hackborn231cc602009-04-27 17:10:36 -07001580 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001581
Dianne Hackborn231cc602009-04-27 17:10:36 -07001582 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001583
Dianne Hackborn231cc602009-04-27 17:10:36 -07001584 mAccountInfoFile.finishWrite(fos);
1585 } catch (java.io.IOException e1) {
1586 Log.w(TAG, "Error writing accounts", e1);
1587 if (fos != null) {
1588 mAccountInfoFile.failWrite(fos);
1589 }
1590 }
1591 }
Costin Manolache360e4542009-09-04 13:36:04 -07001592
Dianne Hackborn231cc602009-04-27 17:10:36 -07001593 static int getIntColumn(Cursor c, String name) {
1594 return c.getInt(c.getColumnIndex(name));
1595 }
Costin Manolache360e4542009-09-04 13:36:04 -07001596
Dianne Hackborn231cc602009-04-27 17:10:36 -07001597 static long getLongColumn(Cursor c, String name) {
1598 return c.getLong(c.getColumnIndex(name));
1599 }
Costin Manolache360e4542009-09-04 13:36:04 -07001600
Dianne Hackborn231cc602009-04-27 17:10:36 -07001601 /**
1602 * Load sync engine state from the old syncmanager database, and then
1603 * erase it. Note that we don't deal with pending operations, active
1604 * sync, or history.
1605 */
1606 private void readLegacyAccountInfoLocked() {
1607 // Look for old database to initialize from.
1608 File file = mContext.getDatabasePath("syncmanager.db");
1609 if (!file.exists()) {
1610 return;
1611 }
1612 String path = file.getPath();
1613 SQLiteDatabase db = null;
1614 try {
1615 db = SQLiteDatabase.openDatabase(path, null,
1616 SQLiteDatabase.OPEN_READONLY);
1617 } catch (SQLiteException e) {
1618 }
Costin Manolache360e4542009-09-04 13:36:04 -07001619
Dianne Hackborn231cc602009-04-27 17:10:36 -07001620 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001621 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001622
Dianne Hackborn231cc602009-04-27 17:10:36 -07001623 // Copy in all of the status information, as well as accounts.
1624 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1625 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1626 qb.setTables("stats, status");
1627 HashMap<String,String> map = new HashMap<String,String>();
1628 map.put("_id", "status._id as _id");
1629 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001630 if (hasType) {
1631 map.put("account_type", "stats.account_type as account_type");
1632 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001633 map.put("authority", "stats.authority as authority");
1634 map.put("totalElapsedTime", "totalElapsedTime");
1635 map.put("numSyncs", "numSyncs");
1636 map.put("numSourceLocal", "numSourceLocal");
1637 map.put("numSourcePoll", "numSourcePoll");
1638 map.put("numSourceServer", "numSourceServer");
1639 map.put("numSourceUser", "numSourceUser");
1640 map.put("lastSuccessSource", "lastSuccessSource");
1641 map.put("lastSuccessTime", "lastSuccessTime");
1642 map.put("lastFailureSource", "lastFailureSource");
1643 map.put("lastFailureTime", "lastFailureTime");
1644 map.put("lastFailureMesg", "lastFailureMesg");
1645 map.put("pending", "pending");
1646 qb.setProjectionMap(map);
1647 qb.appendWhere("stats._id = status.stats_id");
1648 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001650 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001651 String accountType = hasType
1652 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001653 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001654 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001656 String authorityName = c.getString(c.getColumnIndex("authority"));
1657 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Dianne Hackborn7a135592009-05-06 00:28:37 -07001658 new Account(accountName, accountType),
1659 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001660 if (authority != null) {
1661 int i = mSyncStatus.size();
1662 boolean found = false;
1663 SyncStatusInfo st = null;
1664 while (i > 0) {
1665 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001666 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001667 if (st.authorityId == authority.ident) {
1668 found = true;
1669 break;
1670 }
1671 }
1672 if (!found) {
1673 st = new SyncStatusInfo(authority.ident);
1674 mSyncStatus.put(authority.ident, st);
1675 }
1676 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1677 st.numSyncs = getIntColumn(c, "numSyncs");
1678 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1679 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1680 st.numSourceServer = getIntColumn(c, "numSourceServer");
1681 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001682 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001683 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1684 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1685 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1686 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1687 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1688 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 }
Costin Manolache360e4542009-09-04 13:36:04 -07001691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001693
Dianne Hackborn231cc602009-04-27 17:10:36 -07001694 // Retrieve the settings.
1695 qb = new SQLiteQueryBuilder();
1696 qb.setTables("settings");
1697 c = qb.query(db, null, null, null, null, null, null);
1698 while (c.moveToNext()) {
1699 String name = c.getString(c.getColumnIndex("name"));
1700 String value = c.getString(c.getColumnIndex("value"));
1701 if (name == null) continue;
1702 if (name.equals("listen_for_tickles")) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001703 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001704 } else if (name.startsWith("sync_provider_")) {
1705 String provider = name.substring("sync_provider_".length(),
1706 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001707 int i = mAuthorities.size();
1708 while (i > 0) {
1709 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001710 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001711 if (authority.authority.equals(provider)) {
1712 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001713 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001714 }
1715 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 }
Costin Manolache360e4542009-09-04 13:36:04 -07001718
Dianne Hackborn231cc602009-04-27 17:10:36 -07001719 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001720
Dianne Hackborn231cc602009-04-27 17:10:36 -07001721 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001722
Dianne Hackborn231cc602009-04-27 17:10:36 -07001723 writeAccountInfoLocked();
1724 writeStatusLocked();
1725 (new File(path)).delete();
1726 }
1727 }
Costin Manolache360e4542009-09-04 13:36:04 -07001728
Dianne Hackborn231cc602009-04-27 17:10:36 -07001729 public static final int STATUS_FILE_END = 0;
1730 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001731
Dianne Hackborn231cc602009-04-27 17:10:36 -07001732 /**
1733 * Read all sync status back in to the initial engine state.
1734 */
1735 private void readStatusLocked() {
1736 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
1737 try {
1738 byte[] data = mStatusFile.readFully();
1739 Parcel in = Parcel.obtain();
1740 in.unmarshall(data, 0, data.length);
1741 in.setDataPosition(0);
1742 int token;
1743 while ((token=in.readInt()) != STATUS_FILE_END) {
1744 if (token == STATUS_FILE_ITEM) {
1745 SyncStatusInfo status = new SyncStatusInfo(in);
1746 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1747 status.pending = false;
1748 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
1749 + status.authorityId);
1750 mSyncStatus.put(status.authorityId, status);
1751 }
1752 } else {
1753 // Ooops.
1754 Log.w(TAG, "Unknown status token: " + token);
1755 break;
1756 }
1757 }
1758 } catch (java.io.IOException e) {
1759 Log.i(TAG, "No initial status");
1760 }
1761 }
Costin Manolache360e4542009-09-04 13:36:04 -07001762
Dianne Hackborn231cc602009-04-27 17:10:36 -07001763 /**
1764 * Write all sync status to the sync status file.
1765 */
1766 private void writeStatusLocked() {
1767 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07001768
Dianne Hackborn231cc602009-04-27 17:10:36 -07001769 // The file is being written, so we don't need to have a scheduled
1770 // write until the next change.
1771 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07001772
Dianne Hackborn231cc602009-04-27 17:10:36 -07001773 FileOutputStream fos = null;
1774 try {
1775 fos = mStatusFile.startWrite();
1776 Parcel out = Parcel.obtain();
1777 final int N = mSyncStatus.size();
1778 for (int i=0; i<N; i++) {
1779 SyncStatusInfo status = mSyncStatus.valueAt(i);
1780 out.writeInt(STATUS_FILE_ITEM);
1781 status.writeToParcel(out, 0);
1782 }
1783 out.writeInt(STATUS_FILE_END);
1784 fos.write(out.marshall());
1785 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07001786
Dianne Hackborn231cc602009-04-27 17:10:36 -07001787 mStatusFile.finishWrite(fos);
1788 } catch (java.io.IOException e1) {
1789 Log.w(TAG, "Error writing status", e1);
1790 if (fos != null) {
1791 mStatusFile.failWrite(fos);
1792 }
1793 }
1794 }
Costin Manolache360e4542009-09-04 13:36:04 -07001795
Fred Quintana307da1a2010-01-21 14:24:20 -08001796 public static final int PENDING_OPERATION_VERSION = 2;
Costin Manolache360e4542009-09-04 13:36:04 -07001797
Dianne Hackborn231cc602009-04-27 17:10:36 -07001798 /**
1799 * Read all pending operations back in to the initial engine state.
1800 */
1801 private void readPendingOperationsLocked() {
1802 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
1803 try {
1804 byte[] data = mPendingFile.readFully();
1805 Parcel in = Parcel.obtain();
1806 in.unmarshall(data, 0, data.length);
1807 in.setDataPosition(0);
1808 final int SIZE = in.dataSize();
1809 while (in.dataPosition() < SIZE) {
1810 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08001811 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001812 Log.w(TAG, "Unknown pending operation version "
1813 + version + "; dropping all ops");
1814 break;
1815 }
1816 int authorityId = in.readInt();
1817 int syncSource = in.readInt();
1818 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08001819 boolean expedited;
1820 if (version == PENDING_OPERATION_VERSION) {
1821 expedited = in.readInt() != 0;
1822 } else {
1823 expedited = false;
1824 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001825 AuthorityInfo authority = mAuthorities.get(authorityId);
1826 if (authority != null) {
1827 Bundle extras = null;
1828 if (flatExtras != null) {
1829 extras = unflattenBundle(flatExtras);
1830 }
1831 PendingOperation op = new PendingOperation(
1832 authority.account, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08001833 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001834 op.authorityId = authorityId;
1835 op.flatExtras = flatExtras;
1836 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
1837 + " auth=" + op.authority
1838 + " src=" + op.syncSource
Fred Quintana307da1a2010-01-21 14:24:20 -08001839 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07001840 + " extras=" + op.extras);
1841 mPendingOperations.add(op);
1842 }
1843 }
1844 } catch (java.io.IOException e) {
1845 Log.i(TAG, "No initial pending operations");
1846 }
1847 }
Costin Manolache360e4542009-09-04 13:36:04 -07001848
Dianne Hackborn231cc602009-04-27 17:10:36 -07001849 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
1850 out.writeInt(PENDING_OPERATION_VERSION);
1851 out.writeInt(op.authorityId);
1852 out.writeInt(op.syncSource);
1853 if (op.flatExtras == null && op.extras != null) {
1854 op.flatExtras = flattenBundle(op.extras);
1855 }
1856 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08001857 out.writeInt(op.expedited ? 1 : 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001858 }
Costin Manolache360e4542009-09-04 13:36:04 -07001859
Dianne Hackborn231cc602009-04-27 17:10:36 -07001860 /**
1861 * Write all currently pending ops to the pending ops file.
1862 */
1863 private void writePendingOperationsLocked() {
1864 final int N = mPendingOperations.size();
1865 FileOutputStream fos = null;
1866 try {
1867 if (N == 0) {
1868 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
1869 mPendingFile.truncate();
1870 return;
1871 }
Costin Manolache360e4542009-09-04 13:36:04 -07001872
Dianne Hackborn231cc602009-04-27 17:10:36 -07001873 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
1874 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07001875
Dianne Hackborn231cc602009-04-27 17:10:36 -07001876 Parcel out = Parcel.obtain();
1877 for (int i=0; i<N; i++) {
1878 PendingOperation op = mPendingOperations.get(i);
1879 writePendingOperationLocked(op, out);
1880 }
1881 fos.write(out.marshall());
1882 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07001883
Dianne Hackborn231cc602009-04-27 17:10:36 -07001884 mPendingFile.finishWrite(fos);
1885 } catch (java.io.IOException e1) {
1886 Log.w(TAG, "Error writing pending operations", e1);
1887 if (fos != null) {
1888 mPendingFile.failWrite(fos);
1889 }
1890 }
1891 }
Costin Manolache360e4542009-09-04 13:36:04 -07001892
Dianne Hackborn231cc602009-04-27 17:10:36 -07001893 /**
1894 * Append the given operation to the pending ops file; if unable to,
1895 * write all pending ops.
1896 */
1897 private void appendPendingOperationLocked(PendingOperation op) {
1898 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
1899 FileOutputStream fos = null;
1900 try {
1901 fos = mPendingFile.openAppend();
1902 } catch (java.io.IOException e) {
1903 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
1904 writePendingOperationsLocked();
1905 return;
1906 }
Costin Manolache360e4542009-09-04 13:36:04 -07001907
Dianne Hackborn231cc602009-04-27 17:10:36 -07001908 try {
1909 Parcel out = Parcel.obtain();
1910 writePendingOperationLocked(op, out);
1911 fos.write(out.marshall());
1912 out.recycle();
1913 } catch (java.io.IOException e1) {
1914 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001916 try {
1917 fos.close();
1918 } catch (java.io.IOException e2) {
1919 }
1920 }
1921 }
Costin Manolache360e4542009-09-04 13:36:04 -07001922
Dianne Hackborn231cc602009-04-27 17:10:36 -07001923 static private byte[] flattenBundle(Bundle bundle) {
1924 byte[] flatData = null;
1925 Parcel parcel = Parcel.obtain();
1926 try {
1927 bundle.writeToParcel(parcel, 0);
1928 flatData = parcel.marshall();
1929 } finally {
1930 parcel.recycle();
1931 }
1932 return flatData;
1933 }
Costin Manolache360e4542009-09-04 13:36:04 -07001934
Dianne Hackborn231cc602009-04-27 17:10:36 -07001935 static private Bundle unflattenBundle(byte[] flatData) {
1936 Bundle bundle;
1937 Parcel parcel = Parcel.obtain();
1938 try {
1939 parcel.unmarshall(flatData, 0, flatData.length);
1940 parcel.setDataPosition(0);
1941 bundle = parcel.readBundle();
1942 } catch (RuntimeException e) {
1943 // A RuntimeException is thrown if we were unable to parse the parcel.
1944 // Create an empty parcel in this case.
1945 bundle = new Bundle();
1946 } finally {
1947 parcel.recycle();
1948 }
1949 return bundle;
1950 }
Costin Manolache360e4542009-09-04 13:36:04 -07001951
Dianne Hackborn231cc602009-04-27 17:10:36 -07001952 public static final int STATISTICS_FILE_END = 0;
1953 public static final int STATISTICS_FILE_ITEM_OLD = 100;
1954 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07001955
Dianne Hackborn231cc602009-04-27 17:10:36 -07001956 /**
1957 * Read all sync statistics back in to the initial engine state.
1958 */
1959 private void readStatisticsLocked() {
1960 try {
1961 byte[] data = mStatisticsFile.readFully();
1962 Parcel in = Parcel.obtain();
1963 in.unmarshall(data, 0, data.length);
1964 in.setDataPosition(0);
1965 int token;
1966 int index = 0;
1967 while ((token=in.readInt()) != STATISTICS_FILE_END) {
1968 if (token == STATISTICS_FILE_ITEM
1969 || token == STATISTICS_FILE_ITEM_OLD) {
1970 int day = in.readInt();
1971 if (token == STATISTICS_FILE_ITEM_OLD) {
1972 day = day - 2009 + 14245; // Magic!
1973 }
1974 DayStats ds = new DayStats(day);
1975 ds.successCount = in.readInt();
1976 ds.successTime = in.readLong();
1977 ds.failureCount = in.readInt();
1978 ds.failureTime = in.readLong();
1979 if (index < mDayStats.length) {
1980 mDayStats[index] = ds;
1981 index++;
1982 }
1983 } else {
1984 // Ooops.
1985 Log.w(TAG, "Unknown stats token: " + token);
1986 break;
1987 }
1988 }
1989 } catch (java.io.IOException e) {
1990 Log.i(TAG, "No initial statistics");
1991 }
1992 }
Costin Manolache360e4542009-09-04 13:36:04 -07001993
Dianne Hackborn231cc602009-04-27 17:10:36 -07001994 /**
1995 * Write all sync statistics to the sync status file.
1996 */
1997 private void writeStatisticsLocked() {
1998 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07001999
Dianne Hackborn231cc602009-04-27 17:10:36 -07002000 // The file is being written, so we don't need to have a scheduled
2001 // write until the next change.
2002 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002003
Dianne Hackborn231cc602009-04-27 17:10:36 -07002004 FileOutputStream fos = null;
2005 try {
2006 fos = mStatisticsFile.startWrite();
2007 Parcel out = Parcel.obtain();
2008 final int N = mDayStats.length;
2009 for (int i=0; i<N; i++) {
2010 DayStats ds = mDayStats[i];
2011 if (ds == null) {
2012 break;
2013 }
2014 out.writeInt(STATISTICS_FILE_ITEM);
2015 out.writeInt(ds.day);
2016 out.writeInt(ds.successCount);
2017 out.writeLong(ds.successTime);
2018 out.writeInt(ds.failureCount);
2019 out.writeLong(ds.failureTime);
2020 }
2021 out.writeInt(STATISTICS_FILE_END);
2022 fos.write(out.marshall());
2023 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002024
Dianne Hackborn231cc602009-04-27 17:10:36 -07002025 mStatisticsFile.finishWrite(fos);
2026 } catch (java.io.IOException e1) {
2027 Log.w(TAG, "Error writing stats", e1);
2028 if (fos != null) {
2029 mStatisticsFile.failWrite(fos);
2030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 }
2032 }
2033}