List of usage examples for android.content ContentResolver update
public final int update(@RequiresPermission.Write @NonNull Uri uri, @Nullable ContentValues values, @Nullable String where, @Nullable String[] selectionArgs)
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String Push(String fileName, BufferedInputStream bufIn, long lSize) { byte[] buffer = new byte[8192]; int nRead = 0; long lRead = 0; String sTmpFileName = fixFileName(fileName); FileOutputStream dstFile = null; ContentResolver cr = null; ContentValues cv = null;// w ww . j a v a 2 s . co m Uri ffxFiles = null; String sRet = sErrorPrefix + "Push failed!"; try { if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) { cr = contextWrapper.getContentResolver(); ffxFiles = Uri.parse( "content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file"); cv = new ContentValues(); } else { dstFile = new FileOutputStream(sTmpFileName, false); } while ((nRead != -1) && (lRead < lSize)) { nRead = bufIn.read(buffer); if (nRead != -1) { if (dstFile != null) { dstFile.write(buffer, 0, nRead); dstFile.flush(); } else { cv.put("offset", lRead); cv.put("length", nRead); cv.put("chunk", buffer); cr.update(ffxFiles, cv, sTmpFileName, null); } lRead += nRead; } } if (dstFile != null) { dstFile.flush(); dstFile.close(); } if (lRead == lSize) { sRet = HashFile(sTmpFileName); } } catch (IOException e) { e.printStackTrace(); } buffer = null; return (sRet); }
From source file:com.akop.bach.parser.XboxLiveParser.java
private void parseFriendSection(long accountId, JSONArray friends, long updated, List<ContentValues> newCvs, int statusHack) { ContentResolver cr = mContext.getContentResolver(); String[] queryParams = new String[1]; for (int i = 0, n = friends.length(); i < n; i++) { JSONObject friend = friends.optJSONObject(i); if (friend == null) continue; String gamertag = friend.optString("GamerTag"); String gamerpic = friend.optString("LargeGamerTileUrl"); String activity = friend.optString("Presence"); String titleName = null;/* ww w . ja v a 2 s . c o m*/ int gamerscore = friend.optInt("GamerScore", 0); long titleId = 0; JSONObject titleInfo = friend.optJSONObject("TitleInfo"); if (titleInfo != null) { titleId = titleInfo.optLong("Id", 0); titleName = null; if (!titleInfo.isNull("Name")) titleName = titleInfo.optString("Name"); } int statusCode = XboxLive.STATUS_OTHER; if (statusHack < 0) // TODO: HACK! { if (friend.optBoolean("IsOnline")) statusCode = XboxLive.STATUS_ONLINE; else statusCode = XboxLive.STATUS_OFFLINE; } else { statusCode = statusHack; } String statusDescription = Friends.getStatusDescription(mContext, statusCode); ContentValues cv = new ContentValues(15); cv.put(Friends.DELETE_MARKER, updated); cv.put(Friends.GAMERSCORE, gamerscore); cv.put(Friends.CURRENT_ACTIVITY, activity); cv.put(Friends.ICON_URL, gamerpic); cv.put(Friends.STATUS_CODE, statusCode); cv.put(Friends.STATUS, statusDescription); cv.put(Friends.TITLE_ID, titleId); cv.put(Friends.TITLE_NAME, titleName); cv.put(Friends.TITLE_URL, getBoxArt(titleId, false)); // check to see if friend is available locally queryParams[0] = gamertag; Cursor c = cr.query(Friends.CONTENT_URI, FRIENDS_PROJECTION, Friends.ACCOUNT_ID + "=" + accountId + " AND " + Friends.GAMERTAG + "=?", queryParams, null); try { if (c != null && c.moveToFirst()) { // Friend in the system; update record long friendId = c.getLong(COLUMN_FRIEND_ID); cr.update(Friends.CONTENT_URI, cv, Friends._ID + "=" + friendId, null); } else { // New friend cv.put(Friends.GAMERTAG, gamertag); cv.put(Friends.ACCOUNT_ID, accountId); cv.put(Friends.IS_FAVORITE, 0); newCvs.add(cv); } } finally { if (c != null) c.close(); } } }
From source file:com.akop.bach.parser.PsnEuParser.java
@SuppressLint("DefaultLocale") @Override/*from w w w. j ava 2 s.c o m*/ protected void parseTrophies(PsnAccount account, long gameId) throws ParserException, IOException { // Find game record in local DB ContentResolver cr = mContext.getContentResolver(); String gameUid = Games.getUid(mContext, gameId); String url = String.format(URL_TROPHIES_f, gameUid); String page = getResponse(url); int index = 0; long started = System.currentTimeMillis(); Matcher trophies = PATTERN_TROPHIES.matcher(page); Matcher m; List<ContentValues> cvList = new ArrayList<ContentValues>(100); while (trophies.find()) { boolean trophyUnlocked = "true".equalsIgnoreCase(trophies.group(1)); String trophyContent = trophies.group(2); String iconUrl = null; if ((m = PATTERN_TROPHY_ICON.matcher(trophyContent)).find()) iconUrl = getLargeTrophyIcon(resolveImageUrl(url, m.group(1))); String title = mContext.getString(R.string.secret_trophy); String description = mContext.getString(R.string.this_is_a_secret_trophy); if (!(m = PATTERN_TROPHY_TITLE.matcher(trophyContent)).find()) continue; int type = PSN.TROPHY_SECRET; boolean isSecret = false; String trophyType = m.group(1).toUpperCase(); if (trophyType.equals("BRONZE")) type = PSN.TROPHY_BRONZE; else if (trophyType.equals("SILVER")) type = PSN.TROPHY_SILVER; else if (trophyType.equals("GOLD")) type = PSN.TROPHY_GOLD; else if (trophyType.equals("PLATINUM")) type = PSN.TROPHY_PLATINUM; else if (trophyType.equals("UNKNOWN")) isSecret = true; if (!isSecret) { title = htmlDecode(m.group(2)); if ((m = PATTERN_TROPHY_DESCRIPTION.matcher(trophyContent)).find()) description = htmlDecode(m.group(1)); } long earned = 0; String earnedText = null; if (trophyUnlocked) { // No more date info earned = System.currentTimeMillis(); earnedText = mContext.getString(R.string.unlocked); } ContentValues cv = new ContentValues(20); cv.put(Trophies.TITLE, title); cv.put(Trophies.DESCRIPTION, description); cv.put(Trophies.SORT_ORDER, index); cv.put(Trophies.EARNED, earned); cv.put(Trophies.EARNED_TEXT, earnedText); cv.put(Trophies.ICON_URL, iconUrl); cv.put(Trophies.GAME_ID, gameId); cv.put(Trophies.IS_SECRET, isSecret ? 1 : 0); cv.put(Trophies.TYPE, type); cvList.add(cv); index++; } if (App.getConfig().logToConsole()) started = displayTimeTaken("New trophy parsing", started); ContentValues[] cva = new ContentValues[cvList.size()]; cvList.toArray(cva); cr.delete(Trophies.CONTENT_URI, Trophies.GAME_ID + "=" + gameId, null); // Bulk-insert new trophies cr.bulkInsert(Trophies.CONTENT_URI, cva); cr.notifyChange(Trophies.CONTENT_URI, null); if (App.getConfig().logToConsole()) started = displayTimeTaken("New trophy processing", started); // Update the game to remove the 'dirty' attribute ContentValues cv = new ContentValues(10); cv.put(Games.TROPHIES_DIRTY, 0); cr.update(Games.CONTENT_URI, cv, Games._ID + "=" + gameId, null); cr.notifyChange(ContentUris.withAppendedId(Games.CONTENT_URI, gameId), null); if (App.getConfig().logToConsole()) displayTimeTaken("Updating Game", started); }
From source file:com.akop.bach.parser.PsnEuParser.java
@SuppressLint("DefaultLocale") @Override/*from w w w . jav a2 s . c o m*/ protected void parseFriendSummary(PsnAccount account, String friendOnlineId) throws ParserException, IOException { String url = String.format(URL_FRIEND_SUMMARY_f, URLEncoder.encode(friendOnlineId, "UTF-8")); String friendData = getResponse(url); ContentResolver cr = mContext.getContentResolver(); Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION, Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?", new String[] { friendOnlineId }, null); long updated = System.currentTimeMillis(); long started = updated; long friendId = -1; try { if (c != null && c.moveToFirst()) friendId = c.getLong(0); } finally { if (c != null) c.close(); } Matcher m; Matcher friendMatcher = PATTERN_FRIEND_SUMMARY.matcher(friendData); if (friendMatcher.find() && friendMatcher.find()) // skip the first { String friendCard = friendMatcher.group(1); String onlineId = null; if ((m = PATTERN_FRIEND_SUMMARY_ONLINE_ID.matcher(friendCard)).find()) onlineId = htmlDecode(m.group(1)); if (onlineId != null) { int progress = 0; if ((m = PATTERN_FRIEND_SUMMARY_PROGRESS.matcher(friendCard)).find()) progress = Integer.parseInt(m.group(1)); int level = 0; if ((m = PATTERN_FRIEND_SUMMARY_LEVEL.matcher(friendCard)).find()) level = Integer.parseInt(m.group(1)); String iconUrl = null; if ((m = PATTERN_FRIEND_SUMMARY_AVATAR.matcher(friendCard)).find()) iconUrl = getLargeAvatarIcon(resolveImageUrl(url, m.group(1))); int memberType = PSN.MEMBER_TYPE_FREE; if ((m = PATTERN_FRIEND_SUMMARY_IS_PLUS.matcher(friendCard)).find()) memberType = PSN.MEMBER_TYPE_PLUS; int bronze = 0; int silver = 0; int gold = 0; int platinum = 0; m = PATTERN_FRIEND_SUMMARY_TROPHIES.matcher(friendCard); while (m.find()) { String type = m.group(1).toLowerCase(); if ("bronze".equals(type)) bronze = Integer.parseInt(m.group(2)); else if ("silver".equals(type)) silver = Integer.parseInt(m.group(2)); else if ("gold".equals(type)) gold = Integer.parseInt(m.group(2)); else if ("platinum".equals(type)) platinum = Integer.parseInt(m.group(2)); } ContentValues cv = new ContentValues(15); cv.put(Friends.LAST_UPDATED, updated); cv.put(Friends.ONLINE_ID, onlineId); cv.put(Friends.ICON_URL, iconUrl); cv.put(Friends.LEVEL, level); cv.put(Friends.PROGRESS, progress); cv.put(Friends.TROPHIES_PLATINUM, platinum); cv.put(Friends.TROPHIES_GOLD, gold); cv.put(Friends.TROPHIES_SILVER, silver); cv.put(Friends.TROPHIES_BRONZE, bronze); cv.put(Friends.MEMBER_TYPE, memberType); if (friendId < 0) { // New cv.put(Friends.ACCOUNT_ID, account.getId()); cv.put(Friends.ONLINE_STATUS, PSN.STATUS_OTHER); cv.put(Friends.PLAYING, (String) null); cr.insert(Friends.CONTENT_URI, cv); } else { // Existing cr.update(Friends.CONTENT_URI, cv, Friends._ID + "=" + friendId, null); } cr.notifyChange(Friends.CONTENT_URI, null); } } if (App.getConfig().logToConsole()) started = displayTimeTaken("parseCompareGames/processing", started); }
From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java
private int refreshFeed(String feedId, long keepDateBorderTime) { RssAtomParser handler = null;//from w w w .j a va 2 s . com ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(FeedColumns.CONTENT_URI(feedId), null, null, null, null); if (cursor.moveToFirst()) { int urlPosition = cursor.getColumnIndex(FeedColumns.URL); int idPosition = cursor.getColumnIndex(FeedColumns._ID); int titlePosition = cursor.getColumnIndex(FeedColumns.NAME); int fetchModePosition = cursor.getColumnIndex(FeedColumns.FETCH_MODE); int realLastUpdatePosition = cursor.getColumnIndex(FeedColumns.REAL_LAST_UPDATE); int iconPosition = cursor.getColumnIndex(FeedColumns.ICON); int retrieveFullscreenPosition = cursor.getColumnIndex(FeedColumns.RETRIEVE_FULLTEXT); /* ModPrivacyVandaag: if Fetchmode = 99, do not refresh this feed. */ int fetchMode = cursor.getInt(fetchModePosition); if (fetchMode == FETCHMODE_DO_NOT_FETCH) { cursor.close(); return 0; } // end of this added block of code; commented out initialize of fetchmode on line 520 String id = cursor.getString(idPosition); HttpURLConnection connection = null; try { String feedUrl = cursor.getString(urlPosition); connection = NetworkUtils.setupConnection(feedUrl); String contentType = connection.getContentType(); handler = new RssAtomParser(new Date(cursor.getLong(realLastUpdatePosition)), keepDateBorderTime, id, cursor.getString(titlePosition), feedUrl, cursor.getInt(retrieveFullscreenPosition) == 1); handler.setFetchImages(NetworkUtils.needDownloadPictures()); // Log.e (TAG,"feedUrl = "+feedUrl); if (fetchMode == 0) { if (contentType != null && contentType.startsWith(CONTENT_TYPE_TEXT_HTML)) { BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream())); String line; int posStart = -1; while ((line = reader.readLine()) != null) { if (line.contains(HTML_BODY)) { break; } else { Matcher matcher = FEED_LINK_PATTERN.matcher(line); if (matcher.find()) { // not "while" as only one link is needed line = matcher.group(); posStart = line.indexOf(HREF); if (posStart > -1) { String url = line.substring(posStart + 6, line.indexOf('"', posStart + 10)) .replace(Constants.AMP_SG, Constants.AMP); ContentValues values = new ContentValues(); if (url.startsWith(Constants.SLASH)) { int index = feedUrl.indexOf('/', 8); if (index > -1) { url = feedUrl.substring(0, index) + url; } else { url = feedUrl + url; } } else if (!url.startsWith(Constants.HTTP_SCHEME) && !url.startsWith(Constants.HTTPS_SCHEME)) { url = feedUrl + '/' + url; } values.put(FeedColumns.URL, url); cr.update(FeedColumns.CONTENT_URI(id), values, null, null); connection.disconnect(); connection = NetworkUtils.setupConnection(url); contentType = connection.getContentType(); break; } } } } // this indicates a badly configured feed if (posStart == -1) { connection.disconnect(); connection = NetworkUtils.setupConnection(feedUrl); contentType = connection.getContentType(); } } if (contentType != null) { int index = contentType.indexOf(CHARSET); if (index > -1) { int index2 = contentType.indexOf(';', index); try { Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2) : contentType.substring(index + 8)); fetchMode = FETCHMODE_DIRECT; } catch (UnsupportedEncodingException ignored) { fetchMode = FETCHMODE_REENCODE; } } else { fetchMode = FETCHMODE_REENCODE; } } else { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(connection.getInputStream())); char[] chars = new char[20]; int length = bufferedReader.read(chars); String xmlDescription = new String(chars, 0, length); connection.disconnect(); connection = NetworkUtils.setupConnection(connection.getURL()); int start = xmlDescription.indexOf(ENCODING); if (start > -1) { try { Xml.findEncodingByName(xmlDescription.substring(start + 10, xmlDescription.indexOf('"', start + 11))); fetchMode = FETCHMODE_DIRECT; } catch (UnsupportedEncodingException ignored) { fetchMode = FETCHMODE_REENCODE; } } else { // absolutely no encoding information found fetchMode = FETCHMODE_DIRECT; } } ContentValues values = new ContentValues(); values.put(FeedColumns.FETCH_MODE, fetchMode); cr.update(FeedColumns.CONTENT_URI(id), values, null, null); } switch (fetchMode) { default: case FETCHMODE_DIRECT: { if (contentType != null) { int index = contentType.indexOf(CHARSET); int index2 = contentType.indexOf(';', index); InputStream inputStream = connection.getInputStream(); Xml.parse(inputStream, Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2) : contentType.substring(index + 8)), handler); } else { InputStreamReader reader = new InputStreamReader(connection.getInputStream()); Xml.parse(reader, handler); } break; } case FETCHMODE_REENCODE: { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); InputStream inputStream = connection.getInputStream(); byte[] byteBuffer = new byte[4096]; int n; while ((n = inputStream.read(byteBuffer)) > 0) { outputStream.write(byteBuffer, 0, n); } String xmlText = outputStream.toString(); int start = xmlText != null ? xmlText.indexOf(ENCODING) : -1; if (start > -1) { Xml.parse(new StringReader(new String(outputStream.toByteArray(), xmlText.substring(start + 10, xmlText.indexOf('"', start + 11)))), handler); } else { // use content type if (contentType != null) { int index = contentType.indexOf(CHARSET); if (index > -1) { int index2 = contentType.indexOf(';', index); try { StringReader reader = new StringReader(new String(outputStream.toByteArray(), index2 > -1 ? contentType.substring(index + 8, index2) : contentType.substring(index + 8))); Xml.parse(reader, handler); } catch (Exception e) { Log.e("Privacy Vandaag: ", "Error reading string " + e.getMessage()); } } else { StringReader reader = new StringReader(xmlText); Xml.parse(reader, handler); } } } break; } } connection.disconnect(); } catch (FileNotFoundException e) { if (handler == null || (!handler.isDone() && !handler.isCancelled())) { ContentValues values = new ContentValues(); // resets the fetch mode to determine it again later values.put(FeedColumns.FETCH_MODE, 0); values.put(FeedColumns.ERROR, getString(R.string.error_feed_error)); cr.update(FeedColumns.CONTENT_URI(id), values, null, null); } } catch (Throwable e) { if (handler == null || (!handler.isDone() && !handler.isCancelled())) { ContentValues values = new ContentValues(); // resets the fetch mode to determine it again later values.put(FeedColumns.FETCH_MODE, 0); values.put(FeedColumns.ERROR, e.getMessage() != null ? e.getMessage() : getString(R.string.error_feed_process)); cr.update(FeedColumns.CONTENT_URI(id), values, null, null); handler = null; // If an error has occurred, reset the new articles counter for this feed to avoid notifications. } } finally { /* check and optionally find favicon */ /* No longer needed, because the icons of the feeds are included in the package */ /* try { if (handler != null && cursor.getBlob(iconPosition) == null) { String feedLink = handler.getFeedLink(); if (feedLink != null) { NetworkUtils.retrieveFavicon(this, new URL(feedLink), id); } else { NetworkUtils.retrieveFavicon(this, connection.getURL(), id); } } } catch (Throwable ignored) { } */ if (connection != null) { connection.disconnect(); } } } cursor.close(); int newArticles = (handler != null) ? handler.getNewCount() : 0; //Log.e(TAG, "Test notification is gegeven voor feedID " + feedId); //if (newArticles == 0 ) newArticles =2; // ONLY FOR TESTING !!!! // Check of meldingen voor deze feed aanstaat, anders newArticles op 0 zetten if (newArticles > 0) { boolean notifyFeed = true; switch (Integer.parseInt(feedId)) { case 1: // feedID Privacy Barometer notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_PRIVACYBAROMETER, true); break; case 2: // feedID Bits of Freedom notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_BITSOFFREEDOM, true); break; case 3: // feedID Privacy First notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_PRIVACYFIRST, true); break; case 4: // feedID Autoriteit Persoonsgegevens notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_AUTORITEITPERSOONSGEGEVENS, true); } if (!notifyFeed) newArticles = 0; // geen melding als de meldingen voor deze feed uitstaan. } //Log.e(TAG, "Nieuwe artikelen is " + newArticles); return newArticles; }
From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java
private void mobilizeAllEntries() { ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(TaskColumns.CONTENT_URI, new String[] { TaskColumns._ID, TaskColumns.ENTRY_ID, TaskColumns.NUMBER_ATTEMPT }, TaskColumns.IMG_URL_TO_DL + Constants.DB_IS_NULL, null, null); ArrayList<ContentProviderOperation> operations = new ArrayList<>(); while (cursor != null && cursor.moveToNext()) { long taskId = cursor.getLong(0); long entryId = cursor.getLong(1); int nbAttempt = 0; if (!cursor.isNull(2)) { nbAttempt = cursor.getInt(2); }// ww w . j a va 2 s.co m boolean success = false; Uri entryUri = EntryColumns.CONTENT_URI(entryId); Cursor entryCursor = cr.query(entryUri, null, null, null, null); if (entryCursor != null && entryCursor.moveToFirst()) { if (entryCursor.isNull(entryCursor.getColumnIndex(EntryColumns.MOBILIZED_HTML))) { // If we didn't already mobilized it int linkPos = entryCursor.getColumnIndex(EntryColumns.LINK); int abstractHtmlPos = entryCursor.getColumnIndex(EntryColumns.ABSTRACT); int feedIdPos = entryCursor.getColumnIndex(EntryColumns.FEED_ID); HttpURLConnection connection = null; try { String link = entryCursor.getString(linkPos); String feedId = entryCursor.getString(feedIdPos); Cursor cursorFeed = cr.query(FeedColumns.CONTENT_URI(feedId), null, null, null, null); cursorFeed.moveToNext(); int cookieNamePosition = cursorFeed.getColumnIndex(FeedColumns.COOKIE_NAME); int cookieValuePosition = cursorFeed.getColumnIndex(FeedColumns.COOKIE_VALUE); String cookieName = cursorFeed.getString(cookieNamePosition); String cookieValue = cursorFeed.getString(cookieValuePosition); cursorFeed.close(); // Take substring from RSS content and use it // to try to find a text indicator for better content extraction String contentIndicator = null; String text = entryCursor.getString(abstractHtmlPos); if (!TextUtils.isEmpty(text)) { text = Html.fromHtml(text).toString(); if (text.length() > 60) { contentIndicator = text.substring(20, 40); } } connection = NetworkUtils.setupConnection(link, cookieName, cookieValue); String mobilizedHtml = ArticleTextExtractor.extractContent(connection.getInputStream(), contentIndicator); if (mobilizedHtml != null) { mobilizedHtml = HtmlUtils.improveHtmlContent(mobilizedHtml, NetworkUtils.getBaseUrl(link)); ContentValues values = new ContentValues(); values.put(EntryColumns.MOBILIZED_HTML, mobilizedHtml); ArrayList<String> imgUrlsToDownload = null; if (NetworkUtils.needDownloadPictures()) { imgUrlsToDownload = HtmlUtils.getImageURLs(mobilizedHtml); } String mainImgUrl; if (imgUrlsToDownload != null) { mainImgUrl = HtmlUtils.getMainImageURL(imgUrlsToDownload); } else { mainImgUrl = HtmlUtils.getMainImageURL(mobilizedHtml); } if (mainImgUrl != null) { values.put(EntryColumns.IMAGE_URL, mainImgUrl); } if (cr.update(entryUri, values, null, null) > 0) { success = true; operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)) .build()); if (imgUrlsToDownload != null && !imgUrlsToDownload.isEmpty()) { addImagesToDownload(String.valueOf(entryId), imgUrlsToDownload); } } } } catch (Throwable ignored) { if (connection != null) { connection.disconnect(); } } finally { if (connection != null) { connection.disconnect(); } } } else { // We already mobilized it success = true; operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build()); } } if (entryCursor != null) entryCursor.close(); if (!success) { if (nbAttempt + 1 > MAX_TASK_ATTEMPT) { operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build()); } else { ContentValues values = new ContentValues(); values.put(TaskColumns.NUMBER_ATTEMPT, nbAttempt + 1); operations.add(ContentProviderOperation.newUpdate(TaskColumns.CONTENT_URI(taskId)) .withValues(values).build()); } } } if (cursor != null) cursor.close(); if (!operations.isEmpty()) { try { cr.applyBatch(FeedData.AUTHORITY, operations); } catch (Throwable ignored) { } } }
From source file:com.google.samples.apps.iosched.service.SessionCalendarService.java
/** * Adds or removes a single session to/from the specified Google Calendar. */// w w w .ja va2 s. c o m private ArrayList<ContentProviderOperation> processSessionCalendar(final ContentResolver resolver, final long calendarId, final boolean isAddEvent, final Uri sessionUri, final long sessionBlockStart, final long sessionBlockEnd, final String sessionTitle, final String sessionRoom) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Unable to find the Calendar associated with the user or permissions were revoked. if (calendarId == INVALID_CALENDAR_ID || !permissionsAlreadyGranted()) { return batch; } final String calendarEventTitle = makeCalendarEventTitle(sessionTitle); Cursor cursor; ContentValues values = new ContentValues(); // Add Calendar event. if (isAddEvent) { if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) { LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters."); return batch; } // Check if the calendar event exists first. If it does, we don't want to add a // duplicate one. //noinspection MissingPermission cursor = resolver.query(CalendarContract.Events.CONTENT_URI, // URI new String[] { CalendarContract.Events._ID }, // Projection CalendarContract.Events.CALENDAR_ID + "=? and " // Selection + CalendarContract.Events.TITLE + "=? and " + CalendarContract.Events.DTSTART + ">=? and " + CalendarContract.Events.DTEND + "<=?", new String[] { // Selection args Long.valueOf(calendarId).toString(), calendarEventTitle, Long.toString(Config.CONFERENCE_START_MILLIS), Long.toString(Config.CONFERENCE_END_MILLIS) }, null); long newEventId = -1; if (cursor != null && cursor.moveToFirst()) { // Calendar event already exists for this session. newEventId = cursor.getLong(0); cursor.close(); // Data fix (workaround): batch.add(ContentProviderOperation.newUpdate(CalendarContract.Events.CONTENT_URI) .withValue(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID()) .withSelection(CalendarContract.Events._ID + "=?", new String[] { Long.valueOf(newEventId).toString() }) .build()); // End data fix. } else { // Calendar event doesn't exist, create it. // NOTE: we can't use batch processing here because we need the result of // the insert. values.clear(); values.put(CalendarContract.Events.DTSTART, sessionBlockStart); values.put(CalendarContract.Events.DTEND, sessionBlockEnd); values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom); values.put(CalendarContract.Events.TITLE, calendarEventTitle); values.put(CalendarContract.Events.CALENDAR_ID, calendarId); values.put(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID()); @SuppressWarnings("MissingPermission") Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values); String eventId = eventUri.getLastPathSegment(); if (eventId == null) { return batch; // Should be empty at this point } newEventId = Long.valueOf(eventId); // Since we're adding session reminder to system notification, we're not creating // Calendar event reminders. If we were to create Calendar event reminders, this // is how we would do it. //values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId)); //values.put(CalendarContract.Reminders.MINUTES, 10); //values.put(CalendarContract.Reminders.METHOD, // CalendarContract.Reminders.METHOD_ALERT); // Or default? //cr.insert(CalendarContract.Reminders.CONTENT_URI, values); //values.clear(); } // Update the session in our own provider with the newly created calendar event ID. values.clear(); values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId); resolver.update(sessionUri, values, null, null); } else { // Remove Calendar event, if exists. // Get the event calendar id. cursor = resolver.query(sessionUri, new String[] { ScheduleContract.Sessions.SESSION_CAL_EVENT_ID }, null, null, null); long calendarEventId = -1; if (cursor != null && cursor.moveToFirst()) { calendarEventId = cursor.getLong(0); cursor.close(); } // Try to remove the Calendar Event based on key. If successful, move on; // otherwise, remove the event based on Event title. int affectedRows = 0; if (calendarEventId != -1) { //noinspection MissingPermission affectedRows = resolver.delete(CalendarContract.Events.CONTENT_URI, CalendarContract.Events._ID + "=?", new String[] { Long.valueOf(calendarEventId).toString() }); } if (affectedRows == 0) { //noinspection MissingPermission resolver.delete(CalendarContract.Events.CONTENT_URI, String.format("%s=? and %s=? and %s=? and %s=?", CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND), new String[] { Long.valueOf(calendarId).toString(), calendarEventTitle, Long.valueOf(sessionBlockStart).toString(), Long.valueOf(sessionBlockEnd).toString() }); } // Remove the session and calendar event association. values.clear(); values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null); resolver.update(sessionUri, values, null, null); } return batch; }
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String CopyFile(String sTmpSrcFileName, String sTmpDstFileName) { String sRet = sErrorPrefix + "Could not copy " + sTmpSrcFileName + " to " + sTmpDstFileName; ContentValues cv = null;/*ww w . ja va 2 s .c o m*/ File destFile = null; Uri ffxSrcFiles = null; Uri ffxDstFiles = null; FileInputStream srcFile = null; FileOutputStream dstFile = null; byte[] buffer = new byte[4096]; int nRead = 0; long lTotalRead = 0; long lTotalWritten = 0; ContentResolver crIn = null; ContentResolver crOut = null; if (sTmpSrcFileName.contains("org.mozilla.fennec") || sTmpSrcFileName.contains("org.mozilla.firefox")) { ffxSrcFiles = Uri.parse( "content://" + (sTmpSrcFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file"); crIn = contextWrapper.getContentResolver(); } else { try { srcFile = new FileInputStream(sTmpSrcFileName); } catch (FileNotFoundException e) { e.printStackTrace(); } } if (sTmpDstFileName.contains("org.mozilla.fennec") || sTmpDstFileName.contains("org.mozilla.firefox")) { ffxDstFiles = Uri.parse( "content://" + (sTmpDstFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file"); crOut = contextWrapper.getContentResolver(); cv = new ContentValues(); } else { try { dstFile = new FileOutputStream(sTmpDstFileName); } catch (FileNotFoundException e) { e.printStackTrace(); } } if (srcFile != null) { try { while ((nRead = srcFile.read(buffer)) != -1) { lTotalRead += nRead; if (dstFile != null) { dstFile.write(buffer, 0, nRead); dstFile.flush(); } else { cv.put("length", nRead); cv.put("chunk", buffer); if (crOut.update(ffxDstFiles, cv, sTmpDstFileName, null) == 0) break; lTotalWritten += nRead; } } srcFile.close(); if (dstFile != null) { dstFile.flush(); dstFile.close(); destFile = new File(sTmpDstFileName); lTotalWritten = destFile.length(); } if (lTotalWritten == lTotalRead) { sRet = sTmpSrcFileName + " copied to " + sTmpDstFileName; } else { sRet = sErrorPrefix + "Failed to copy " + sTmpSrcFileName + " [length = " + lTotalWritten + "] to " + sTmpDstFileName + " [length = " + lTotalRead + "]"; } } catch (IOException e) { e.printStackTrace(); } } else { String[] columns = new String[] { "_id", "chunk", "length" }; Cursor myCursor = crIn.query(ffxSrcFiles, columns, // Which columns to return sTmpSrcFileName, // Which rows to return (all rows) null, // Selection arguments (none) null); // Order clause (none) if (myCursor != null) { int nRows = myCursor.getCount(); byte[] buf = null; for (int lcv = 0; lcv < nRows; lcv++) { if (myCursor.moveToPosition(lcv)) { buf = myCursor.getBlob(myCursor.getColumnIndex("chunk")); if (buf != null) { nRead = buf.length; try { lTotalRead += nRead; if (dstFile != null) { dstFile.write(buffer, 0, nRead); dstFile.flush(); } else { cv.put("length", nRead); cv.put("chunk", buffer); if (crOut.update(ffxDstFiles, cv, sTmpDstFileName, null) == 0) break; lTotalWritten += nRead; } } catch (IOException e) { e.printStackTrace(); } buf = null; } } } if (nRows == -1) { sRet = sErrorPrefix + sTmpSrcFileName + ",-1\nNo such file or directory"; } else { myCursor.close(); if (dstFile != null) { try { dstFile.flush(); dstFile.close(); destFile = new File(sTmpDstFileName); lTotalWritten = destFile.length(); } catch (IOException e) { e.printStackTrace(); } } if (lTotalWritten == lTotalRead) { sRet = sTmpSrcFileName + " copied to " + sTmpDstFileName; } else { sRet = sErrorPrefix + "Failed to copy " + sTmpSrcFileName + " [length = " + lTotalWritten + "] to " + sTmpDstFileName + " [length = " + lTotalRead + "]"; } } } else { sRet = sErrorPrefix + sTmpSrcFileName + ",-1\nUnable to access file (internal error)"; } } return (sRet); }
From source file:com.android.exchange.adapter.EmailSyncAdapter.java
@Override public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mContext.getContentResolver(); if (getSyncKey().equals("0")) { return false; }/*from w w w.j ava2s. com*/ // Never upsync from these folders if (mMailbox.mType == Mailbox.TYPE_DRAFTS || mMailbox.mType == Mailbox.TYPE_OUTBOX) { return false; } // This code is split out for unit testing purposes boolean firstCommand = sendDeletedItems(s, mDeletedIdList, true); if (!mFetchRequestList.isEmpty()) { // Add FETCH commands for messages that need a body (i.e. we didn't find it during // our earlier sync; this happens only in EAS 2.5 where the body couldn't be found // after parsing the message's MIME data) if (firstCommand) { s.start(Tags.SYNC_COMMANDS); firstCommand = false; } for (FetchRequest req : mFetchRequestList) { s.start(Tags.SYNC_FETCH).data(Tags.SYNC_SERVER_ID, req.serverId).end(); } } // Find our trash mailbox, since deletions will have been moved there... long trashMailboxId = Mailbox.findMailboxOfType(mContext, mMailbox.mAccountKey, Mailbox.TYPE_TRASH); // Do the same now for updated items Cursor c = cr.query(Message.UPDATED_CONTENT_URI, Message.LIST_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); // We keep track of the list of updated item id's as we did above with deleted items mUpdatedIdList.clear(); try { ContentValues cv = new ContentValues(); while (c.moveToNext()) { long id = c.getLong(Message.LIST_ID_COLUMN); // Say we've handled this update mUpdatedIdList.add(id); // We have the id of the changed item. But first, we have to find out its current // state, since the updated table saves the opriginal state Cursor currentCursor = cr.query(ContentUris.withAppendedId(Message.CONTENT_URI, id), UPDATES_PROJECTION, null, null, null); try { // If this item no longer exists (shouldn't be possible), just move along if (!currentCursor.moveToFirst()) { continue; } // Keep going if there's no serverId String serverId = currentCursor.getString(UPDATES_SERVER_ID_COLUMN); if (serverId == null) { continue; } boolean flagChange = false; boolean readChange = false; long mailbox = currentCursor.getLong(UPDATES_MAILBOX_KEY_COLUMN); // If the message is now in the trash folder, it has been deleted by the user if (mailbox == trashMailboxId) { if (firstCommand) { s.start(Tags.SYNC_COMMANDS); firstCommand = false; } // Send the command to delete this message s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end(); // Mark the message as moved (so the copy will be deleted if/when the server // version is synced) int flags = c.getInt(Message.LIST_FLAGS_COLUMN); cv.put(MessageColumns.FLAGS, flags | EasSyncService.MESSAGE_FLAG_MOVED_MESSAGE); cr.update(ContentUris.withAppendedId(Message.CONTENT_URI, id), cv, null, null); continue; } else if (mailbox != c.getLong(Message.LIST_MAILBOX_KEY_COLUMN)) { // The message has moved to another mailbox; add a request for this // Note: The Sync command doesn't handle moving messages, so we need // to handle this as a "request" (similar to meeting response and // attachment load) mService.addRequest(new MessageMoveRequest(id, mailbox)); // Regardless of other changes that might be made, we don't want to indicate // that this message has been updated until the move request has been // handled (without this, a crash between the flag upsync and the move // would cause the move to be lost) mUpdatedIdList.remove(id); } // We can only send flag changes to the server in 12.0 or later int flag = 0; if (mService.mProtocolVersionDouble >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) { flag = currentCursor.getInt(UPDATES_FLAG_COLUMN); if (flag != c.getInt(Message.LIST_FAVORITE_COLUMN)) { flagChange = true; } } int read = currentCursor.getInt(UPDATES_READ_COLUMN); if (read != c.getInt(Message.LIST_READ_COLUMN)) { readChange = true; } if (!flagChange && !readChange) { // In this case, we've got nothing to send to the server continue; } if (firstCommand) { s.start(Tags.SYNC_COMMANDS); firstCommand = false; } // Send the change to "read" and "favorite" (flagged) s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, c.getString(Message.LIST_SERVER_ID_COLUMN)) .start(Tags.SYNC_APPLICATION_DATA); if (readChange) { s.data(Tags.EMAIL_READ, Integer.toString(read)); } // "Flag" is a relatively complex concept in EAS 12.0 and above. It is not only // the boolean "favorite" that we think of in Gmail, but it also represents a // follow up action, which can include a subject, start and due dates, and even // recurrences. We don't support any of this as yet, but EAS 12.0 and higher // require that a flag contain a status, a type, and four date fields, two each // for start date and end (due) date. if (flagChange) { if (flag != 0) { // Status 2 = set flag s.start(Tags.EMAIL_FLAG).data(Tags.EMAIL_FLAG_STATUS, "2"); // "FollowUp" is the standard type s.data(Tags.EMAIL_FLAG_TYPE, "FollowUp"); long now = System.currentTimeMillis(); Calendar calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.setTimeInMillis(now); // Flags are required to have a start date and end date (duplicated) // First, we'll set the current date/time in GMT as the start time String utc = formatDateTime(calendar); s.data(Tags.TASK_START_DATE, utc).data(Tags.TASK_UTC_START_DATE, utc); // And then we'll use one week from today for completion date calendar.setTimeInMillis(now + 1 * WEEKS); utc = formatDateTime(calendar); s.data(Tags.TASK_DUE_DATE, utc).data(Tags.TASK_UTC_DUE_DATE, utc); s.end(); } else { s.tag(Tags.EMAIL_FLAG); } } s.end().end(); // SYNC_APPLICATION_DATA, SYNC_CHANGE } finally { currentCursor.close(); } } } finally { c.close(); } if (!firstCommand) { s.end(); // SYNC_COMMANDS } return false; }
From source file:com.akop.bach.parser.PsnUsParser.java
protected void parseTrophies(PsnAccount account, long gameId) throws ParserException, IOException { // Find game record in local DB ContentResolver cr = mContext.getContentResolver(); String gameUid = Games.getUid(mContext, gameId); List<NameValuePair> inputs = new ArrayList<NameValuePair>(); inputs.add(new BasicNameValuePair("sortBy", "id_asc")); inputs.add(new BasicNameValuePair("titleId", gameUid)); String page = getResponse(String.format(URL_TROPHIES, URLEncoder.encode(account.getScreenName(), "UTF-8")), inputs, true);/* w w w. java2s . c om*/ int index = 0; long started = System.currentTimeMillis(); Matcher achievements = PATTERN_TROPHIES.matcher(page); Matcher m; List<ContentValues> cvList = new ArrayList<ContentValues>(100); while (achievements.find()) { String trophyRow = achievements.group(2); String title = mContext.getString(R.string.secret_trophy); if ((m = PATTERN_TROPHY_TITLE.matcher(trophyRow)).find()) title = htmlDecode(m.group(1)); String description = mContext.getString(R.string.this_is_a_secret_trophy); if ((m = PATTERN_TROPHY_DESCRIPTION.matcher(trophyRow)).find()) description = htmlDecode(m.group(1)); String iconUrl = null; if ((m = PATTERN_TROPHY_ICON.matcher(trophyRow)).find()) iconUrl = getAvatarImage(m.group(1)); long earned = 0; if ((m = PATTERN_TROPHY_EARNED.matcher(trophyRow)).find()) { try { earned = TROPHY_DATE_FORMAT.parse(m.group(1)).getTime(); } catch (ParseException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); } } boolean isSecret = false; int type = 0; if ((m = PATTERN_TROPHY_TYPE.matcher(trophyRow)).find()) { String trophyType = m.group(1).toUpperCase(); if (trophyType.equals("BRONZE")) type = PSN.TROPHY_BRONZE; else if (trophyType.equals("SILVER")) type = PSN.TROPHY_SILVER; else if (trophyType.equals("GOLD")) type = PSN.TROPHY_GOLD; else if (trophyType.equals("PLATINUM")) type = PSN.TROPHY_PLATINUM; else if (trophyType.equals("HIDDEN")) isSecret = true; } ContentValues cv = new ContentValues(20); cv.put(Trophies.TITLE, title); cv.put(Trophies.DESCRIPTION, description); cv.put(Trophies.SORT_ORDER, index); cv.put(Trophies.EARNED, earned); cv.put(Trophies.ICON_URL, iconUrl); cv.put(Trophies.GAME_ID, gameId); cv.put(Trophies.IS_SECRET, isSecret ? 1 : 0); cv.put(Trophies.TYPE, type); cvList.add(cv); index++; } if (App.getConfig().logToConsole()) started = displayTimeTaken("New trophy parsing", started); ContentValues[] cva = new ContentValues[cvList.size()]; cvList.toArray(cva); cr.delete(Trophies.CONTENT_URI, Trophies.GAME_ID + "=" + gameId, null); // Bulk-insert new trophies cr.bulkInsert(Trophies.CONTENT_URI, cva); cr.notifyChange(Trophies.CONTENT_URI, null); if (App.getConfig().logToConsole()) started = displayTimeTaken("New trophy processing", started); // Update the game to remove the 'dirty' attribute ContentValues cv = new ContentValues(10); cv.put(Games.TROPHIES_DIRTY, 0); cr.update(Games.CONTENT_URI, cv, Games._ID + "=" + gameId, null); cr.notifyChange(ContentUris.withAppendedId(Games.CONTENT_URI, gameId), null); if (App.getConfig().logToConsole()) displayTimeTaken("Updating Game", started); }