blob: f843a62fd490b63d5756425c8deb6b4770804ea2 [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
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Matthew Williamsfa774182013-06-18 15:44:11 -070021import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080022import android.content.ContentResolver;
23import android.content.Context;
24import android.content.ISyncStatusObserver;
25import android.content.PeriodicSync;
26import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070027import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080028import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070031import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070033import android.os.Bundle;
34import android.os.Environment;
35import android.os.Handler;
36import android.os.Message;
37import android.os.Parcel;
38import android.os.RemoteCallbackList;
39import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070040import android.os.UserHandle;
Dianne Hackborn39606a02012-07-31 17:54:35 -070041import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.util.Log;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080043import android.util.Pair;
Dianne Hackborn231cc602009-04-27 17:10:36 -070044import android.util.SparseArray;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070045import android.util.ArrayMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070046import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080047
48import com.android.internal.annotations.VisibleForTesting;
49import com.android.internal.util.ArrayUtils;
50import com.android.internal.util.FastXmlSerializer;
51
52import org.xmlpull.v1.XmlPullParser;
53import org.xmlpull.v1.XmlPullParserException;
54import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
Dianne Hackborn231cc602009-04-27 17:10:36 -070056import java.io.File;
57import java.io.FileInputStream;
58import java.io.FileOutputStream;
Matthew Williamsba352712013-08-13 15:53:31 -070059import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070061import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070063import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080064import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070065import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060066import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
68/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070069 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070071 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 * @hide
73 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070074public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070077 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070078
Amith Yamasani04e0d262012-02-14 11:50:53 -080079 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
80 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070081 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080082 private static final String XML_ATTR_ENABLED = "enabled";
83 private static final String XML_ATTR_USER = "user";
84 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
85
Matthew Williamsfa774182013-06-18 15:44:11 -070086 /** Default time for a periodic sync. */
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080087 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
88
Matthew Williamsfa774182013-06-18 15:44:11 -070089 /** Percentage of period that is flex by default, if no flex is set. */
90 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
91
92 /** Lower bound on sync time from which we assign a default flex time. */
93 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
94
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080095 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070096 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
Dianne Hackborn231cc602009-04-27 17:10:36 -070098 /** Enum value for a sync start event. */
99 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Dianne Hackborn231cc602009-04-27 17:10:36 -0700101 /** Enum value for a sync stop event. */
102 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103
Dianne Hackborn231cc602009-04-27 17:10:36 -0700104 // TODO: i18n -- grab these out of resources.
105 /** String names for the sync event types. */
106 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Dianne Hackborn231cc602009-04-27 17:10:36 -0700108 /** Enum value for a server-initiated sync. */
109 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Dianne Hackborn231cc602009-04-27 17:10:36 -0700111 /** Enum value for a local-initiated sync. */
112 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700113 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700114 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Dianne Hackborn231cc602009-04-27 17:10:36 -0700116 /** Enum value for a user-initiated sync. */
117 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800119 /** Enum value for a periodic sync. */
120 public static final int SOURCE_PERIODIC = 4;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700121
122 /** Enum value for a sync started for a service. */
123 public static final int SOURCE_SERVICE = 5;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800124
Fred Quintana307da1a2010-01-21 14:24:20 -0800125 public static final long NOT_IN_BACKOFF_MODE = -1;
126
Dianne Hackborn231cc602009-04-27 17:10:36 -0700127 // TODO: i18n -- grab these out of resources.
128 /** String names for the sync source types. */
129 public static final String[] SOURCES = { "SERVER",
130 "LOCAL",
131 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800132 "USER",
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700133 "PERIODIC",
134 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
Dianne Hackborn231cc602009-04-27 17:10:36 -0700136 // The MESG column will contain one of these or one of the Error types.
137 public static final String MESG_SUCCESS = "success";
138 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700140 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700141
Dianne Hackborn231cc602009-04-27 17:10:36 -0700142 private static final int MSG_WRITE_STATUS = 1;
143 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700144
Dianne Hackborn231cc602009-04-27 17:10:36 -0700145 private static final int MSG_WRITE_STATISTICS = 2;
146 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700147
148 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700149
Fred Quintanac2e46912010-03-15 16:10:44 -0700150 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700151 private static final int ACCOUNTS_VERSION = 2;
152
153 private static HashMap<String, String> sAuthorityRenames;
154
155 static {
156 sAuthorityRenames = new HashMap<String, String>();
157 sAuthorityRenames.put("contacts", "com.android.contacts");
158 sAuthorityRenames.put("calendar", "com.android.calendar");
159 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700160
Dianne Hackborn231cc602009-04-27 17:10:36 -0700161 public static class PendingOperation {
Matthew Williams8ef22042013-07-26 12:56:39 -0700162 final EndPoint target;
Alon Albert57286f92012-10-09 14:21:38 -0700163 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700164 final int syncSource;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700165 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800166 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700167
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700168 final int authorityId;
169 // No longer used.
170 // Keep around for sake up updating from pending.bin to pending.xml
Dianne Hackborn231cc602009-04-27 17:10:36 -0700171 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700172
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700173 PendingOperation(AuthorityInfo authority, int reason, int source,
174 Bundle extras, boolean expedited) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700175 this.target = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700176 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700177 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700178 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800179 this.expedited = expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700180 this.authorityId = authority.ident;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700181 }
182
183 PendingOperation(PendingOperation other) {
Alon Albert57286f92012-10-09 14:21:38 -0700184 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700185 this.syncSource = other.syncSource;
Matthew Williams8ef22042013-07-26 12:56:39 -0700186 this.target = other.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700187 this.extras = other.extras;
188 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800189 this.expedited = other.expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700190 }
191
192 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700193 * Considered equal if they target the same sync adapter (A
194 * {@link android.content.SyncService}
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700195 * is considered an adapter), for the same userId.
196 * @param other PendingOperation to compare.
197 * @return true if the two pending ops are the same.
198 */
199 public boolean equals(PendingOperation other) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700200 return target.matchesSpec(other.target);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700201 }
202
203 public String toString() {
Matthew Williams8ef22042013-07-26 12:56:39 -0700204 return "service=" + target.service
205 + " user=" + target.userId
206 + " auth=" + target
207 + " account=" + target.account
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700208 + " src=" + syncSource
209 + " extras=" + extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 }
Costin Manolache360e4542009-09-04 13:36:04 -0700212
Dianne Hackborn231cc602009-04-27 17:10:36 -0700213 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800214 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700215 final HashMap<String, AuthorityInfo> authorities =
216 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700217
Amith Yamasani04e0d262012-02-14 11:50:53 -0800218 AccountInfo(AccountAndUser accountAndUser) {
219 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700220 }
221 }
Costin Manolache360e4542009-09-04 13:36:04 -0700222
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700223 /** Bare bones representation of a sync target. */
224 public static class EndPoint {
225 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
226 new EndPoint(null, null, UserHandle.USER_ALL);
Matthew Williamsfa774182013-06-18 15:44:11 -0700227 final ComponentName service;
Dianne Hackborn7a135592009-05-06 00:28:37 -0700228 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800229 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700230 final String provider;
231 final boolean target_service;
232 final boolean target_provider;
233
234 public EndPoint(ComponentName service, int userId) {
235 this.service = service;
236 this.userId = userId;
237 this.account = null;
238 this.provider = null;
239 this.target_service = true;
240 this.target_provider = false;
241 }
242
243 public EndPoint(Account account, String provider, int userId) {
244 this.account = account;
245 this.provider = provider;
246 this.userId = userId;
247 this.service = null;
248 this.target_service = false;
249 this.target_provider = true;
250 }
251
252 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700253 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
254 *
255 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
256 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700257 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700258 public boolean matchesSpec(EndPoint spec) {
259 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700260 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700261 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700262 return false;
263 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700264 if (target_service && spec.target_service) {
265 return service.equals(spec.service);
266 } else if (target_provider && spec.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700267 boolean accountsMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700268 if (spec.account == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700269 accountsMatch = true;
270 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700271 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700272 }
273 boolean providersMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700274 if (spec.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700275 providersMatch = true;
276 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700277 providersMatch = provider.equals(spec.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700278 }
279 return accountsMatch && providersMatch;
280 }
281 return false;
282 }
283
284 public String toString() {
285 StringBuilder sb = new StringBuilder();
286 if (target_provider) {
287 sb.append(account == null ? "ALL ACCS" : account.name)
288 .append("/")
289 .append(provider == null ? "ALL PDRS" : provider);
290 } else if (target_service) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700291 sb.append(service.getPackageName() + "/")
292 .append(service.getClassName());
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700293 } else {
294 sb.append("invalid target");
295 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700296 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700297 return sb.toString();
298 }
299 }
300
301 public static class AuthorityInfo {
Matthew Williams8ef22042013-07-26 12:56:39 -0700302 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700303 final int ident;
304 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700305 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700306 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800307 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700308 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800309 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700310 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800311 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700312
Matthew Williamsfa774182013-06-18 15:44:11 -0700313 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700314
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700315 /**
316 * Copy constructor for making deep-ish copies. Only the bundles stored
317 * in periodic syncs can make unexpected changes.
318 *
319 * @param toCopy AuthorityInfo to be copied.
320 */
321 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700322 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700323 ident = toCopy.ident;
324 enabled = toCopy.enabled;
325 syncable = toCopy.syncable;
326 backoffTime = toCopy.backoffTime;
327 backoffDelay = toCopy.backoffDelay;
328 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700329 periodicSyncs = new ArrayList<PeriodicSync>();
330 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700331 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700332 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700333 }
334 }
335
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700336 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700337 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700338 ident = id;
339 enabled = info.target_provider ?
340 SYNC_ENABLED_DEFAULT : true;
341 // Service is active by default,
342 if (info.target_service) {
343 this.syncable = 1;
344 }
345 periodicSyncs = new ArrayList<PeriodicSync>();
346 defaultInitialisation();
347 }
348
349 private void defaultInitialisation() {
Fred Quintana4a6679b2009-08-17 13:05:39 -0700350 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800351 backoffTime = -1; // if < 0 then we aren't in backoff mode
352 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700353 PeriodicSync defaultSync;
354 // Old version is one sync a day. Empty bundle gets replaced by any addPeriodicSync()
355 // call.
Matthew Williams8ef22042013-07-26 12:56:39 -0700356 if (target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700357 defaultSync =
Matthew Williams8ef22042013-07-26 12:56:39 -0700358 new PeriodicSync(target.account, target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700359 new Bundle(),
360 DEFAULT_POLL_FREQUENCY_SECONDS,
361 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
362 periodicSyncs.add(defaultSync);
363 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700364 }
365 }
Costin Manolache360e4542009-09-04 13:36:04 -0700366
Dianne Hackborn231cc602009-04-27 17:10:36 -0700367 public static class SyncHistoryItem {
368 int authorityId;
369 int historyId;
370 long eventTime;
371 long elapsedTime;
372 int source;
373 int event;
374 long upstreamActivity;
375 long downstreamActivity;
376 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700377 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700378 Bundle extras;
379 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700380 }
Costin Manolache360e4542009-09-04 13:36:04 -0700381
Dianne Hackborn231cc602009-04-27 17:10:36 -0700382 public static class DayStats {
383 public final int day;
384 public int successCount;
385 public long successTime;
386 public int failureCount;
387 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700388
Dianne Hackborn231cc602009-04-27 17:10:36 -0700389 public DayStats(int day) {
390 this.day = day;
391 }
392 }
Costin Manolache360e4542009-09-04 13:36:04 -0700393
Amith Yamasani04e0d262012-02-14 11:50:53 -0800394 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700395
396 /** Called when a sync is needed on an account(s) due to some change in state. */
397 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800398 }
399
Dianne Hackborn231cc602009-04-27 17:10:36 -0700400 // Primary list of all syncable authorities. Also our global lock.
401 private final SparseArray<AuthorityInfo> mAuthorities =
402 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700403
Amith Yamasani04e0d262012-02-14 11:50:53 -0800404 private final HashMap<AccountAndUser, AccountInfo> mAccounts
405 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406
Dianne Hackborn231cc602009-04-27 17:10:36 -0700407 private final ArrayList<PendingOperation> mPendingOperations =
408 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700409
Amith Yamasani04e0d262012-02-14 11:50:53 -0800410 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
411 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700412
Dianne Hackborn231cc602009-04-27 17:10:36 -0700413 private final SparseArray<SyncStatusInfo> mSyncStatus =
414 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700415
Dianne Hackborn231cc602009-04-27 17:10:36 -0700416 private final ArrayList<SyncHistoryItem> mSyncHistory =
417 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700418
Dianne Hackborn231cc602009-04-27 17:10:36 -0700419 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
420 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700421
Matthew Williams8ef22042013-07-26 12:56:39 -0700422 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700423 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
424 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700425
Fred Quintana77c560f2010-03-29 22:20:26 -0700426 private int mNextAuthorityId = 0;
427
Dianne Hackborn231cc602009-04-27 17:10:36 -0700428 // We keep 4 weeks of stats.
429 private final DayStats[] mDayStats = new DayStats[7*4];
430 private final Calendar mCal;
431 private int mYear;
432 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700433
Dianne Hackborn231cc602009-04-27 17:10:36 -0700434 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800435
Dianne Hackborn231cc602009-04-27 17:10:36 -0700436 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700437
Ashish Sharma69d95de2012-04-11 17:27:24 -0700438 private int mSyncRandomOffset;
439
Dianne Hackborn231cc602009-04-27 17:10:36 -0700440 /**
441 * This file contains the core engine state: all accounts and the
442 * settings for them. It must never be lost, and should be changed
443 * infrequently, so it is stored as an XML file.
444 */
445 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700446
Dianne Hackborn231cc602009-04-27 17:10:36 -0700447 /**
448 * This file contains the current sync status. We would like to retain
449 * it across boots, but its loss is not the end of the world, so we store
450 * this information as binary data.
451 */
452 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700453
Dianne Hackborn231cc602009-04-27 17:10:36 -0700454 /**
455 * This file contains sync statistics. This is purely debugging information
456 * so is written infrequently and can be thrown away at any time.
457 */
458 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700459
Dianne Hackborn231cc602009-04-27 17:10:36 -0700460 /**
461 * This file contains the pending sync operations. It is a binary file,
462 * which must be updated every time an operation is added or removed,
463 * so we have special handling of it.
464 */
465 private final AtomicFile mPendingFile;
466 private static final int PENDING_FINISH_TO_WRITE = 4;
467 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700468
Dianne Hackborn231cc602009-04-27 17:10:36 -0700469 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800470 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800471 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800472
473 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700474
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800475 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700478
Dianne Hackborn231cc602009-04-27 17:10:36 -0700479 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700480
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800481 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
482 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
483
Dianne Hackborn231cc602009-04-27 17:10:36 -0700484 File systemDir = new File(dataDir, "system");
485 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800486 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700487
488 maybeDeleteLegacyPendingInfoLocked(syncDir);
489
Dianne Hackborn231cc602009-04-27 17:10:36 -0700490 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
491 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Matthew Williamsba352712013-08-13 15:53:31 -0700492 mPendingFile = new AtomicFile(new File(syncDir, "pending.xml"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700493 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700494
Dianne Hackborn231cc602009-04-27 17:10:36 -0700495 readAccountInfoLocked();
496 readStatusLocked();
497 readPendingOperationsLocked();
498 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700499 readAndDeleteLegacyAccountInfoLocked();
500 writeAccountInfoLocked();
501 writeStatusLocked();
502 writePendingOperationsLocked();
503 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 }
505
506 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800507 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 }
509
510 public static void init(Context context) {
511 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800512 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800514 // This call will return the correct directory whether Encrypted File Systems is
515 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600516 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800517 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 }
519
520 public static SyncStorageEngine getSingleton() {
521 if (sSyncStorageEngine == null) {
522 throw new IllegalStateException("not initialized");
523 }
524 return sSyncStorageEngine;
525 }
526
Amith Yamasani04e0d262012-02-14 11:50:53 -0800527 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
528 if (mSyncRequestListener == null) {
529 mSyncRequestListener = listener;
530 }
531 }
532
Dianne Hackborn231cc602009-04-27 17:10:36 -0700533 @Override public void handleMessage(Message msg) {
534 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700535 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700536 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700537 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700538 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700539 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700540 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 }
542 }
543 }
Costin Manolache360e4542009-09-04 13:36:04 -0700544
Ashish Sharma69d95de2012-04-11 17:27:24 -0700545 public int getSyncRandomOffset() {
546 return mSyncRandomOffset;
547 }
548
Dianne Hackborn231cc602009-04-27 17:10:36 -0700549 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
550 synchronized (mAuthorities) {
551 mChangeListeners.register(callback, mask);
552 }
553 }
Costin Manolache360e4542009-09-04 13:36:04 -0700554
Dianne Hackborn231cc602009-04-27 17:10:36 -0700555 public void removeStatusChangeListener(ISyncStatusObserver callback) {
556 synchronized (mAuthorities) {
557 mChangeListeners.unregister(callback);
558 }
559 }
Costin Manolache360e4542009-09-04 13:36:04 -0700560
Matthew Williamsfa774182013-06-18 15:44:11 -0700561 /**
562 * Figure out a reasonable flex time for cases where none is provided (old api calls).
563 * @param syncTimeSeconds requested sync time from now.
564 * @return amount of seconds before syncTimeSeconds that the sync can occur.
565 * I.e.
566 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700567 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700568 */
569 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
570 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
571 // Small enough sync request time that we don't add flex time - developer probably
572 // wants to wait for an operation to occur before syncing so we honour the
573 // request time.
574 return 0L;
575 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
576 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
577 } else {
578 // Large enough sync request time that we cap the flex time.
579 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
580 }
581 }
582
Dianne Hackborn231cc602009-04-27 17:10:36 -0700583 private void reportChange(int which) {
584 ArrayList<ISyncStatusObserver> reports = null;
585 synchronized (mAuthorities) {
586 int i = mChangeListeners.beginBroadcast();
587 while (i > 0) {
588 i--;
589 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
590 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 continue;
592 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700593 if (reports == null) {
594 reports = new ArrayList<ISyncStatusObserver>(i);
595 }
596 reports.add(mChangeListeners.getBroadcastItem(i));
597 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700598 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700599 }
Costin Manolache360e4542009-09-04 13:36:04 -0700600
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700601 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700602 Log.v(TAG, "reportChange " + which + " to: " + reports);
603 }
Costin Manolache360e4542009-09-04 13:36:04 -0700604
Dianne Hackborn231cc602009-04-27 17:10:36 -0700605 if (reports != null) {
606 int i = reports.size();
607 while (i > 0) {
608 i--;
609 try {
610 reports.get(i).onStatusChanged(which);
611 } catch (RemoteException e) {
612 // The remote callback list will take care of this for us.
613 }
614 }
615 }
616 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700617
Amith Yamasani04e0d262012-02-14 11:50:53 -0800618 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700619 synchronized (mAuthorities) {
620 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700621 AuthorityInfo authority = getAuthorityLocked(
622 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700623 "getSyncAutomatically");
624 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700625 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700626
Dianne Hackborn231cc602009-04-27 17:10:36 -0700627 int i = mAuthorities.size();
628 while (i > 0) {
629 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700630 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700631 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700632 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700633 return true;
634 }
635 }
636 return false;
637 }
638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639
Amith Yamasani04e0d262012-02-14 11:50:53 -0800640 public void setSyncAutomatically(Account account, int userId, String providerName,
641 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700642 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800643 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
644 + ", user " + userId + " -> " + sync);
645 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700646 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700647 AuthorityInfo authority =
648 getOrCreateAuthorityLocked(
649 new EndPoint(account, providerName, userId),
650 -1 /* ident */,
651 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700652 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700653 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800654 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
655 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700656 return;
657 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700658 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700659 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700661
Fred Quintana77c560f2010-03-29 22:20:26 -0700662 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700663 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
664 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700665 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700666 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 }
668
Amith Yamasani04e0d262012-02-14 11:50:53 -0800669 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700670 synchronized (mAuthorities) {
671 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700672 AuthorityInfo authority = getAuthorityLocked(
673 new EndPoint(account, providerName, userId),
674 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700675 if (authority == null) {
676 return -1;
677 }
678 return authority.syncable;
679 }
680
681 int i = mAuthorities.size();
682 while (i > 0) {
683 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700684 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700685 if (authorityInfo.target != null
686 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700687 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700688 }
689 }
690 return -1;
691 }
692 }
693
Amith Yamasani04e0d262012-02-14 11:50:53 -0800694 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700695 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700696 }
697
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700698 public boolean getIsTargetServiceActive(ComponentName cname, int userId) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700699 synchronized (mAuthorities) {
700 if (cname != null) {
701 AuthorityInfo authority = getAuthorityLocked(
702 new EndPoint(cname, userId),
Matthew Williams8ef22042013-07-26 12:56:39 -0700703 "get service active");
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700704 if (authority == null) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700705 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700706 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700707 return (authority.syncable == 1);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700708 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700709 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700710 }
711 }
712
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700713 public void setIsTargetServiceActive(ComponentName cname, int userId, boolean active) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700714 setSyncableStateForEndPoint(new EndPoint(cname, userId), active ? 1 : 0);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700715 }
716
717 /**
718 * An enabled sync service and a syncable provider's adapter both get resolved to the same
719 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700720 * @param target target to set value for.
721 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700722 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700723 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700724 AuthorityInfo aInfo;
725 synchronized (mAuthorities) {
726 aInfo = getOrCreateAuthorityLocked(target, -1, false);
727 if (syncable > 1) {
728 syncable = 1;
729 } else if (syncable < -1) {
730 syncable = -1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700731 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700732 if (Log.isLoggable(TAG, Log.VERBOSE)) {
733 Log.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
734 }
735 if (aInfo.syncable == syncable) {
736 if (Log.isLoggable(TAG, Log.VERBOSE)) {
737 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
738 }
739 return;
740 }
741 aInfo.syncable = syncable;
742 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700743 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700744 if (syncable > 0) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700745 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700746 }
747 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
748 }
749
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700750 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800751 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700752 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
753 if (authority != null) {
754 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800755 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700756 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800757 }
758 }
759
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700760 /**
761 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
762 * the account or provider info be null, which signifies all accounts or providers.
763 */
764 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
765 if (Log.isLoggable(TAG, Log.VERBOSE)) {
766 Log.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800767 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
768 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700769 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800770 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700771 if (info.target_provider
772 && (info.account == null || info.provider == null)) {
773 // Do more work for a provider sync if the provided info has specified all
774 // accounts/providers.
775 changed = setBackoffLocked(
776 info.account /* may be null */,
777 info.userId,
778 info.provider /* may be null */,
779 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800780 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700781 AuthorityInfo authorityInfo =
782 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
783 if (authorityInfo.backoffTime == nextSyncTime
784 && authorityInfo.backoffDelay == nextDelay) {
785 changed = false;
786 } else {
787 authorityInfo.backoffTime = nextSyncTime;
788 authorityInfo.backoffDelay = nextDelay;
789 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800790 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800791 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800792 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800793 if (changed) {
794 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
795 }
796 }
797
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700798 /**
799 * Either set backoff for a specific authority, or set backoff for all the
800 * accounts on a specific adapter/all adapters.
801 *
802 * @param account account for which to set backoff. Null to specify all accounts.
803 * @param userId id of the user making this request.
804 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700805 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700806 */
807 private boolean setBackoffLocked(Account account, int userId, String providerName,
808 long nextSyncTime, long nextDelay) {
809 boolean changed = false;
810 for (AccountInfo accountInfo : mAccounts.values()) {
811 if (account != null && !account.equals(accountInfo.accountAndUser.account)
812 && userId != accountInfo.accountAndUser.userId) {
813 continue;
814 }
815 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
816 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700817 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700818 continue;
819 }
820 if (authorityInfo.backoffTime != nextSyncTime
821 || authorityInfo.backoffDelay != nextDelay) {
822 authorityInfo.backoffTime = nextSyncTime;
823 authorityInfo.backoffDelay = nextDelay;
824 changed = true;
825 }
826 }
827 }
828 return changed;
829 }
830
Alon Alberted1d2532011-02-15 14:02:14 -0800831 public void clearAllBackoffs(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800832 boolean changed = false;
833 synchronized (mAuthorities) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700834 synchronized (syncQueue) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700835 // Clear backoff for all sync adapters.
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700836 for (AccountInfo accountInfo : mAccounts.values()) {
837 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
838 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
839 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700840 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700841 Log.v(TAG, "clearAllBackoffs:"
Matthew Williams8ef22042013-07-26 12:56:39 -0700842 + " authority:" + authorityInfo.target
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700843 + " account:" + accountInfo.accountAndUser.account.name
844 + " user:" + accountInfo.accountAndUser.userId
845 + " backoffTime was: " + authorityInfo.backoffTime
846 + " backoffDelay was: " + authorityInfo.backoffDelay);
847 }
848 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
849 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700850 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800851 }
Alon Albert744e310f2010-12-14 11:37:20 -0800852 }
853 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700854 // Clear backoff for all sync services.
855 for (ComponentName service : mServices.keySet()) {
856 SparseArray<AuthorityInfo> aInfos = mServices.get(service);
857 for (int i = 0; i < aInfos.size(); i++) {
858 AuthorityInfo authorityInfo = aInfos.valueAt(i);
859 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
860 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
861 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
862 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
863 }
864 }
865 }
866 syncQueue.clearBackoffs();
Alon Albert744e310f2010-12-14 11:37:20 -0800867 }
868 }
869
870 if (changed) {
871 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
872 }
873 }
874
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700875 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800876 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700877 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800878 if (authority == null) {
879 return 0;
880 }
881 return authority.delayUntil;
882 }
883 }
884
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700885 public void setDelayUntilTime(EndPoint info, long delayUntil) {
886 if (Log.isLoggable(TAG, Log.VERBOSE)) {
887 Log.v(TAG, "setDelayUntil: " + info
888 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800889 }
890 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700891 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
892 if (authority.delayUntil == delayUntil) {
893 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700894 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700895 authority.delayUntil = delayUntil;
896 }
897 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
898 }
899
900 public void updateOrAddPeriodicSync(EndPoint info, long period, long flextime, Bundle extras) {
901 if (Log.isLoggable(TAG, Log.VERBOSE)) {
902 Log.v(TAG, "addPeriodicSync: " + info
903 + " -> period " + period + ", flex " + flextime + ", extras "
904 + extras.toString());
905 }
906 synchronized (mAuthorities) {
907 if (period <= 0) {
908 Log.e(TAG, "period < 0, should never happen in updateOrAddPeriodicSync");
909 }
910 if (extras == null) {
911 Log.e(TAG, "null extras, should never happen in updateOrAddPeriodicSync:");
Matthew Williamsfa774182013-06-18 15:44:11 -0700912 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700913 try {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700914 PeriodicSync toUpdate;
915 if (info.target_provider) {
916 toUpdate = new PeriodicSync(info.account,
917 info.provider,
918 extras,
919 period,
920 flextime);
Fred Quintana77c560f2010-03-29 22:20:26 -0700921 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700922 toUpdate = new PeriodicSync(info.service,
923 extras,
924 period,
925 flextime);
926 }
927 AuthorityInfo authority =
928 getOrCreateAuthorityLocked(info, -1, false);
929 // add this periodic sync if an equivalent periodic doesn't already exist.
930 boolean alreadyPresent = false;
931 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
932 PeriodicSync syncInfo = authority.periodicSyncs.get(i);
933 if (SyncManager.syncExtrasEquals(syncInfo.extras,
934 extras,
935 true /* includeSyncSettings*/)) {
936 if (period == syncInfo.period &&
937 flextime == syncInfo.flexTime) {
938 // Absolutely the same.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700939 return;
Fred Quintana77c560f2010-03-29 22:20:26 -0700940 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700941 authority.periodicSyncs.set(i, toUpdate);
942 alreadyPresent = true;
943 break;
Fred Quintana77c560f2010-03-29 22:20:26 -0700944 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700945 }
946 // If we added an entry to the periodicSyncs array also add an entry to
947 // the periodic syncs status to correspond to it.
948 if (!alreadyPresent) {
949 authority.periodicSyncs.add(toUpdate);
950 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
951 // A new periodic sync is initialised as already having been run.
952 status.setPeriodicSyncTime(
953 authority.periodicSyncs.size() - 1,
954 System.currentTimeMillis());
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800955 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700956 } finally {
957 writeAccountInfoLocked();
958 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800959 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800960 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800961 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
962 }
963
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700964 public void removePeriodicSync(EndPoint info, Bundle extras) {
965 synchronized(mAuthorities) {
966 try {
967 AuthorityInfo authority =
968 getOrCreateAuthorityLocked(info, -1, false);
Matthew Williams8ef22042013-07-26 12:56:39 -0700969 // Remove any periodic syncs that match the target and extras.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700970 SyncStatusInfo status = mSyncStatus.get(authority.ident);
971 boolean changed = false;
972 Iterator<PeriodicSync> iterator = authority.periodicSyncs.iterator();
973 int i = 0;
974 while (iterator.hasNext()) {
975 PeriodicSync syncInfo = iterator.next();
976 if (SyncManager.syncExtrasEquals(syncInfo.extras,
977 extras,
978 true /* includeSyncSettings */)) {
979 iterator.remove();
980 changed = true;
981 // If we removed an entry from the periodicSyncs array also
982 // remove the corresponding entry from the status
983 if (status != null) {
984 status.removePeriodicSyncTime(i);
985 } else {
986 Log.e(TAG, "Tried removing sync status on remove periodic sync but"
987 + " did not find it.");
988 }
989 } else {
990 i++;
991 }
992 }
993 if (!changed) {
994 return;
995 }
996 } finally {
997 writeAccountInfoLocked();
998 writeStatusLocked();
999 }
1000 }
1001 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001002 }
1003
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001004 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001005 * @return list of periodic syncs for a target. Never null. If no such syncs exist, returns an
1006 * empty list.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001007 */
1008 public List<PeriodicSync> getPeriodicSyncs(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001009 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001010 AuthorityInfo authorityInfo = getAuthorityLocked(info, "getPeriodicSyncs");
1011 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
1012 if (authorityInfo != null) {
1013 for (PeriodicSync item : authorityInfo.periodicSyncs) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001014 // Copy and send out. Necessary for thread-safety although it's parceled.
1015 syncs.add(new PeriodicSync(item));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001016 }
1017 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001018 return syncs;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001019 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001020 }
1021
Amith Yamasani04e0d262012-02-14 11:50:53 -08001022 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001023 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001024 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001025 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001026 return;
1027 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001028 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001029 writeAccountInfoLocked();
1030 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001031 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -07001032 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
1033 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -07001034 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001035 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -08001036 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038
Amith Yamasani04e0d262012-02-14 11:50:53 -08001039 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001040 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001041 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +08001042 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001043 }
1044 }
Costin Manolache360e4542009-09-04 13:36:04 -07001045
Dianne Hackborn231cc602009-04-27 17:10:36 -07001046 public AuthorityInfo getAuthority(int authorityId) {
1047 synchronized (mAuthorities) {
1048 return mAuthorities.get(authorityId);
1049 }
1050 }
Costin Manolache360e4542009-09-04 13:36:04 -07001051
Dianne Hackborn231cc602009-04-27 17:10:36 -07001052 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001053 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -07001054 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001055 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001056 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001057 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001058 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001059 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001060 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001061 return true;
1062 }
1063 }
1064 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001065 return false;
1066 }
Costin Manolache360e4542009-09-04 13:36:04 -07001067
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001068 public PendingOperation insertIntoPending(SyncOperation op) {
1069 PendingOperation pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001070 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001071 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1072 Log.v(TAG, "insertIntoPending: authority=" + op.target
Amith Yamasani04e0d262012-02-14 11:50:53 -08001073 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -07001074 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001075 final EndPoint info = op.target;
1076 AuthorityInfo authority =
1077 getOrCreateAuthorityLocked(info,
1078 -1 /* desired identifier */,
1079 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001080 if (authority == null) {
1081 return null;
1082 }
Costin Manolache360e4542009-09-04 13:36:04 -07001083
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001084 pop = new PendingOperation(authority, op.reason, op.syncSource, op.extras,
1085 op.expedited);
1086 mPendingOperations.add(pop);
1087 writePendingOperationsLocked();
Costin Manolache360e4542009-09-04 13:36:04 -07001088
Dianne Hackborn231cc602009-04-27 17:10:36 -07001089 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1090 status.pending = true;
1091 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001092 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001093 return pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001094 }
1095
Matthew Williamsfa774182013-06-18 15:44:11 -07001096 /**
1097 * Remove from list of pending operations. If successful, search through list for matching
Matthew Williams8ef22042013-07-26 12:56:39 -07001098 * authorities. If there are no more pending syncs for the same target,
1099 * update the SyncStatusInfo for that target.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001100 * @param op Pending op to delete.
Matthew Williamsfa774182013-06-18 15:44:11 -07001101 */
Dianne Hackborn231cc602009-04-27 17:10:36 -07001102 public boolean deleteFromPending(PendingOperation op) {
1103 boolean res = false;
1104 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001105 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1106 Log.v(TAG, "deleteFromPending: account=" + op.toString());
Fred Quintana77c560f2010-03-29 22:20:26 -07001107 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001108 if (mPendingOperations.remove(op)) {
1109 if (mPendingOperations.size() == 0
1110 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
1111 writePendingOperationsLocked();
1112 mNumPendingFinished = 0;
1113 } else {
1114 mNumPendingFinished++;
1115 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001116 AuthorityInfo authority = getAuthorityLocked(op.target, "deleteFromPending");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001117 if (authority != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001118 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1119 Log.v(TAG, "removing - " + authority.toString());
1120 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001121 final int N = mPendingOperations.size();
1122 boolean morePending = false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001123 for (int i = 0; i < N; i++) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001124 PendingOperation cur = mPendingOperations.get(i);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001125 if (cur.equals(op)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001126 morePending = true;
1127 break;
1128 }
1129 }
Costin Manolache360e4542009-09-04 13:36:04 -07001130
Dianne Hackborn231cc602009-04-27 17:10:36 -07001131 if (!morePending) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001132 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001133 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1134 status.pending = false;
1135 }
1136 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001137 res = true;
1138 }
1139 }
Costin Manolache360e4542009-09-04 13:36:04 -07001140
Fred Quintanaac9385e2009-06-22 18:00:59 -07001141 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001142 return res;
1143 }
1144
Dianne Hackborn231cc602009-04-27 17:10:36 -07001145 /**
1146 * Return a copy of the current array of pending operations. The
1147 * PendingOperation objects are the real objects stored inside, so that
1148 * they can be used with deleteFromPending().
1149 */
1150 public ArrayList<PendingOperation> getPendingOperations() {
1151 synchronized (mAuthorities) {
1152 return new ArrayList<PendingOperation>(mPendingOperations);
1153 }
1154 }
Costin Manolache360e4542009-09-04 13:36:04 -07001155
Dianne Hackborn231cc602009-04-27 17:10:36 -07001156 /**
1157 * Return the number of currently pending operations.
1158 */
1159 public int getPendingOperationCount() {
1160 synchronized (mAuthorities) {
1161 return mPendingOperations.size();
1162 }
1163 }
Costin Manolache360e4542009-09-04 13:36:04 -07001164
Dianne Hackborn231cc602009-04-27 17:10:36 -07001165 /**
1166 * Called when the set of account has changed, given the new array of
1167 * active accounts.
1168 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001169 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001170 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001171 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1172 Log.v(TAG, "Updating for new accounts...");
1173 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001174 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1175 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1176 while (accIt.hasNext()) {
1177 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001178 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1179 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001180 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001181 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001182 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001183 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001184 for (AuthorityInfo auth : acc.authorities.values()) {
1185 removing.put(auth.ident, auth);
1186 }
1187 accIt.remove();
1188 }
1189 }
Costin Manolache360e4542009-09-04 13:36:04 -07001190
Dianne Hackborn231cc602009-04-27 17:10:36 -07001191 // Clean out all data structures.
1192 int i = removing.size();
1193 if (i > 0) {
1194 while (i > 0) {
1195 i--;
1196 int ident = removing.keyAt(i);
1197 mAuthorities.remove(ident);
1198 int j = mSyncStatus.size();
1199 while (j > 0) {
1200 j--;
1201 if (mSyncStatus.keyAt(j) == ident) {
1202 mSyncStatus.remove(mSyncStatus.keyAt(j));
1203 }
1204 }
1205 j = mSyncHistory.size();
1206 while (j > 0) {
1207 j--;
1208 if (mSyncHistory.get(j).authorityId == ident) {
1209 mSyncHistory.remove(j);
1210 }
1211 }
1212 }
1213 writeAccountInfoLocked();
1214 writeStatusLocked();
1215 writePendingOperationsLocked();
1216 writeStatisticsLocked();
1217 }
1218 }
1219 }
1220
1221 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001222 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1223 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001224 */
Fred Quintana918339a2010-10-05 14:00:39 -07001225 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1226 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001227 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001228 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001229 Log.v(TAG, "setActiveSync: account="
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001230 + " auth=" + activeSyncContext.mSyncOperation.target
Fred Quintana918339a2010-10-05 14:00:39 -07001231 + " src=" + activeSyncContext.mSyncOperation.syncSource
1232 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001233 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001234 final EndPoint info = activeSyncContext.mSyncOperation.target;
1235 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1236 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001237 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001238 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001239 syncInfo = new SyncInfo(
1240 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001241 authorityInfo.target.account,
1242 authorityInfo.target.provider,
1243 authorityInfo.target.service,
Fred Quintana918339a2010-10-05 14:00:39 -07001244 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001245 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001246 }
Fred Quintana918339a2010-10-05 14:00:39 -07001247 reportActiveChange();
1248 return syncInfo;
1249 }
1250
1251 /**
1252 * Called to indicate that a previously active sync is no longer active.
1253 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001254 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001255 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001256 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001257 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1258 + " user=" + userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001259 + " auth=" + syncInfo.authority
1260 + " service=" + syncInfo.service);
Fred Quintana918339a2010-10-05 14:00:39 -07001261 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001262 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001263 }
1264
1265 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001266 }
1267
1268 /**
1269 * To allow others to send active change reports, to poke clients.
1270 */
1271 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001272 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001273 }
Costin Manolache360e4542009-09-04 13:36:04 -07001274
Dianne Hackborn231cc602009-04-27 17:10:36 -07001275 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001276 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001277 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001278 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001279 long id;
1280 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001281 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1282 Log.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001283 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001284 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001285 if (authority == null) {
1286 return -1;
1287 }
1288 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001289 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001290 item.authorityId = authority.ident;
1291 item.historyId = mNextHistoryId++;
1292 if (mNextHistoryId < 0) mNextHistoryId = 0;
1293 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001294 item.source = op.syncSource;
1295 item.reason = op.reason;
1296 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001297 item.event = EVENT_START;
1298 mSyncHistory.add(0, item);
1299 while (mSyncHistory.size() > MAX_HISTORY) {
1300 mSyncHistory.remove(mSyncHistory.size()-1);
1301 }
1302 id = item.historyId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001303 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001304 }
Costin Manolache360e4542009-09-04 13:36:04 -07001305
Fred Quintanaac9385e2009-06-22 18:00:59 -07001306 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001307 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 }
1309
Fred Quintana77c560f2010-03-29 22:20:26 -07001310 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001312 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001313 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001314 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1315 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001316 SyncHistoryItem item = null;
1317 int i = mSyncHistory.size();
1318 while (i > 0) {
1319 i--;
1320 item = mSyncHistory.get(i);
1321 if (item.historyId == historyId) {
1322 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001324 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
Costin Manolache360e4542009-09-04 13:36:04 -07001326
Dianne Hackborn231cc602009-04-27 17:10:36 -07001327 if (item == null) {
1328 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1329 return;
1330 }
Costin Manolache360e4542009-09-04 13:36:04 -07001331
Dianne Hackborn231cc602009-04-27 17:10:36 -07001332 item.elapsedTime = elapsedTime;
1333 item.event = EVENT_STOP;
1334 item.mesg = resultMessage;
1335 item.downstreamActivity = downstreamActivity;
1336 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001337
Dianne Hackborn231cc602009-04-27 17:10:36 -07001338 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001339
Dianne Hackborn231cc602009-04-27 17:10:36 -07001340 status.numSyncs++;
1341 status.totalElapsedTime += elapsedTime;
1342 switch (item.source) {
1343 case SOURCE_LOCAL:
1344 status.numSourceLocal++;
1345 break;
1346 case SOURCE_POLL:
1347 status.numSourcePoll++;
1348 break;
1349 case SOURCE_USER:
1350 status.numSourceUser++;
1351 break;
1352 case SOURCE_SERVER:
1353 status.numSourceServer++;
1354 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001355 case SOURCE_PERIODIC:
1356 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001357 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001358 }
Costin Manolache360e4542009-09-04 13:36:04 -07001359
Dianne Hackborn231cc602009-04-27 17:10:36 -07001360 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001361 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001362 if (mDayStats[0] == null) {
1363 mDayStats[0] = new DayStats(day);
1364 } else if (day != mDayStats[0].day) {
1365 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1366 mDayStats[0] = new DayStats(day);
1367 writeStatisticsNow = true;
1368 } else if (mDayStats[0] == null) {
1369 }
1370 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001371
Dianne Hackborn231cc602009-04-27 17:10:36 -07001372 final long lastSyncTime = (item.eventTime + elapsedTime);
1373 boolean writeStatusNow = false;
1374 if (MESG_SUCCESS.equals(resultMessage)) {
1375 // - if successful, update the successful columns
1376 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1377 writeStatusNow = true;
1378 }
1379 status.lastSuccessTime = lastSyncTime;
1380 status.lastSuccessSource = item.source;
1381 status.lastFailureTime = 0;
1382 status.lastFailureSource = -1;
1383 status.lastFailureMesg = null;
1384 status.initialFailureTime = 0;
1385 ds.successCount++;
1386 ds.successTime += elapsedTime;
1387 } else if (!MESG_CANCELED.equals(resultMessage)) {
1388 if (status.lastFailureTime == 0) {
1389 writeStatusNow = true;
1390 }
1391 status.lastFailureTime = lastSyncTime;
1392 status.lastFailureSource = item.source;
1393 status.lastFailureMesg = resultMessage;
1394 if (status.initialFailureTime == 0) {
1395 status.initialFailureTime = lastSyncTime;
1396 }
1397 ds.failureCount++;
1398 ds.failureTime += elapsedTime;
1399 }
Costin Manolache360e4542009-09-04 13:36:04 -07001400
Dianne Hackborn231cc602009-04-27 17:10:36 -07001401 if (writeStatusNow) {
1402 writeStatusLocked();
1403 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1404 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1405 WRITE_STATUS_DELAY);
1406 }
1407 if (writeStatisticsNow) {
1408 writeStatisticsLocked();
1409 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1410 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1411 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001412 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001413 }
Costin Manolache360e4542009-09-04 13:36:04 -07001414
Fred Quintanaac9385e2009-06-22 18:00:59 -07001415 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001416 }
1417
1418 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001419 * Return a list of the currently active syncs. Note that the returned items are the
1420 * real, live active sync objects, so be careful what you do with it.
1421 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001422 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001423 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001424 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1425 if (syncs == null) {
1426 syncs = new ArrayList<SyncInfo>();
1427 mCurrentSyncs.put(userId, syncs);
1428 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001429 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001430 }
1431 }
Costin Manolache360e4542009-09-04 13:36:04 -07001432
Dianne Hackborn231cc602009-04-27 17:10:36 -07001433 /**
1434 * Return an array of the current sync status for all authorities. Note
1435 * that the objects inside the array are the real, live status objects,
1436 * so be careful what you do with them.
1437 */
1438 public ArrayList<SyncStatusInfo> getSyncStatus() {
1439 synchronized (mAuthorities) {
1440 final int N = mSyncStatus.size();
1441 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1442 for (int i=0; i<N; i++) {
1443 ops.add(mSyncStatus.valueAt(i));
1444 }
1445 return ops;
1446 }
1447 }
Costin Manolache360e4542009-09-04 13:36:04 -07001448
Dianne Hackborn231cc602009-04-27 17:10:36 -07001449 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001450 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001451 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001452 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001453 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001454 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001455 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001456 true /* write to storage if this results in a change */);
1457 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1458 }
1459 }
1460
1461 /**
1462 * Return a copy of all authorities with their corresponding sync status
1463 */
1464 public ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> getCopyOfAllAuthoritiesWithSyncStatus() {
1465 synchronized (mAuthorities) {
1466 ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos =
1467 new ArrayList<Pair<AuthorityInfo, SyncStatusInfo>>(mAuthorities.size());
1468 for (int i = 0; i < mAuthorities.size(); i++) {
1469 infos.add(createCopyPairOfAuthorityWithSyncStatusLocked(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001470 }
1471 return infos;
1472 }
1473 }
1474
1475 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001476 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001477 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001478 * @param info the endpoint target we are querying status info for.
1479 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001480 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001481 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
1482 if (info.target_provider && (info.account == null || info.provider == null)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001483 throw new IllegalArgumentException();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001484 } else if (info.target_service && info.service == null) {
1485 throw new IllegalArgumentException();
Costin Manolacheb7520982009-09-02 18:03:05 -07001486 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001487 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001488 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001489 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001490 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001491 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001492 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001493 && ainfo.target.matchesSpec(info)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001494 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001495 }
1496 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001497 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001498 }
1499 }
Costin Manolache360e4542009-09-04 13:36:04 -07001500
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001501 /** Return true if the pending status is true of any matching authorities. */
1502 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001503 synchronized (mAuthorities) {
1504 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001505 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001506 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001507 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1508 if (ainfo == null) {
1509 continue;
1510 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001511 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001512 continue;
1513 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001514 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001515 return true;
1516 }
1517 }
1518 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 }
1520 }
1521
1522 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001523 * Return an array of the current sync status for all authorities. Note
1524 * that the objects inside the array are the real, live status objects,
1525 * so be careful what you do with them.
1526 */
1527 public ArrayList<SyncHistoryItem> getSyncHistory() {
1528 synchronized (mAuthorities) {
1529 final int N = mSyncHistory.size();
1530 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1531 for (int i=0; i<N; i++) {
1532 items.add(mSyncHistory.get(i));
1533 }
1534 return items;
1535 }
1536 }
Costin Manolache360e4542009-09-04 13:36:04 -07001537
Dianne Hackborn231cc602009-04-27 17:10:36 -07001538 /**
1539 * Return an array of the current per-day statistics. Note
1540 * that the objects inside the array are the real, live status objects,
1541 * so be careful what you do with them.
1542 */
1543 public DayStats[] getDayStatistics() {
1544 synchronized (mAuthorities) {
1545 DayStats[] ds = new DayStats[mDayStats.length];
1546 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1547 return ds;
1548 }
1549 }
Costin Manolache360e4542009-09-04 13:36:04 -07001550
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001551 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1552 AuthorityInfo authorityInfo) {
1553 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1554 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1555 }
1556
Dianne Hackborn55280a92009-05-07 15:53:46 -07001557 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001558 mCal.setTimeInMillis(System.currentTimeMillis());
1559 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1560 if (mYear != mCal.get(Calendar.YEAR)) {
1561 mYear = mCal.get(Calendar.YEAR);
1562 mCal.clear();
1563 mCal.set(Calendar.YEAR, mYear);
1564 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1565 }
1566 return dayOfYear + mYearInDays;
1567 }
Costin Manolache360e4542009-09-04 13:36:04 -07001568
Dianne Hackborn231cc602009-04-27 17:10:36 -07001569 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001570 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001571 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001572 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001573 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001574 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001575 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001576 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
1577 if (info.target_service) {
1578 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1579 AuthorityInfo authority = null;
1580 if (aInfo != null) {
1581 authority = aInfo.get(info.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001582 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001583 if (authority == null) {
1584 if (tag != null) {
1585 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001586 Log.v(TAG, tag + " No authority info found for " + info.service + " for"
1587 + " user " + info.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001588 }
1589 }
1590 return null;
1591 }
1592 return authority;
1593 } else if (info.target_provider){
1594 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1595 AccountInfo accountInfo = mAccounts.get(au);
1596 if (accountInfo == null) {
1597 if (tag != null) {
1598 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1599 Log.v(TAG, tag + ": unknown account " + au);
1600 }
1601 }
1602 return null;
1603 }
1604 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1605 if (authority == null) {
1606 if (tag != null) {
1607 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1608 Log.v(TAG, tag + ": unknown provider " + info.provider);
1609 }
1610 }
1611 return null;
1612 }
1613 return authority;
1614 } else {
1615 Log.e(TAG, tag + " Authority : " + info + ", invalid target");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001616 return null;
1617 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001618 }
Costin Manolache360e4542009-09-04 13:36:04 -07001619
Matthew Williamsfa774182013-06-18 15:44:11 -07001620 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001621 * @param info info identifying target.
1622 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001623 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001624 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001625 * exists.
1626 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001627 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1628 AuthorityInfo authority = null;
1629 if (info.target_service) {
1630 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1631 if (aInfo == null) {
1632 aInfo = new SparseArray<AuthorityInfo>();
1633 mServices.put(info.service, aInfo);
Matthew Williamsfa774182013-06-18 15:44:11 -07001634 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001635 authority = aInfo.get(info.userId);
1636 if (authority == null) {
1637 authority = createAuthorityLocked(info, ident, doWrite);
1638 aInfo.put(info.userId, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001639 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001640 } else if (info.target_provider) {
1641 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1642 AccountInfo account = mAccounts.get(au);
1643 if (account == null) {
1644 account = new AccountInfo(au);
1645 mAccounts.put(au, account);
1646 }
1647 authority = account.authorities.get(info.provider);
1648 if (authority == null) {
1649 authority = createAuthorityLocked(info, ident, doWrite);
1650 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001651 }
1652 }
1653 return authority;
1654 }
1655
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001656 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1657 AuthorityInfo authority;
1658 if (ident < 0) {
1659 ident = mNextAuthorityId;
1660 mNextAuthorityId++;
1661 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001662 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001663 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1664 Log.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001665 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001666 authority = new AuthorityInfo(info, ident);
1667 mAuthorities.put(ident, authority);
1668 if (doWrite) {
1669 writeAccountInfoLocked();
1670 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001671 return authority;
1672 }
Costin Manolache360e4542009-09-04 13:36:04 -07001673
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001674 public void removeAuthority(EndPoint info) {
1675 synchronized (mAuthorities) {
1676 if (info.target_provider) {
1677 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
1678 } else {
1679 SparseArray<AuthorityInfo> aInfos = mServices.get(info.service);
1680 if (aInfos != null) {
1681 AuthorityInfo authorityInfo = aInfos.get(info.userId);
1682 if (authorityInfo != null) {
1683 mAuthorities.remove(authorityInfo.ident);
1684 aInfos.delete(info.userId);
1685 writeAccountInfoLocked();
1686 }
1687 }
1688
1689 }
1690 }
1691 }
1692
1693 /**
1694 * Remove an authority associated with a provider. Needs to be a standalone function for
1695 * backward compatibility.
1696 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001697 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1698 boolean doWrite) {
1699 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001700 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001701 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1702 if (authorityInfo != null) {
1703 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001704 if (doWrite) {
1705 writeAccountInfoLocked();
1706 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001707 }
1708 }
1709 }
1710
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001711 /**
1712 * Updates (in a synchronized way) the periodic sync time of the specified
Matthew Williams8ef22042013-07-26 12:56:39 -07001713 * target id and target periodic sync
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001714 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001715 public void setPeriodicSyncTime(int authorityId, PeriodicSync targetPeriodicSync, long when) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001716 boolean found = false;
1717 final AuthorityInfo authorityInfo;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001718 synchronized (mAuthorities) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001719 authorityInfo = mAuthorities.get(authorityId);
1720 for (int i = 0; i < authorityInfo.periodicSyncs.size(); i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001721 PeriodicSync periodicSync = authorityInfo.periodicSyncs.get(i);
1722 if (targetPeriodicSync.equals(periodicSync)) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001723 mSyncStatus.get(authorityId).setPeriodicSyncTime(i, when);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001724 found = true;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001725 break;
1726 }
1727 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001728 }
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001729 if (!found) {
1730 Log.w(TAG, "Ignoring setPeriodicSyncTime request for a sync that does not exist. " +
Matthew Williams8ef22042013-07-26 12:56:39 -07001731 "Authority: " + authorityInfo.target);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001732 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001733 }
1734
Dianne Hackborn231cc602009-04-27 17:10:36 -07001735 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1736 SyncStatusInfo status = mSyncStatus.get(authorityId);
1737 if (status == null) {
1738 status = new SyncStatusInfo(authorityId);
1739 mSyncStatus.put(authorityId, status);
1740 }
1741 return status;
1742 }
Costin Manolache360e4542009-09-04 13:36:04 -07001743
Dianne Hackborn55280a92009-05-07 15:53:46 -07001744 public void writeAllState() {
1745 synchronized (mAuthorities) {
1746 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001747
Dianne Hackborn55280a92009-05-07 15:53:46 -07001748 if (mNumPendingFinished > 0) {
1749 // Only write these if they are out of date.
1750 writePendingOperationsLocked();
1751 }
Costin Manolache360e4542009-09-04 13:36:04 -07001752
Dianne Hackborn55280a92009-05-07 15:53:46 -07001753 // Just always write these... they are likely out of date.
1754 writeStatusLocked();
1755 writeStatisticsLocked();
1756 }
1757 }
Costin Manolache360e4542009-09-04 13:36:04 -07001758
Dianne Hackborn231cc602009-04-27 17:10:36 -07001759 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001760 * public for testing
1761 */
1762 public void clearAndReadState() {
1763 synchronized (mAuthorities) {
1764 mAuthorities.clear();
1765 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001766 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001767 mPendingOperations.clear();
1768 mSyncStatus.clear();
1769 mSyncHistory.clear();
1770
1771 readAccountInfoLocked();
1772 readStatusLocked();
1773 readPendingOperationsLocked();
1774 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001775 readAndDeleteLegacyAccountInfoLocked();
1776 writeAccountInfoLocked();
1777 writeStatusLocked();
1778 writePendingOperationsLocked();
1779 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001780 }
1781 }
1782
1783 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001784 * Read all account information back in to the initial engine state.
1785 */
1786 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001787 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001788 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001790 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001791 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001792 Log.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001793 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001794 XmlPullParser parser = Xml.newPullParser();
1795 parser.setInput(fis, null);
1796 int eventType = parser.getEventType();
1797 while (eventType != XmlPullParser.START_TAG) {
1798 eventType = parser.next();
1799 }
1800 String tagName = parser.getName();
1801 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001802 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001803 String versionString = parser.getAttributeValue(null, "version");
1804 int version;
1805 try {
1806 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1807 } catch (NumberFormatException e) {
1808 version = 0;
1809 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001810 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001811 try {
1812 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1813 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1814 } catch (NumberFormatException e) {
1815 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001816 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001817 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1818 try {
1819 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1820 } catch (NumberFormatException e) {
1821 mSyncRandomOffset = 0;
1822 }
1823 if (mSyncRandomOffset == 0) {
1824 Random random = new Random(System.currentTimeMillis());
1825 mSyncRandomOffset = random.nextInt(86400);
1826 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001827 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001828 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001829 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001830 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001831 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001832 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001833 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001834 if (parser.getDepth() == 2) {
1835 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001836 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001837 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001838 if (authority.ident > highestAuthorityId) {
1839 highestAuthorityId = authority.ident;
1840 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001841 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1842 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001843 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001844 } else if (parser.getDepth() == 3) {
1845 if ("periodicSync".equals(tagName) && authority != null) {
1846 periodicSync = parsePeriodicSync(parser, authority);
1847 }
1848 } else if (parser.getDepth() == 4 && periodicSync != null) {
1849 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001850 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001851 }
1852 }
1853 }
1854 eventType = parser.next();
1855 } while (eventType != XmlPullParser.END_DOCUMENT);
1856 }
1857 } catch (XmlPullParserException e) {
1858 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001859 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001860 } catch (java.io.IOException e) {
1861 if (fis == null) Log.i(TAG, "No initial accounts");
1862 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001863 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001864 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001865 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001866 if (fis != null) {
1867 try {
1868 fis.close();
1869 } catch (java.io.IOException e1) {
1870 }
1871 }
1872 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001873
Fred Quintana77c560f2010-03-29 22:20:26 -07001874 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001875 }
Costin Manolache360e4542009-09-04 13:36:04 -07001876
Fred Quintanafb084402010-03-23 17:57:03 -07001877 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001878 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1879 * pending.xml was used starting in KLP.
1880 * @param syncDir directory where the sync files are located.
1881 */
1882 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1883 File file = new File(syncDir, "pending.bin");
1884 if (!file.exists()) {
1885 return;
1886 } else {
1887 file.delete();
1888 }
1889 }
1890
1891 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001892 * some authority names have changed. copy over their settings and delete the old ones
1893 * @return true if a change was made
1894 */
1895 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1896 boolean writeNeeded = false;
1897
1898 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1899 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001900 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001901 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001902 // skip this authority if it doesn't target a provider
1903 if (authority.target.target_service) {
1904 continue;
1905 }
Fred Quintanafb084402010-03-23 17:57:03 -07001906 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001907 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001908 if (newAuthorityName == null) {
1909 continue;
1910 }
1911
1912 // remember this authority so we can remove it later. we can't remove it
1913 // now without messing up this loop iteration
1914 authoritiesToRemove.add(authority);
1915
1916 // this authority isn't enabled, no need to copy it to the new authority name since
1917 // the default is "disabled"
1918 if (!authority.enabled) {
1919 continue;
1920 }
1921
1922 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001923 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001924 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001925 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001926 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001927 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001928 continue;
1929 }
1930
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001931 AuthorityInfo newAuthority =
1932 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001933 newAuthority.enabled = true;
1934 writeNeeded = true;
1935 }
1936
1937 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001938 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001939 authorityInfo.target.account,
1940 authorityInfo.target.userId,
1941 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001942 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001943 writeNeeded = true;
1944 }
1945
1946 return writeNeeded;
1947 }
1948
Amith Yamasani04e0d262012-02-14 11:50:53 -08001949 private void parseListenForTickles(XmlPullParser parser) {
1950 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1951 int userId = 0;
1952 try {
1953 userId = Integer.parseInt(user);
1954 } catch (NumberFormatException e) {
1955 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1956 } catch (NullPointerException e) {
1957 Log.e(TAG, "the user in listen-for-tickles is null", e);
1958 }
1959 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1960 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1961 mMasterSyncAutomatically.put(userId, listen);
1962 }
1963
Fred Quintanac2e46912010-03-15 16:10:44 -07001964 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001965 AuthorityInfo authority = null;
1966 int id = -1;
1967 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001968 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001969 } catch (NumberFormatException e) {
1970 Log.e(TAG, "error parsing the id of the authority", e);
1971 } catch (NullPointerException e) {
1972 Log.e(TAG, "the id of the authority is null", e);
1973 }
1974 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001975 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001976 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001977 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001978 String accountName = parser.getAttributeValue(null, "account");
1979 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001980 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001981 String packageName = parser.getAttributeValue(null, "package");
1982 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001983 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001984 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001985 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001986 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001987 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001988 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001989 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001990 Log.v(TAG_FILE, "Adding authority:"
1991 + " account=" + accountName
1992 + " accountType=" + accountType
1993 + " auth=" + authorityName
1994 + " package=" + packageName
1995 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001996 + " user=" + userId
1997 + " enabled=" + enabled
1998 + " syncable=" + syncable);
1999 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002000 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07002001 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002002 Log.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07002003 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002004 EndPoint info;
2005 if (accountName != null && authorityName != null) {
2006 info = new EndPoint(
2007 new Account(accountName, accountType),
2008 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07002009 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -07002010 info = new EndPoint(
2011 new ComponentName(packageName, className),
2012 userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07002013 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002014 authority = getOrCreateAuthorityLocked(info, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07002015 // If the version is 0 then we are upgrading from a file format that did not
2016 // know about periodic syncs. In that case don't clear the list since we
Matthew Williamsfa774182013-06-18 15:44:11 -07002017 // want the default, which is a daily periodic sync.
Fred Quintanac2e46912010-03-15 16:10:44 -07002018 // Otherwise clear out this default list since we will populate it later with
2019 // the periodic sync descriptions that are read from the configuration file.
2020 if (version > 0) {
2021 authority.periodicSyncs.clear();
2022 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002023 }
2024 if (authority != null) {
2025 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
2026 if ("unknown".equals(syncable)) {
2027 authority.syncable = -1;
2028 } else {
2029 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07002030 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002031 }
2032 } else {
2033 Log.w(TAG, "Failure adding authority: account="
2034 + accountName + " auth=" + authorityName
2035 + " enabled=" + enabled
2036 + " syncable=" + syncable);
2037 }
2038 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002039 return authority;
2040 }
2041
Matthew Williamsfa774182013-06-18 15:44:11 -07002042 /**
2043 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
2044 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002045 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002046 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002047 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07002048 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002049 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07002050 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002051 try {
2052 period = Long.parseLong(periodValue);
2053 } catch (NumberFormatException e) {
2054 Log.e(TAG, "error parsing the period of a periodic sync", e);
2055 return null;
2056 } catch (NullPointerException e) {
2057 Log.e(TAG, "the period of a periodic sync is null", e);
2058 return null;
2059 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002060 try {
2061 flextime = Long.parseLong(flexValue);
2062 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002063 flextime = calculateDefaultFlexTime(period);
Matthew Williams8ef22042013-07-26 12:56:39 -07002064 Log.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
2065 + ", using default: "
2066 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07002067 } catch (NullPointerException expected) {
2068 flextime = calculateDefaultFlexTime(period);
2069 Log.d(TAG, "No flex time specified for this sync, using a default. period: "
2070 + period + " flex: " + flextime);
2071 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002072 PeriodicSync periodicSync;
Matthew Williams8ef22042013-07-26 12:56:39 -07002073 if (authorityInfo.target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002074 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07002075 new PeriodicSync(authorityInfo.target.account,
2076 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002077 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07002078 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002079 } else {
2080 periodicSync =
2081 new PeriodicSync(
Matthew Williams8ef22042013-07-26 12:56:39 -07002082 authorityInfo.target.service,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002083 extras,
2084 period,
2085 flextime);
2086 }
2087 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002088 return periodicSync;
2089 }
2090
Matthew Williamsfa774182013-06-18 15:44:11 -07002091 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002092 String name = parser.getAttributeValue(null, "name");
2093 String type = parser.getAttributeValue(null, "type");
2094 String value1 = parser.getAttributeValue(null, "value1");
2095 String value2 = parser.getAttributeValue(null, "value2");
2096
2097 try {
2098 if ("long".equals(type)) {
2099 extras.putLong(name, Long.parseLong(value1));
2100 } else if ("integer".equals(type)) {
2101 extras.putInt(name, Integer.parseInt(value1));
2102 } else if ("double".equals(type)) {
2103 extras.putDouble(name, Double.parseDouble(value1));
2104 } else if ("float".equals(type)) {
2105 extras.putFloat(name, Float.parseFloat(value1));
2106 } else if ("boolean".equals(type)) {
2107 extras.putBoolean(name, Boolean.parseBoolean(value1));
2108 } else if ("string".equals(type)) {
2109 extras.putString(name, value1);
2110 } else if ("account".equals(type)) {
2111 extras.putParcelable(name, new Account(value1, value2));
2112 }
2113 } catch (NumberFormatException e) {
2114 Log.e(TAG, "error parsing bundle value", e);
2115 } catch (NullPointerException e) {
2116 Log.e(TAG, "error parsing bundle value", e);
2117 }
2118 }
2119
Dianne Hackborn231cc602009-04-27 17:10:36 -07002120 /**
2121 * Write all account information to the account file.
2122 */
2123 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002124 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002125 Log.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002126 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002127 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07002128
Dianne Hackborn231cc602009-04-27 17:10:36 -07002129 try {
2130 fos = mAccountInfoFile.startWrite();
2131 XmlSerializer out = new FastXmlSerializer();
2132 out.setOutput(fos, "utf-8");
2133 out.startDocument(null, true);
2134 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07002135
Dianne Hackborn231cc602009-04-27 17:10:36 -07002136 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07002137 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002138 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07002139 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002140
2141 // Write the Sync Automatically flags for each user
2142 final int M = mMasterSyncAutomatically.size();
2143 for (int m = 0; m < M; m++) {
2144 int userId = mMasterSyncAutomatically.keyAt(m);
2145 Boolean listen = mMasterSyncAutomatically.valueAt(m);
2146 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
2147 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
2148 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
2149 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002150 }
Costin Manolache360e4542009-09-04 13:36:04 -07002151
Dianne Hackborn231cc602009-04-27 17:10:36 -07002152 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07002153 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07002154 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002155 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002156 out.startTag(null, "authority");
2157 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002158 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002159 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002160 if (info.service == null) {
2161 out.attribute(null, "account", info.account.name);
2162 out.attribute(null, "type", info.account.type);
2163 out.attribute(null, "authority", info.provider);
Matthew Williamsfa774182013-06-18 15:44:11 -07002164 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002165 out.attribute(null, "package", info.service.getPackageName());
2166 out.attribute(null, "class", info.service.getClassName());
Matthew Williamsfa774182013-06-18 15:44:11 -07002167 }
Fred Quintana5e787c42009-08-16 23:13:53 -07002168 if (authority.syncable < 0) {
2169 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07002170 } else {
2171 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07002172 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002173 for (PeriodicSync periodicSync : authority.periodicSyncs) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002174 out.startTag(null, "periodicSync");
Matthew Williamsfa774182013-06-18 15:44:11 -07002175 out.attribute(null, "period", Long.toString(periodicSync.period));
2176 out.attribute(null, "flex", Long.toString(periodicSync.flexTime));
2177 final Bundle extras = periodicSync.extras;
2178 extrasToXml(out, extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002179 out.endTag(null, "periodicSync");
2180 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002181 out.endTag(null, "authority");
2182 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002183 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002184 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002185 mAccountInfoFile.finishWrite(fos);
2186 } catch (java.io.IOException e1) {
2187 Log.w(TAG, "Error writing accounts", e1);
2188 if (fos != null) {
2189 mAccountInfoFile.failWrite(fos);
2190 }
2191 }
2192 }
Costin Manolache360e4542009-09-04 13:36:04 -07002193
Dianne Hackborn231cc602009-04-27 17:10:36 -07002194 static int getIntColumn(Cursor c, String name) {
2195 return c.getInt(c.getColumnIndex(name));
2196 }
Costin Manolache360e4542009-09-04 13:36:04 -07002197
Dianne Hackborn231cc602009-04-27 17:10:36 -07002198 static long getLongColumn(Cursor c, String name) {
2199 return c.getLong(c.getColumnIndex(name));
2200 }
Costin Manolache360e4542009-09-04 13:36:04 -07002201
Dianne Hackborn231cc602009-04-27 17:10:36 -07002202 /**
2203 * Load sync engine state from the old syncmanager database, and then
2204 * erase it. Note that we don't deal with pending operations, active
2205 * sync, or history.
2206 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002207 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002208 // Look for old database to initialize from.
2209 File file = mContext.getDatabasePath("syncmanager.db");
2210 if (!file.exists()) {
2211 return;
2212 }
2213 String path = file.getPath();
2214 SQLiteDatabase db = null;
2215 try {
2216 db = SQLiteDatabase.openDatabase(path, null,
2217 SQLiteDatabase.OPEN_READONLY);
2218 } catch (SQLiteException e) {
2219 }
Costin Manolache360e4542009-09-04 13:36:04 -07002220
Dianne Hackborn231cc602009-04-27 17:10:36 -07002221 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002222 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002223
Dianne Hackborn231cc602009-04-27 17:10:36 -07002224 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07002225 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002226 Log.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07002227 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002228 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2229 qb.setTables("stats, status");
2230 HashMap<String,String> map = new HashMap<String,String>();
2231 map.put("_id", "status._id as _id");
2232 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002233 if (hasType) {
2234 map.put("account_type", "stats.account_type as account_type");
2235 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002236 map.put("authority", "stats.authority as authority");
2237 map.put("totalElapsedTime", "totalElapsedTime");
2238 map.put("numSyncs", "numSyncs");
2239 map.put("numSourceLocal", "numSourceLocal");
2240 map.put("numSourcePoll", "numSourcePoll");
2241 map.put("numSourceServer", "numSourceServer");
2242 map.put("numSourceUser", "numSourceUser");
2243 map.put("lastSuccessSource", "lastSuccessSource");
2244 map.put("lastSuccessTime", "lastSuccessTime");
2245 map.put("lastFailureSource", "lastFailureSource");
2246 map.put("lastFailureTime", "lastFailureTime");
2247 map.put("lastFailureMesg", "lastFailureMesg");
2248 map.put("pending", "pending");
2249 qb.setProjectionMap(map);
2250 qb.appendWhere("stats._id = status.stats_id");
2251 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002253 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002254 String accountType = hasType
2255 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002256 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002257 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002259 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002260 AuthorityInfo authority =
2261 this.getOrCreateAuthorityLocked(
2262 new EndPoint(new Account(accountName, accountType),
2263 authorityName,
2264 0 /* legacy is single-user */)
2265 , -1,
2266 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002267 if (authority != null) {
2268 int i = mSyncStatus.size();
2269 boolean found = false;
2270 SyncStatusInfo st = null;
2271 while (i > 0) {
2272 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002273 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002274 if (st.authorityId == authority.ident) {
2275 found = true;
2276 break;
2277 }
2278 }
2279 if (!found) {
2280 st = new SyncStatusInfo(authority.ident);
2281 mSyncStatus.put(authority.ident, st);
2282 }
2283 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2284 st.numSyncs = getIntColumn(c, "numSyncs");
2285 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2286 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2287 st.numSourceServer = getIntColumn(c, "numSourceServer");
2288 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002289 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002290 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2291 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2292 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2293 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2294 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2295 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 }
Costin Manolache360e4542009-09-04 13:36:04 -07002298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002299 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002300
Dianne Hackborn231cc602009-04-27 17:10:36 -07002301 // Retrieve the settings.
2302 qb = new SQLiteQueryBuilder();
2303 qb.setTables("settings");
2304 c = qb.query(db, null, null, null, null, null, null);
2305 while (c.moveToNext()) {
2306 String name = c.getString(c.getColumnIndex("name"));
2307 String value = c.getString(c.getColumnIndex("value"));
2308 if (name == null) continue;
2309 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002310 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002311 } else if (name.startsWith("sync_provider_")) {
2312 String provider = name.substring("sync_provider_".length(),
2313 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002314 int i = mAuthorities.size();
2315 while (i > 0) {
2316 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002317 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002318 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002319 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002320 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002321 }
2322 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 }
Costin Manolache360e4542009-09-04 13:36:04 -07002325
Dianne Hackborn231cc602009-04-27 17:10:36 -07002326 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002327
Dianne Hackborn231cc602009-04-27 17:10:36 -07002328 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002329
Dianne Hackborn231cc602009-04-27 17:10:36 -07002330 (new File(path)).delete();
2331 }
2332 }
Costin Manolache360e4542009-09-04 13:36:04 -07002333
Dianne Hackborn231cc602009-04-27 17:10:36 -07002334 public static final int STATUS_FILE_END = 0;
2335 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002336
Dianne Hackborn231cc602009-04-27 17:10:36 -07002337 /**
2338 * Read all sync status back in to the initial engine state.
2339 */
2340 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002341 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002342 Log.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002343 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002344 try {
2345 byte[] data = mStatusFile.readFully();
2346 Parcel in = Parcel.obtain();
2347 in.unmarshall(data, 0, data.length);
2348 in.setDataPosition(0);
2349 int token;
2350 while ((token=in.readInt()) != STATUS_FILE_END) {
2351 if (token == STATUS_FILE_ITEM) {
2352 SyncStatusInfo status = new SyncStatusInfo(in);
2353 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2354 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002355 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002356 Log.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002357 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002358 mSyncStatus.put(status.authorityId, status);
2359 }
2360 } else {
2361 // Ooops.
2362 Log.w(TAG, "Unknown status token: " + token);
2363 break;
2364 }
2365 }
2366 } catch (java.io.IOException e) {
2367 Log.i(TAG, "No initial status");
2368 }
2369 }
Costin Manolache360e4542009-09-04 13:36:04 -07002370
Dianne Hackborn231cc602009-04-27 17:10:36 -07002371 /**
2372 * Write all sync status to the sync status file.
2373 */
2374 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002375 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002376 Log.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002377 }
Costin Manolache360e4542009-09-04 13:36:04 -07002378
Dianne Hackborn231cc602009-04-27 17:10:36 -07002379 // The file is being written, so we don't need to have a scheduled
2380 // write until the next change.
2381 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002382
Dianne Hackborn231cc602009-04-27 17:10:36 -07002383 FileOutputStream fos = null;
2384 try {
2385 fos = mStatusFile.startWrite();
2386 Parcel out = Parcel.obtain();
2387 final int N = mSyncStatus.size();
2388 for (int i=0; i<N; i++) {
2389 SyncStatusInfo status = mSyncStatus.valueAt(i);
2390 out.writeInt(STATUS_FILE_ITEM);
2391 status.writeToParcel(out, 0);
2392 }
2393 out.writeInt(STATUS_FILE_END);
2394 fos.write(out.marshall());
2395 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002396
Dianne Hackborn231cc602009-04-27 17:10:36 -07002397 mStatusFile.finishWrite(fos);
2398 } catch (java.io.IOException e1) {
2399 Log.w(TAG, "Error writing status", e1);
2400 if (fos != null) {
2401 mStatusFile.failWrite(fos);
2402 }
2403 }
2404 }
Costin Manolache360e4542009-09-04 13:36:04 -07002405
Matthew Williamsba352712013-08-13 15:53:31 -07002406 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002407
Matthew Williamsba352712013-08-13 15:53:31 -07002408 /** Read all pending operations back in to the initial engine state. */
Dianne Hackborn231cc602009-04-27 17:10:36 -07002409 private void readPendingOperationsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002410 FileInputStream fis = null;
2411 if (!mPendingFile.getBaseFile().exists()) {
2412 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2413 Log.v(TAG_FILE, "No pending operation file.");
2414 return;
Matthew Williamsfa774182013-06-18 15:44:11 -07002415 }
2416 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002417 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002418 fis = mPendingFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07002419 XmlPullParser parser;
2420 parser = Xml.newPullParser();
Matthew Williamsfa774182013-06-18 15:44:11 -07002421 parser.setInput(fis, null);
Matthew Williamsba352712013-08-13 15:53:31 -07002422
Matthew Williamsfa774182013-06-18 15:44:11 -07002423 int eventType = parser.getEventType();
2424 while (eventType != XmlPullParser.START_TAG &&
2425 eventType != XmlPullParser.END_DOCUMENT) {
2426 eventType = parser.next();
Matthew Williamsfa774182013-06-18 15:44:11 -07002427 }
Matthew Williamsba352712013-08-13 15:53:31 -07002428 if (eventType == XmlPullParser.END_DOCUMENT) return; // Nothing to read.
Matthew Williamsfa774182013-06-18 15:44:11 -07002429
2430 String tagName = parser.getName();
Matthew Williamsba352712013-08-13 15:53:31 -07002431 do {
Matthew Williamsfa774182013-06-18 15:44:11 -07002432 PendingOperation pop = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07002433 if (eventType == XmlPullParser.START_TAG) {
2434 try {
2435 tagName = parser.getName();
2436 if (parser.getDepth() == 1 && "op".equals(tagName)) {
2437 // Verify version.
2438 String versionString =
2439 parser.getAttributeValue(null, XML_ATTR_VERSION);
2440 if (versionString == null ||
2441 Integer.parseInt(versionString) != PENDING_OPERATION_VERSION) {
2442 Log.w(TAG, "Unknown pending operation version " + versionString);
2443 throw new java.io.IOException("Unknown version.");
2444 }
2445 int authorityId = Integer.valueOf(parser.getAttributeValue(
2446 null, XML_ATTR_AUTHORITYID));
2447 boolean expedited = Boolean.valueOf(parser.getAttributeValue(
2448 null, XML_ATTR_EXPEDITED));
2449 int syncSource = Integer.valueOf(parser.getAttributeValue(
2450 null, XML_ATTR_SOURCE));
2451 int reason = Integer.valueOf(parser.getAttributeValue(
2452 null, XML_ATTR_REASON));
2453 AuthorityInfo authority = mAuthorities.get(authorityId);
2454 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2455 Log.v(TAG_FILE, authorityId + " " + expedited + " " + syncSource + " "
2456 + reason);
2457 }
2458 if (authority != null) {
2459 pop = new PendingOperation(
2460 authority, reason, syncSource, new Bundle(), expedited);
2461 pop.flatExtras = null; // No longer used.
2462 mPendingOperations.add(pop);
Matthew Williamsba352712013-08-13 15:53:31 -07002463 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002464 Log.v(TAG_FILE, "Adding pending op: "
2465 + pop.target
Matthew Williamsfa774182013-06-18 15:44:11 -07002466 + " src=" + pop.syncSource
2467 + " reason=" + pop.reason
2468 + " expedited=" + pop.expedited);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002469 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002470 } else {
2471 // Skip non-existent authority.
2472 pop = null;
2473 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2474 Log.v(TAG_FILE, "No authority found for " + authorityId
2475 + ", skipping");
Matthew Williamsfa774182013-06-18 15:44:11 -07002476 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002477 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002478 } else if (parser.getDepth() == 2 &&
2479 pop != null &&
2480 "extra".equals(tagName)) {
2481 parseExtra(parser, pop.extras);
Matthew Williamsfa774182013-06-18 15:44:11 -07002482 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002483 } catch (NumberFormatException e) {
2484 Log.d(TAG, "Invalid data in xml file.", e);
Matthew Williamsfa774182013-06-18 15:44:11 -07002485 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002486 }
Matthew Williamsba352712013-08-13 15:53:31 -07002487 eventType = parser.next();
2488 } while(eventType != XmlPullParser.END_DOCUMENT);
Matthew Williamsfa774182013-06-18 15:44:11 -07002489 } catch (java.io.IOException e) {
Matthew Williamsba352712013-08-13 15:53:31 -07002490 Log.w(TAG_FILE, "Error reading pending data.", e);
2491 } catch (XmlPullParserException e) {
2492 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2493 Log.w(TAG_FILE, "Error parsing pending ops xml.", e);
2494 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002495 } finally {
Matthew Williamsfa774182013-06-18 15:44:11 -07002496 if (fis != null) {
2497 try {
2498 fis.close();
2499 } catch (java.io.IOException e1) {}
2500 }
2501 }
2502 }
Matthew Williamsba352712013-08-13 15:53:31 -07002503
Dianne Hackborn231cc602009-04-27 17:10:36 -07002504 static private byte[] flattenBundle(Bundle bundle) {
2505 byte[] flatData = null;
2506 Parcel parcel = Parcel.obtain();
2507 try {
2508 bundle.writeToParcel(parcel, 0);
2509 flatData = parcel.marshall();
2510 } finally {
2511 parcel.recycle();
2512 }
2513 return flatData;
2514 }
Costin Manolache360e4542009-09-04 13:36:04 -07002515
Dianne Hackborn231cc602009-04-27 17:10:36 -07002516 static private Bundle unflattenBundle(byte[] flatData) {
2517 Bundle bundle;
2518 Parcel parcel = Parcel.obtain();
2519 try {
2520 parcel.unmarshall(flatData, 0, flatData.length);
2521 parcel.setDataPosition(0);
2522 bundle = parcel.readBundle();
2523 } catch (RuntimeException e) {
2524 // A RuntimeException is thrown if we were unable to parse the parcel.
2525 // Create an empty parcel in this case.
2526 bundle = new Bundle();
2527 } finally {
2528 parcel.recycle();
2529 }
2530 return bundle;
2531 }
Costin Manolache360e4542009-09-04 13:36:04 -07002532
Matthew Williams8ef22042013-07-26 12:56:39 -07002533 private static final String XML_ATTR_VERSION = "version";
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002534 private static final String XML_ATTR_AUTHORITYID = "authority_id";
2535 private static final String XML_ATTR_SOURCE = "source";
2536 private static final String XML_ATTR_EXPEDITED = "expedited";
2537 private static final String XML_ATTR_REASON = "reason";
2538
2539 /**
2540 * Write all currently pending ops to the pending ops file.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002541 */
2542 private void writePendingOperationsLocked() {
2543 final int N = mPendingOperations.size();
2544 FileOutputStream fos = null;
2545 try {
2546 if (N == 0) {
2547 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)){
2548 Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2549 }
2550 mPendingFile.truncate();
2551 return;
2552 }
2553 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2554 Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2555 }
2556 fos = mPendingFile.startWrite();
2557 XmlSerializer out = new FastXmlSerializer();
2558 out.setOutput(fos, "utf-8");
2559 out.startDocument(null, true);
2560 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2561
2562 out.startTag(null, "pending");
2563 out.attribute(null, "version", Integer.toString(PENDING_OPERATION_VERSION));
2564
2565 for (int i = 0; i < N; i++) {
2566 PendingOperation pop = mPendingOperations.get(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002567 writePendingOperationLocked(pop, out);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002568 }
2569 out.endTag(null, "pending");
2570 out.endDocument();
2571 mPendingFile.finishWrite(fos);
2572 } catch (java.io.IOException e1) {
2573 Log.w(TAG, "Error writing pending operations", e1);
2574 if (fos != null) {
2575 mPendingFile.failWrite(fos);
2576 }
2577 }
2578 }
2579
Matthew Williams8ef22042013-07-26 12:56:39 -07002580 /** Write all currently pending ops to the pending ops file. */
2581 private void writePendingOperationLocked(PendingOperation pop, XmlSerializer out)
2582 throws IOException {
2583 // Pending operation.
2584 out.startTag(null, "op");
2585
2586 out.attribute(null, XML_ATTR_VERSION, Integer.toString(PENDING_OPERATION_VERSION));
2587 out.attribute(null, XML_ATTR_AUTHORITYID, Integer.toString(pop.authorityId));
2588 out.attribute(null, XML_ATTR_SOURCE, Integer.toString(pop.syncSource));
2589 out.attribute(null, XML_ATTR_EXPEDITED, Boolean.toString(pop.expedited));
2590 out.attribute(null, XML_ATTR_REASON, Integer.toString(pop.reason));
2591 extrasToXml(out, pop.extras);
2592
2593 out.endTag(null, "op");
2594 }
2595
2596 /**
2597 * Append the given operation to the pending ops file; if unable to,
2598 * write all pending ops.
2599 */
2600 private void appendPendingOperationLocked(PendingOperation op) {
2601 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2602 Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2603 }
2604 FileOutputStream fos = null;
2605 try {
2606 fos = mPendingFile.openAppend();
2607 } catch (java.io.IOException e) {
2608 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2609 Log.v(TAG, "Failed append; writing full file");
2610 }
2611 writePendingOperationsLocked();
2612 return;
2613 }
2614
2615 try {
2616 XmlSerializer out = new FastXmlSerializer();
2617 out.setOutput(fos, "utf-8");
2618 writePendingOperationLocked(op, out);
2619 out.endDocument();
2620 mPendingFile.finishWrite(fos);
2621 } catch (java.io.IOException e1) {
2622 Log.w(TAG, "Error writing appending operation", e1);
2623 mPendingFile.failWrite(fos);
2624 } finally {
2625 try {
2626 fos.close();
2627 } catch (IOException e) {}
2628 }
2629 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002630
Matthew Williamsfa774182013-06-18 15:44:11 -07002631 private void extrasToXml(XmlSerializer out, Bundle extras) throws java.io.IOException {
2632 for (String key : extras.keySet()) {
2633 out.startTag(null, "extra");
2634 out.attribute(null, "name", key);
2635 final Object value = extras.get(key);
2636 if (value instanceof Long) {
2637 out.attribute(null, "type", "long");
2638 out.attribute(null, "value1", value.toString());
2639 } else if (value instanceof Integer) {
2640 out.attribute(null, "type", "integer");
2641 out.attribute(null, "value1", value.toString());
2642 } else if (value instanceof Boolean) {
2643 out.attribute(null, "type", "boolean");
2644 out.attribute(null, "value1", value.toString());
2645 } else if (value instanceof Float) {
2646 out.attribute(null, "type", "float");
2647 out.attribute(null, "value1", value.toString());
2648 } else if (value instanceof Double) {
2649 out.attribute(null, "type", "double");
2650 out.attribute(null, "value1", value.toString());
2651 } else if (value instanceof String) {
2652 out.attribute(null, "type", "string");
2653 out.attribute(null, "value1", value.toString());
2654 } else if (value instanceof Account) {
2655 out.attribute(null, "type", "account");
2656 out.attribute(null, "value1", ((Account)value).name);
2657 out.attribute(null, "value2", ((Account)value).type);
2658 }
2659 out.endTag(null, "extra");
2660 }
2661 }
2662
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002663 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2664 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2665 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002666 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002667 } else {
2668 SyncRequest.Builder req =
2669 new SyncRequest.Builder()
Matthew Williams8ef22042013-07-26 12:56:39 -07002670 .syncOnce(0, 0)
2671 .setExtras(extras);
2672 if (authorityInfo.target.target_provider) {
2673 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002674 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -07002675 req.setSyncAdapter(authorityInfo.target.service);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002676 }
2677 ContentResolver.requestSync(req.build());
2678 }
2679 }
2680
Alon Albert57286f92012-10-09 14:21:38 -07002681 private void requestSync(Account account, int userId, int reason, String authority,
2682 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002683 // If this is happening in the system process, then call the syncrequest listener
2684 // to make a request back to the SyncManager directly.
2685 // If this is probably a test instance, then call back through the ContentResolver
2686 // which will know which userId to apply based on the Binder id.
2687 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2688 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002689 mSyncRequestListener.onSyncRequest(
Matthew Williams8ef22042013-07-26 12:56:39 -07002690 new EndPoint(account, authority, userId),
2691 reason,
2692 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002693 } else {
2694 ContentResolver.requestSync(account, authority, extras);
2695 }
2696 }
2697
Dianne Hackborn231cc602009-04-27 17:10:36 -07002698 public static final int STATISTICS_FILE_END = 0;
2699 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2700 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002701
Dianne Hackborn231cc602009-04-27 17:10:36 -07002702 /**
2703 * Read all sync statistics back in to the initial engine state.
2704 */
2705 private void readStatisticsLocked() {
2706 try {
2707 byte[] data = mStatisticsFile.readFully();
2708 Parcel in = Parcel.obtain();
2709 in.unmarshall(data, 0, data.length);
2710 in.setDataPosition(0);
2711 int token;
2712 int index = 0;
2713 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2714 if (token == STATISTICS_FILE_ITEM
2715 || token == STATISTICS_FILE_ITEM_OLD) {
2716 int day = in.readInt();
2717 if (token == STATISTICS_FILE_ITEM_OLD) {
2718 day = day - 2009 + 14245; // Magic!
2719 }
2720 DayStats ds = new DayStats(day);
2721 ds.successCount = in.readInt();
2722 ds.successTime = in.readLong();
2723 ds.failureCount = in.readInt();
2724 ds.failureTime = in.readLong();
2725 if (index < mDayStats.length) {
2726 mDayStats[index] = ds;
2727 index++;
2728 }
2729 } else {
2730 // Ooops.
2731 Log.w(TAG, "Unknown stats token: " + token);
2732 break;
2733 }
2734 }
2735 } catch (java.io.IOException e) {
2736 Log.i(TAG, "No initial statistics");
2737 }
2738 }
Costin Manolache360e4542009-09-04 13:36:04 -07002739
Dianne Hackborn231cc602009-04-27 17:10:36 -07002740 /**
2741 * Write all sync statistics to the sync status file.
2742 */
2743 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002744 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2745 Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
2746 }
Costin Manolache360e4542009-09-04 13:36:04 -07002747
Dianne Hackborn231cc602009-04-27 17:10:36 -07002748 // The file is being written, so we don't need to have a scheduled
2749 // write until the next change.
2750 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002751
Dianne Hackborn231cc602009-04-27 17:10:36 -07002752 FileOutputStream fos = null;
2753 try {
2754 fos = mStatisticsFile.startWrite();
2755 Parcel out = Parcel.obtain();
2756 final int N = mDayStats.length;
2757 for (int i=0; i<N; i++) {
2758 DayStats ds = mDayStats[i];
2759 if (ds == null) {
2760 break;
2761 }
2762 out.writeInt(STATISTICS_FILE_ITEM);
2763 out.writeInt(ds.day);
2764 out.writeInt(ds.successCount);
2765 out.writeLong(ds.successTime);
2766 out.writeInt(ds.failureCount);
2767 out.writeLong(ds.failureTime);
2768 }
2769 out.writeInt(STATISTICS_FILE_END);
2770 fos.write(out.marshall());
2771 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002772
Dianne Hackborn231cc602009-04-27 17:10:36 -07002773 mStatisticsFile.finishWrite(fos);
2774 } catch (java.io.IOException e1) {
2775 Log.w(TAG, "Error writing stats", e1);
2776 if (fos != null) {
2777 mStatisticsFile.failWrite(fos);
2778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 }
2780 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002781
2782 /**
2783 * Dump state of PendingOperations.
2784 */
2785 public void dumpPendingOperations(StringBuilder sb) {
2786 sb.append("Pending Ops: ").append(mPendingOperations.size()).append(" operation(s)\n");
2787 for (PendingOperation pop : mPendingOperations) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002788 sb.append("(info: " + pop.target.toString())
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002789 .append(", extras: " + pop.extras)
Matthew Williamsfa774182013-06-18 15:44:11 -07002790 .append(")\n");
2791 }
2792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793}