List of usage examples for android.provider CalendarContract AUTHORITY
String AUTHORITY
To view the source code for android.provider CalendarContract AUTHORITY.
Click Source Link
From source file:com.nineash.hutsync.client.NetworkUtilities.java
private static long getCalendar(Account account) { // Find the Last.fm calendar if we've got one Uri calenderUri = Calendars.CONTENT_URI.buildUpon() .appendQueryParameter(Calendars.ACCOUNT_NAME, account.name) .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type).build(); Cursor c1 = mContentResolver.query(calenderUri, new String[] { BaseColumns._ID }, null, null, null); if (c1.moveToNext()) { long ret = c1.getLong(0); c1.close();/*from w w w . j a v a 2 s .co m*/ return ret; } else { ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Calendars.CONTENT_URI .buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") .appendQueryParameter(Calendars.ACCOUNT_NAME, account.name) .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type).build()); builder.withValue(Calendars.ACCOUNT_NAME, account.name); builder.withValue(Calendars.ACCOUNT_TYPE, account.type); builder.withValue(Calendars.NAME, "Pizza Hut Shifts"); builder.withValue(Calendars.CALENDAR_DISPLAY_NAME, "Pizza Hut Shifts"); builder.withValue(Calendars.CALENDAR_COLOR, 0xD51007); builder.withValue(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ); builder.withValue(Calendars.OWNER_ACCOUNT, account.name); builder.withValue(Calendars.SYNC_EVENTS, 1); operationList.add(builder.build()); try { mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return -1; } c1.close(); return getCalendar(account); } }
From source file:saschpe.birthdays.service.CalendarSyncService.java
private static void applyBatchOperation(ContentResolver cr, ArrayList<ContentProviderOperation> operations) { try {//from w w w.j a v a 2 s . c o m Log.d(TAG, "Applying calendar batch operation"); cr.applyBatch(CalendarContract.AUTHORITY, operations); Log.d(TAG, "Successfully applied calendar batch operation"); } catch (Exception e) { Log.e(TAG, "Failed to apply calendar batch operation"); } }
From source file:at.bitfire.davdroid.AccountSettings.java
@SuppressWarnings({ "Recycle", "unused" }) private void update_2_3() { // Don't show a warning for Android updates anymore accountManager.setUserData(account, "last_android_version", null); Long serviceCardDAV = null, serviceCalDAV = null; ServiceDB.OpenHelper dbHelper = new ServiceDB.OpenHelper(context); try {//from w w w. ja v a 2 s . com SQLiteDatabase db = dbHelper.getWritableDatabase(); // we have to create the WebDAV Service database only from the old address book, calendar and task list URLs // CardDAV: migrate address books ContentProviderClient client = context.getContentResolver() .acquireContentProviderClient(ContactsContract.AUTHORITY); if (client != null) try { LocalAddressBook addrBook = new LocalAddressBook(account, client); String url = addrBook.getURL(); if (url != null) { App.log.fine("Migrating address book " + url); // insert CardDAV service ContentValues values = new ContentValues(); values.put(Services.ACCOUNT_NAME, account.name); values.put(Services.SERVICE, Services.SERVICE_CARDDAV); serviceCardDAV = db.insert(Services._TABLE, null, values); // insert address book values.clear(); values.put(Collections.SERVICE_ID, serviceCardDAV); values.put(Collections.URL, url); values.put(Collections.SYNC, 1); db.insert(Collections._TABLE, null, values); // insert home set HttpUrl homeSet = HttpUrl.parse(url).resolve("../"); values.clear(); values.put(HomeSets.SERVICE_ID, serviceCardDAV); values.put(HomeSets.URL, homeSet.toString()); db.insert(HomeSets._TABLE, null, values); } } catch (ContactsStorageException e) { App.log.log(Level.SEVERE, "Couldn't migrate address book", e); } finally { client.release(); } // CalDAV: migrate calendars + task lists Set<String> collections = new HashSet<>(); Set<HttpUrl> homeSets = new HashSet<>(); client = context.getContentResolver().acquireContentProviderClient(CalendarContract.AUTHORITY); if (client != null) try { LocalCalendar calendars[] = (LocalCalendar[]) LocalCalendar.find(account, client, LocalCalendar.Factory.INSTANCE, null, null); for (LocalCalendar calendar : calendars) { String url = calendar.getName(); App.log.fine("Migrating calendar " + url); collections.add(url); homeSets.add(HttpUrl.parse(url).resolve("../")); } } catch (CalendarStorageException e) { App.log.log(Level.SEVERE, "Couldn't migrate calendars", e); } finally { client.release(); } TaskProvider provider = LocalTaskList.acquireTaskProvider(context.getContentResolver()); if (provider != null) try { LocalTaskList[] taskLists = (LocalTaskList[]) LocalTaskList.find(account, provider, LocalTaskList.Factory.INSTANCE, null, null); for (LocalTaskList taskList : taskLists) { String url = taskList.getSyncId(); App.log.fine("Migrating task list " + url); collections.add(url); homeSets.add(HttpUrl.parse(url).resolve("../")); } } catch (CalendarStorageException e) { App.log.log(Level.SEVERE, "Couldn't migrate task lists", e); } finally { provider.close(); } if (!collections.isEmpty()) { // insert CalDAV service ContentValues values = new ContentValues(); values.put(Services.ACCOUNT_NAME, account.name); values.put(Services.SERVICE, Services.SERVICE_CALDAV); serviceCalDAV = db.insert(Services._TABLE, null, values); // insert collections for (String url : collections) { values.clear(); values.put(Collections.SERVICE_ID, serviceCalDAV); values.put(Collections.URL, url); values.put(Collections.SYNC, 1); db.insert(Collections._TABLE, null, values); } // insert home sets for (HttpUrl homeSet : homeSets) { values.clear(); values.put(HomeSets.SERVICE_ID, serviceCalDAV); values.put(HomeSets.URL, homeSet.toString()); db.insert(HomeSets._TABLE, null, values); } } } finally { dbHelper.close(); } // initiate service detection (refresh) to get display names, colors etc. Intent refresh = new Intent(context, DavService.class); refresh.setAction(DavService.ACTION_REFRESH_COLLECTIONS); if (serviceCardDAV != null) { refresh.putExtra(DavService.EXTRA_DAV_SERVICE_ID, serviceCardDAV); context.startService(refresh); } if (serviceCalDAV != null) { refresh.putExtra(DavService.EXTRA_DAV_SERVICE_ID, serviceCalDAV); context.startService(refresh); } }
From source file:saschpe.birthdays.service.CalendarSyncService.java
/** * Updates the calendar color/* w w w. j a v a 2 s .c o m*/ */ public static void updateCalendarColor(Context context) { int color = PreferencesHelper.getCalendarColor(context); ContentResolver cr = context.getContentResolver(); Uri uri = ContentUris.withAppendedId(getCalendarUri(context, CalendarContract.Calendars.CONTENT_URI), getCalendar(context)); Log.d(TAG, "Updating calendar " + uri.toString() + " color " + color); ContentProviderClient client = cr.acquireContentProviderClient(CalendarContract.AUTHORITY); ContentValues values = new ContentValues(); values.put(CalendarContract.Calendars.CALENDAR_COLOR, color); try { client.update(uri, values, null, null); } catch (RemoteException e) { Log.e(TAG, "Failed to update calendar color!", e); } client.release(); }
From source file:com.nineash.hutsync.client.NetworkUtilities.java
/** * Perform 2-way sync with the server-side contacts. We send a request that * includes all the locally-dirty contacts so that the server can process * those changes, and we receive (and return) a list of contacts that were * updated on the server-side that need to be updated locally. * * @param account The account being synced * @param authtoken The authtoken stored in the AccountManager for this * account//from w ww .j a v a2 s . c o m * @param serverSyncState A token returned from the server on the last sync * @param dirtyContacts A list of the contacts to send to the server * @return A list of contacts that we need to update locally */ public static void syncCalendar(Context context, Account account, String authtoken, long serverSyncState) throws JSONException, ParseException, IOException, AuthenticationException { ArrayList<SerializableCookie> myCookies; CookieStore cookieStore = new BasicCookieStore(); DefaultHttpClient hClient = getHttpClient(context); mContentResolver = context.getContentResolver(); final String[] weeknames = { "rota_this_week", "rota_next_week" }; long calendar_id = getCalendar(account); if (calendar_id == -1) { Log.e("CalendarSyncAdapter", "Unable to create HutSync event calendar"); return; } try { myCookies = (ArrayList<SerializableCookie>) fromString(authtoken); } catch (final IOException e) { Log.e(TAG, "IOException when expanding authtoken", e); return; } catch (final ClassNotFoundException e) { Log.e(TAG, "ClassNotFoundException when expanding authtoken", e); return; } for (SerializableCookie cur_cookie : myCookies) { cookieStore.addCookie(cur_cookie.getCookie()); } hClient.setCookieStore(cookieStore); Log.i(TAG, "Syncing to: " + SYNC_CONTACTS_URI); HttpGet httpget = new HttpGet(SYNC_CONTACTS_URI); final HttpResponse resp = hClient.execute(httpget); final String response = EntityUtils.toString(resp.getEntity()); HashMap<Long, SyncEntry> localEvents = new HashMap<Long, SyncEntry>(); ArrayList<Event> events = new ArrayList<Event>(); Pattern p = Pattern.compile("background-color:(#[[a-f][A-F][0-9]]{6})"); Pattern ps = Pattern .compile(".calendar-key span.(\\S+) \\{ background-color:(#[[a-f][A-F][0-9]]{6}); color:#fff; \\}"); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { //check we are still logged in //if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { // Log.e(TAG, "Authentication exception in sending dirty contacts"); // throw new AuthenticationException(); //} //if we are logged in Map<String, String> shift_types = new HashMap<String, String>(); int length = weeknames.length; Document doc = Jsoup.parse(response); String full_name = doc.select("a[href*=" + account.name + "/profile]").first().text(); AccountManager mAccountManager = AccountManager.get(context); Account[] the_accounts = mAccountManager.getAccountsByType(Constants.ACCOUNT_TYPE); boolean multiple_accounts = (the_accounts.length > 1); Elements the_styles = doc.select("style"); for (Element the_style : the_styles) { String st_txt = the_style.html(); Matcher ms = ps.matcher(st_txt); while (ms.find()) { // Find each match in turn; String can't do this. String cname = ms.group(1); // Access a submatch group; String can't do this. String ccol = ms.group(2); String rname = doc.select("span." + cname).first().text(); Log.i(TAG, "LOOK: " + cname + ", " + ccol + ", " + rname); shift_types.put(ccol, rname); } } for (int w = 0; w < weeknames.length; w++) { Elements the_dates = doc.select("div.homepage div.accord-content table[id=" + weeknames[w] + "] tr.heading th:not(.skipStyles)"); //for (Element hidden : the_dates) { //0 is Mon, 6 is Sun Element the_date = the_dates.first(); //figure out the year for the Monday. String str_v = the_date.text(); String[] str_sub = str_v.split(" "); str_sub[1] = str_sub[1].trim(); String[] date_split = str_sub[1].split("/"); Calendar c = Calendar.getInstance(); int this_month = c.get(Calendar.MONTH) + 1; int monday_month = Integer.parseInt(date_split[1]); int this_year = c.get(Calendar.YEAR); int monday_year = this_year; if (this_month > monday_month) { monday_year++; } else if (this_month < monday_month) { monday_year--; } SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); Date date = new Date(); if (str_v != null && !str_v.isEmpty()) { String this_date = str_sub[1] + "/" + monday_year; //we need to figure out the year - sometimes its next year try { date = format.parse(this_date); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.i(TAG, "Dates: " + this_date + " - " + date); } //} for (int i = 1; i < 8; ++i) { //1 is monday, 7 is sunday Elements hiddens = doc.select("div.homepage div.accord-content table[id=" + weeknames[w] + "] td:eq(" + Integer.toString(i) + "):not(.skipStyles) div.timeElem"); int add_days = i - 1; for (Element hidden : hiddens) { String str = hidden.text(); if (str != null && !str.isEmpty()) { String style = hidden.attr("style"); String bg_col = ""; Matcher m = p.matcher(style); if (m.find()) { bg_col = m.group(1); // Access a submatch group; String can't do this. } Log.i(TAG, "Time: " + str + "(" + bg_col + ")"); String ev_description = ""; //Location too? if (multiple_accounts) ev_description += full_name + "\n\n"; String[] times = str.split(" - "); String[] start_time = times[0].split(":"); String[] end_time = times[1].split(":"); int add_start_hours = Integer.parseInt(start_time[0]); int add_start_minutes = Integer.parseInt(start_time[1]); int add_finish_hours = Integer.parseInt(end_time[0]); int add_finish_minutes = Integer.parseInt(end_time[1]); String ev_shiftType = ""; if (bg_col != null && !bg_col.isEmpty()) { ev_shiftType = (String) shift_types.get(bg_col); } else { ev_shiftType = "Other"; } String ev_title = ev_shiftType + " Shift"; c.setTime(date); c.add(Calendar.DATE, add_days); c.add(Calendar.HOUR_OF_DAY, add_start_hours); c.add(Calendar.MINUTE, add_start_minutes); Date startDate = c.getTime(); long ev_id = startDate.getTime(); c.setTime(date); c.add(Calendar.DATE, add_days); if (add_finish_hours < add_start_hours) { //shift rolls to next day c.add(Calendar.HOUR_OF_DAY, 24); ev_description += "Shift finishes at " + times[1] + " on the next day\n\n"; } else { c.add(Calendar.HOUR_OF_DAY, add_finish_hours); c.add(Calendar.MINUTE, add_finish_minutes); } Date endDate = c.getTime(); Event ev = new Event(ev_id, ev_title, startDate, endDate, ev_description, ev_shiftType); events.add(ev); Log.i(TAG, "Event: " + ev); } } } } //next merge adjacent shifts SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); Event prev_event = null; for (Iterator<Event> it = events.iterator(); it.hasNext();) { Event cur_event = it.next(); if (prev_event != null) { if (prev_event.getEndDate().compareTo(cur_event.getStartDate()) == 0) { prev_event.setDescription(prev_event.getDescription() + "Merged consecutive shifts:\n" + timeFormat.format(prev_event.getStartDate()) + " to " + timeFormat.format(prev_event.getEndDate()) + " (" + prev_event.getShiftType() + ")\n" + timeFormat.format(cur_event.getStartDate()) + " to " + timeFormat.format(cur_event.getEndDate()) + " (" + cur_event.getShiftType() + ")\n\n"); prev_event.setEndDate(cur_event.getEndDate()); //TODO: only merge if other + FOH/BOH, note times in new description it.remove(); } } prev_event = cur_event; } //next, load local events Cursor c1 = mContentResolver.query( Events.CONTENT_URI.buildUpon().appendQueryParameter(Events.ACCOUNT_NAME, account.name) .appendQueryParameter(Events.ACCOUNT_TYPE, account.type).build(), new String[] { Events._ID, Events._SYNC_ID }, Events.CALENDAR_ID + "=?", new String[] { String.valueOf(calendar_id) }, null); while (c1 != null && c1.moveToNext()) { //if(is_full_sync) { // deleteEvent(context, account, c1.getLong(0)); //} else { SyncEntry entry = new SyncEntry(); entry.raw_id = c1.getLong(0); localEvents.put(c1.getLong(1), entry); //} } c1.close(); try { ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); for (Event event : events) { if (localEvents.containsKey(Long.valueOf(event.getId()))) { SyncEntry entry = localEvents.get(Long.valueOf(event.getId())); operationList.add(updateEvent(calendar_id, account, event, entry.raw_id)); } else { operationList.add(updateEvent(calendar_id, account, event, -1)); } if (operationList.size() >= 50) { try { mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList); } catch (Exception e) { e.printStackTrace(); } operationList.clear(); } } if (operationList.size() > 0) { try { mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); return; } } else { Log.e(TAG, "Server error in sending dirty contacts: " + resp.getStatusLine()); throw new IOException(); } }
From source file:at.bitfire.davdroid.ui.AccountActivity.java
protected static void requestSync(Account account) { String authorities[] = { ContactsContract.AUTHORITY, CalendarContract.AUTHORITY, TaskProvider.ProviderName.OpenTasks.authority }; for (String authority : authorities) { Bundle extras = new Bundle(); extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); // manual sync extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); // run immediately (don't queue) ContentResolver.requestSync(account, authority, extras); }/*from ww w .ja va 2 s. c o m*/ }
From source file:com.android.exchange.EasAccountService.java
private void runPingLoop() throws IOException, StaleFolderListException, IllegalHeartbeatException, CommandStatusException { int pingHeartbeat = mPingHeartbeat; userLog("runPingLoop"); // Do push for all sync services here long endTime = System.currentTimeMillis() + (30 * DateUtils.MINUTE_IN_MILLIS); HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>(); ArrayList<String> readyMailboxes = new ArrayList<String>(); ArrayList<String> notReadyMailboxes = new ArrayList<String>(); int pingWaitCount = 0; long inboxId = -1; android.accounts.Account amAccount = new android.accounts.Account(mAccount.mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE); while ((System.currentTimeMillis() < endTime) && !isStopped()) { // Count of pushable mailboxes int pushCount = 0; // Count of mailboxes that can be pushed right now int canPushCount = 0; // Count of uninitialized boxes int uninitCount = 0; Serializer s = new Serializer(); Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX, null, null);//www.j a v a2 s. c om if (c == null) throw new ProviderUnavailableException(); notReadyMailboxes.clear(); readyMailboxes.clear(); // Look for an inbox, and remember its id if (inboxId == -1) { inboxId = Mailbox.findMailboxOfType(mContext, mAccount.mId, Mailbox.TYPE_INBOX); } try { // Loop through our pushed boxes seeing what is available to push while (c.moveToNext()) { pushCount++; // Two requirements for push: // 1) ExchangeService tells us the mailbox is syncable (not running/not stopped) // 2) The syncKey isn't "0" (i.e. it's synced at least once) long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN); String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); // See what type of box we've got and get authority int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN); String authority = EmailContent.AUTHORITY; switch (mailboxType) { case Mailbox.TYPE_CALENDAR: authority = CalendarContract.AUTHORITY; break; case Mailbox.TYPE_CONTACTS: authority = ContactsContract.AUTHORITY; break; } // See whether we can ping for this mailbox int pingStatus; if (!ContentResolver.getSyncAutomatically(amAccount, authority)) { pingStatus = ExchangeService.PING_STATUS_DISABLED; } else { pingStatus = ExchangeService.pingStatus(mailboxId); } if (pingStatus == ExchangeService.PING_STATUS_OK) { String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN); if ((syncKey == null) || syncKey.equals("0")) { // We can't push until the initial sync is done pushCount--; uninitCount++; continue; } if (canPushCount++ == 0) { // Initialize the Ping command s.start(Tags.PING_PING) .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat)) .start(Tags.PING_FOLDERS); } String folderClass = getTargetCollectionClassFromCursor(c); s.start(Tags.PING_FOLDER).data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN)) .data(Tags.PING_CLASS, folderClass).end(); readyMailboxes.add(mailboxName); } else if ((pingStatus == ExchangeService.PING_STATUS_RUNNING) || (pingStatus == ExchangeService.PING_STATUS_WAITING)) { notReadyMailboxes.add(mailboxName); } else if (pingStatus == ExchangeService.PING_STATUS_UNABLE) { pushCount--; userLog(mailboxName, " in error state; ignore"); continue; } else if (pingStatus == ExchangeService.PING_STATUS_DISABLED) { pushCount--; userLog(mailboxName, " disabled by user; ignore"); continue; } } } finally { c.close(); } if (Eas.USER_LOG) { if (!notReadyMailboxes.isEmpty()) { userLog("Ping not ready for: " + notReadyMailboxes); } if (!readyMailboxes.isEmpty()) { userLog("Ping ready for: " + readyMailboxes); } } // If we've waited 10 seconds or more, just ping with whatever boxes are ready // But use a shorter than normal heartbeat boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5); if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) { // If all pingable boxes are ready for push, send Ping to the server s.end().end().done(); pingWaitCount = 0; mPostAborted = false; mPostReset = false; // If we've been stopped, this is a good time to return if (isStopped()) return; long pingTime = SystemClock.elapsedRealtime(); try { // Send the ping, wrapped by appropriate timeout/alarm if (forcePing) { userLog("Forcing ping after waiting for all boxes to be ready"); } EasResponse resp = sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat); try { int code = resp.getStatus(); userLog("Ping response: ", code); // If we're not allowed to sync (e.g. roaming policy), terminate gracefully // now; otherwise we might start a sync based on the response if (!ExchangeService.canAutoSync(mAccount)) { stop(); } // Return immediately if we've been asked to stop during the ping if (isStopped()) { userLog("Stopping pingLoop"); return; } if (code == HttpStatus.SC_OK) { if (!resp.isEmpty()) { InputStream is = resp.getInputStream(); int pingResult = parsePingResult(is, mContentResolver, pingErrorMap); // If our ping completed (status = 1), and wasn't forced and we're // not at the maximum, try increasing timeout by two minutes if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) { if (pingHeartbeat > mPingHighWaterMark) { mPingHighWaterMark = pingHeartbeat; userLog("Setting high water mark at: ", mPingHighWaterMark); } if ((pingHeartbeat < mPingMaxHeartbeat) && !mPingHeartbeatDropped) { pingHeartbeat += PING_HEARTBEAT_INCREMENT; if (pingHeartbeat > mPingMaxHeartbeat) { pingHeartbeat = mPingMaxHeartbeat; } userLog("Increase ping heartbeat to ", pingHeartbeat, "s"); } } else if (pingResult == PROTOCOL_PING_STATUS_BAD_PARAMETERS || pingResult == PROTOCOL_PING_STATUS_RETRY) { // These errors appear to be server-related (I've seen a bad // parameters result with known good parameters...) userLog("Server error during Ping: " + pingResult); // Act as if we have an IOException (backoff, etc.) throw new IOException(); } // Make sure to clear out any pending sync errors ExchangeService.removeFromSyncErrorMap(mMailboxId); } else { userLog("Ping returned empty result; throwing IOException"); // Act as if we have an IOException (backoff, etc.) throw new IOException(); } } else if (resp.isAuthError()) { mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE; userLog("Authorization error during Ping: ", code); throw new IOException(); } } finally { resp.close(); } } catch (IOException e) { String message = e.getMessage(); // If we get the exception that is indicative of a NAT timeout and if we // haven't yet "fixed" the timeout, back off by two minutes and "fix" it boolean hasMessage = message != null; userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]")); if (mPostReset) { // Nothing to do in this case; this is ExchangeService telling us to try // another ping. } else if (mPostAborted || isLikelyNatFailure(message)) { long pingLength = SystemClock.elapsedRealtime() - pingTime; if ((pingHeartbeat > mPingMinHeartbeat) && (pingHeartbeat > mPingHighWaterMark)) { pingHeartbeat -= PING_HEARTBEAT_INCREMENT; mPingHeartbeatDropped = true; if (pingHeartbeat < mPingMinHeartbeat) { pingHeartbeat = mPingMinHeartbeat; } userLog("Decreased ping heartbeat to ", pingHeartbeat, "s"); } else if (mPostAborted) { // There's no point in throwing here; this can happen in two cases // 1) An alarm, which indicates minutes without activity; no sense // backing off // 2) ExchangeService abort, due to sync of mailbox. Again, we want to // keep on trying to ping userLog("Ping aborted; retry"); } else if (pingLength < 2000) { userLog("Abort or NAT type return < 2 seconds; throwing IOException"); throw e; } else { userLog("NAT type IOException"); } } else if (hasMessage && message.contains("roken pipe")) { // The "broken pipe" error (uppercase or lowercase "b") seems to be an // internal error, so let's not throw an exception (which leads to delays) // but rather simply run through the loop again } else { throw e; } } } else if (forcePing) { // In this case, there aren't any boxes that are pingable, but there are boxes // waiting (for IOExceptions) userLog("pingLoop waiting 60s for any pingable boxes"); sleep(60 * DateUtils.SECOND_IN_MILLIS, true); } else if (pushCount > 0) { // If we want to Ping, but can't just yet, wait a little bit // TODO Change sleep to wait and use notify from ExchangeService when a sync ends sleep(2 * DateUtils.SECOND_IN_MILLIS, false); pingWaitCount++; //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)"); } else if (uninitCount > 0) { // In this case, we're doing an initial sync of at least one mailbox. Since this // is typically a one-time case, I'm ok with trying again every 10 seconds until // we're in one of the other possible states. userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)"); sleep(10 * DateUtils.SECOND_IN_MILLIS, true); } else if (inboxId == -1) { // In this case, we're still syncing mailboxes, so sleep for only a short time sleep(45 * DateUtils.SECOND_IN_MILLIS, true); } else { // We've got nothing to do, so we'll check again in 20 minutes at which time // we'll update the folder list, check for policy changes and/or remote wipe, etc. // Let the device sleep in the meantime... userLog(ACCOUNT_MAILBOX_SLEEP_TEXT); sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true); } } // Save away the current heartbeat mPingHeartbeat = pingHeartbeat; }
From source file:saschpe.birthdays.service.CalendarSyncService.java
/** * Returns birthday calendar ID./* ww w.j ava 2 s .com*/ * * If no calendar is present, a new one is created. * * @return calendar id */ public static long getCalendar(Context context) { final Uri calenderUri = getCalendarUri(context, CalendarContract.Calendars.CONTENT_URI); final String selection = CalendarContract.Calendars.ACCOUNT_NAME + " = ? AND " + CalendarContract.Calendars.ACCOUNT_TYPE + " = ? AND " + CalendarContract.Calendars.NAME + " = ?"; final String calendarName = context.getString(R.string.calendar_name); ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(calenderUri, new String[] { BaseColumns._ID }, selection, new String[] { context.getString(R.string.app_name), context.getString(R.string.account_type), calendarName }, null); if (cursor != null && cursor.moveToNext()) { // Yay, calendar exists already. Just return it's id. long calendarId = cursor.getLong(0); cursor.close(); return calendarId; } else { if (cursor != null) { cursor.close(); } // So we've got to create a calendar first before we can return it's id. ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(calenderUri); builder.withValue(CalendarContract.Calendars.ACCOUNT_NAME, context.getString(R.string.app_name)); builder.withValue(CalendarContract.Calendars.ACCOUNT_TYPE, context.getString(R.string.account_type)); builder.withValue(CalendarContract.Calendars.NAME, calendarName); builder.withValue(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, context.getString(R.string.birthdays_and_anniversaries)); builder.withValue(CalendarContract.Calendars.CALENDAR_COLOR, PreferencesHelper.getCalendarColor(context)); builder.withValue(CalendarContract.Calendars.SYNC_EVENTS, PreferencesHelper.isCalendarSynced(context)); builder.withValue(CalendarContract.Calendars.VISIBLE, 1); if (BuildConfig.DEBUG) { builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_EDITOR); } else { builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_READ); } builder.withValue(CalendarContract.Calendars.OWNER_ACCOUNT, context.getString(R.string.app_name)); ArrayList<ContentProviderOperation> operations = new ArrayList<>(); operations.add(builder.build()); try { cr.applyBatch(CalendarContract.AUTHORITY, operations); Log.d(TAG, "Created calendar " + calendarName); } catch (RemoteException e) { Log.e(TAG, "Unable to create new calendar!", e); return -1; } catch (OperationApplicationException e) { Log.e(TAG, "Unable to create new calendar!", e); return -2; } // Try once again, this time we should find something in the database return getCalendar(context); } }
From source file:com.android.calendar.EventInfoFragment.java
/** * Creates an exception to a recurring event. The only change we're making is to the * "self attendee status" value. The provider will take care of updating the corresponding * Attendees.attendeeStatus entry.//from ww w.j a v a2 s . c o m * * @param eventId The recurring event. * @param status The new value for selfAttendeeStatus. */ private void createExceptionResponse(long eventId, int status) { ContentValues values = new ContentValues(); values.put(Events.ORIGINAL_INSTANCE_TIME, mStartMillis); values.put(Events.SELF_ATTENDEE_STATUS, status); values.put(Events.STATUS, Events.STATUS_CONFIRMED); ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); Uri exceptionUri = Uri.withAppendedPath(Events.CONTENT_EXCEPTION_URI, String.valueOf(eventId)); ops.add(ContentProviderOperation.newInsert(exceptionUri).withValues(values).build()); mHandler.startBatch(mHandler.getNextToken(), null, CalendarContract.AUTHORITY, ops, Utils.UNDO_DELAY); }