List of usage examples for android.content ContentResolver query
public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder)
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String Pull(String fileName, long lOffset, long lLength, OutputStream out) { String sTmpFileName = fixFileName(fileName); String sRet = sErrorPrefix + "Could not read the file " + sTmpFileName; byte[] buffer = new byte[4096]; int nRead = 0; long lSent = 0; if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) { ContentResolver cr = contextWrapper.getContentResolver(); Uri ffxFiles = null;//from ww w.j a v a2s. c o m ffxFiles = Uri .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file"); String[] columns = new String[] { "_id", "chunk", "length" }; String[] args = new String[2]; args[0] = Long.toString(lOffset); args[1] = Long.toString(lLength); Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return sTmpFileName, // Which rows to return (all rows) args, // Selection arguments (none) null); // Order clause (none) if (myCursor != null) { int nRows = myCursor.getCount(); long lFileLength = 0; for (int lcv = 0; lcv < nRows; lcv++) { if (myCursor.moveToPosition(lcv)) { if (lcv == 0) { lFileLength = myCursor.getLong(2); String sTmp = sTmpFileName + "," + lFileLength + "\n"; try { out.write(sTmp.getBytes()); } catch (IOException e) { e.printStackTrace(); break; } } if (lLength != 0) { byte[] buf = myCursor.getBlob(1); if (buf != null) { nRead = buf.length; try { if ((lSent + nRead) <= lFileLength) { out.write(buf, 0, nRead); lSent += nRead; } else { nRead = (int) (lFileLength - lSent); out.write(buf, 0, nRead); Log.d("pull warning", "more bytes read than expected"); break; } } catch (IOException e) { e.printStackTrace(); sRet = sErrorPrefix + "Could not write to out " + sTmpFileName; } buf = null; } } } } if (nRows == 0) { String sTmp = sTmpFileName + "," + lFileLength + "\n"; try { out.write(sTmp.getBytes()); } catch (IOException e) { e.printStackTrace(); } } if (nRows == -1) { sRet = sErrorPrefix + sTmpFileName + ",-1\nNo such file or directory"; } else { myCursor.close(); sRet = ""; } } else { sRet = sErrorPrefix + sTmpFileName + ",-1\nUnable to access file (internal error)"; } } else { try { File f = new File(sTmpFileName); long lFileLength = f.length(); FileInputStream fin = new FileInputStream(f); if (lFileLength == 0) { while ((nRead = fin.read(buffer)) != -1) { lFileLength += nRead; } fin.close(); fin = new FileInputStream(f); } // lLength == -1 return everything between lOffset and eof // lLength == 0 return file length // lLength > 0 return lLength bytes if (lLength == -1) { lFileLength = lFileLength - lOffset; } else if (lLength == 0) { // just return the file length } else { lFileLength = ((lLength <= (lFileLength - lOffset)) ? lLength : (lFileLength - lOffset)); } String sTmp = sTmpFileName + "," + lFileLength + "\n"; out.write(sTmp.getBytes()); if (lLength != 0) { if (lOffset > 0) { fin.skip(lOffset); } while ((nRead = fin.read(buffer)) != -1) { if ((lSent + nRead) <= lFileLength) { out.write(buffer, 0, nRead); lSent += nRead; } else { nRead = (int) (lFileLength - lSent); out.write(buffer, 0, nRead); if (lLength != -1) Log.d("pull warning", "more bytes read than sent"); break; } } } fin.close(); out.flush(); sRet = ""; } catch (FileNotFoundException e) { sRet = sErrorPrefix + sTmpFileName + ",-1\nNo such file or directory"; } catch (IOException e) { sRet = e.toString(); } } 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;//from w w w .j av a 2 s .co 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.android.contacts.ContactSaveService.java
private void saveContact(Intent intent) { RawContactDeltaList state = intent.getParcelableExtra(EXTRA_CONTACT_STATE); boolean isProfile = intent.getBooleanExtra(EXTRA_SAVE_IS_PROFILE, false); Bundle updatedPhotos = intent.getParcelableExtra(EXTRA_UPDATED_PHOTOS); if (state == null) { Log.e(TAG, "Invalid arguments for saveContact request"); return;//from ww w .j ava 2 s . com } int saveMode = intent.getIntExtra(EXTRA_SAVE_MODE, -1); // Trim any empty fields, and RawContacts, before persisting final AccountTypeManager accountTypes = AccountTypeManager.getInstance(this); RawContactModifier.trimEmpty(state, accountTypes); Uri lookupUri = null; final ContentResolver resolver = getContentResolver(); boolean succeeded = false; // Keep track of the id of a newly raw-contact (if any... there can be at most one). long insertedRawContactId = -1; // Attempt to persist changes int tries = 0; while (tries++ < PERSIST_TRIES) { try { // Build operations and try applying final ArrayList<CPOWrapper> diffWrapper = state.buildDiffWrapper(); final ArrayList<ContentProviderOperation> diff = Lists.newArrayList(); for (CPOWrapper cpoWrapper : diffWrapper) { diff.add(cpoWrapper.getOperation()); } if (DEBUG) { Log.v(TAG, "Content Provider Operations:"); for (ContentProviderOperation operation : diff) { Log.v(TAG, operation.toString()); } } int numberProcessed = 0; boolean batchFailed = false; final ContentProviderResult[] results = new ContentProviderResult[diff.size()]; while (numberProcessed < diff.size()) { final int subsetCount = applyDiffSubset(diff, numberProcessed, results, resolver); if (subsetCount == -1) { Log.w(TAG, "Resolver.applyBatch failed in saveContacts"); batchFailed = true; break; } else { numberProcessed += subsetCount; } } if (batchFailed) { // Retry save continue; } final long rawContactId = getRawContactId(state, diffWrapper, results); if (rawContactId == -1) { throw new IllegalStateException("Could not determine RawContact ID after save"); } // We don't have to check to see if the value is still -1. If we reach here, // the previous loop iteration didn't succeed, so any ID that we obtained is bogus. insertedRawContactId = getInsertedRawContactId(diffWrapper, results); if (isProfile) { // Since the profile supports local raw contacts, which may have been completely // removed if all information was removed, we need to do a special query to // get the lookup URI for the profile contact (if it still exists). Cursor c = resolver.query(Profile.CONTENT_URI, new String[] { Contacts._ID, Contacts.LOOKUP_KEY }, null, null, null); if (c == null) { continue; } try { if (c.moveToFirst()) { final long contactId = c.getLong(0); final String lookupKey = c.getString(1); lookupUri = Contacts.getLookupUri(contactId, lookupKey); } } finally { c.close(); } } else { final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); lookupUri = RawContacts.getContactLookupUri(resolver, rawContactUri); } if (lookupUri != null && Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Saved contact. New URI: " + lookupUri); } // We can change this back to false later, if we fail to save the contact photo. succeeded = true; break; } catch (RemoteException e) { // Something went wrong, bail without success FeedbackHelper.sendFeedback(this, TAG, "Problem persisting user edits", e); break; } catch (IllegalArgumentException e) { // This is thrown by applyBatch on malformed requests FeedbackHelper.sendFeedback(this, TAG, "Problem persisting user edits", e); showToast(R.string.contactSavedErrorToast); break; } catch (OperationApplicationException e) { // Version consistency failed, re-parent change and try again Log.w(TAG, "Version consistency failed, re-parenting: " + e.toString()); final StringBuilder sb = new StringBuilder(RawContacts._ID + " IN("); boolean first = true; final int count = state.size(); for (int i = 0; i < count; i++) { Long rawContactId = state.getRawContactId(i); if (rawContactId != null && rawContactId != -1) { if (!first) { sb.append(','); } sb.append(rawContactId); first = false; } } sb.append(")"); if (first) { throw new IllegalStateException("Version consistency failed for a new contact", e); } final RawContactDeltaList newState = RawContactDeltaList.fromQuery( isProfile ? RawContactsEntity.PROFILE_CONTENT_URI : RawContactsEntity.CONTENT_URI, resolver, sb.toString(), null, null); state = RawContactDeltaList.mergeAfter(newState, state); // Update the new state to use profile URIs if appropriate. if (isProfile) { for (RawContactDelta delta : state) { delta.setProfileQueryUri(); } } } } // Now save any updated photos. We do this at the end to ensure that // the ContactProvider already knows about newly-created contacts. if (updatedPhotos != null) { for (String key : updatedPhotos.keySet()) { Uri photoUri = updatedPhotos.getParcelable(key); long rawContactId = Long.parseLong(key); // If the raw-contact ID is negative, we are saving a new raw-contact; // replace the bogus ID with the new one that we actually saved the contact at. if (rawContactId < 0) { rawContactId = insertedRawContactId; } // If the save failed, insertedRawContactId will be -1 if (rawContactId < 0 || !saveUpdatedPhoto(rawContactId, photoUri, saveMode)) { succeeded = false; } } } Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT); if (callbackIntent != null) { if (succeeded) { // Mark the intent to indicate that the save was successful (even if the lookup URI // is now null). For local contacts or the local profile, it's possible that the // save triggered removal of the contact, so no lookup URI would exist.. callbackIntent.putExtra(EXTRA_SAVE_SUCCEEDED, true); } callbackIntent.setData(lookupUri); deliverCallback(callbackIntent); } }
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String processCommand(String theCmdLine, PrintWriter out, BufferedInputStream in, OutputStream cmdOut) { String strReturn = ""; Command cCmd = null;//from w w w. jav a 2s . co m Command cSubCmd = null; if (bTraceOn) ((ASMozStub) this.contextWrapper).SendToDataChannel(theCmdLine); String[] Argv = parseCmdLine2(theCmdLine); int Argc = Argv.length; cCmd = Command.getCmd(Argv[0]); switch (cCmd) { case TRACE: if (Argc == 2) bTraceOn = (Argv[1].equalsIgnoreCase("on") ? true : false); else strReturn = sErrorPrefix + "Wrong number of arguments for trace command!"; break; case VER: strReturn = prgVersion; break; case CLOK: strReturn = GetClok(); break; case TZGET: strReturn = GetTimeZone(); break; case TZSET: if (Argc == 2) strReturn = SetTimeZone(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for settz command!"; break; case UPDT: if (Argc >= 2) strReturn = StrtUpdtOMatic(Argv[1], Argv[2], (Argc > 3 ? Argv[3] : null), (Argc > 4 ? Argv[4] : null)); else strReturn = sErrorPrefix + "Wrong number of arguments for updt command!"; break; case SETTIME: strReturn = SetSystemTime(Argv[1], (Argc > 2 ? Argv[2] : null), cmdOut); break; case CWD: try { strReturn = new java.io.File(currentDir).getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } break; case CD: if (Argc == 2) strReturn = changeDir(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for cd command!"; break; case LS: strReturn = PrintDir(((Argc > 1) ? Argv[1] : currentDir)); break; case GETAPPROOT: if (Argc == 2) strReturn = GetAppRoot(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for getapproot command!"; break; case ISDIR: if (Argc == 2) strReturn = isDirectory(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for isdir command!"; break; case TESTROOT: strReturn = GetTestRoot(); break; case DEAD: if (Argc == 2) strReturn = (IsProcessDead(Argv[1]) ? (Argv[1] + " is hung or unresponsive") : (Argv[1] + " is ok")); else strReturn = sErrorPrefix + "Wrong number of arguments for dead command!"; break; case PS: strReturn = GetProcessInfo(); break; case PULL: if (Argc >= 2) { long lOff = 0; long lLen = -1; if (Argc > 2) { try { lOff = Long.parseLong(Argv[2].trim()); } catch (NumberFormatException nfe) { lOff = 0; System.out.println("NumberFormatException: " + nfe.getMessage()); } } if (Argc == 4) { try { lLen = Long.parseLong(Argv[3].trim()); } catch (NumberFormatException nfe) { lLen = -1; System.out.println("NumberFormatException: " + nfe.getMessage()); } } strReturn = Pull(Argv[1], lOff, lLen, cmdOut); } else { strReturn = sErrorPrefix + "Wrong number of arguments for pull command!"; } break; case PUSH: if (Argc == 3) { long lArg = 0; try { lArg = Long.parseLong(Argv[2].trim()); } catch (NumberFormatException nfe) { System.out.println("NumberFormatException: " + nfe.getMessage()); } strReturn = Push(Argv[1], in, lArg); } else strReturn = sErrorPrefix + "Wrong number of arguments for push command!"; break; case INST: if (Argc >= 2) strReturn = InstallApp(Argv[1], cmdOut); else strReturn = sErrorPrefix + "Wrong number of arguments for inst command!"; break; case UNINST: if (Argc >= 2) strReturn = UnInstallApp(Argv[1], cmdOut, true); else strReturn = sErrorPrefix + "Wrong number of arguments for uninst command!"; break; case UNINSTALL: if (Argc >= 2) strReturn = UnInstallApp(Argv[1], cmdOut, false); else strReturn = sErrorPrefix + "Wrong number of arguments for uninstall command!"; break; case ALRT: if (Argc > 1) { if (Argv[1].contentEquals("on")) { String sTitle = "Agent Alert"; String sMsg = "The Agent Alert System has been activated!"; if (Argc == 3) { sTitle = Argv[2]; sMsg = ""; } else if (Argc == 4) { sTitle = Argv[2]; sMsg = Argv[3]; } StartAlert(sTitle, sMsg); } else { StopAlert(); } } else { strReturn = sErrorPrefix + "Wrong number of arguments for alrt command!"; } break; case REBT: if (Argc >= 1) strReturn = RunReboot(cmdOut, (Argc > 1 ? Argv[1] : null), (Argc > 2 ? Argv[2] : null)); else strReturn = sErrorPrefix + "Wrong number of arguments for rebt command!"; // RunReboot(cmdOut); break; case TMPD: strReturn = GetTmpDir(); break; case DEVINFO: if (Argc == 1) { strReturn += SUTAgentAndroid.sUniqueID; strReturn += "\n"; strReturn += GetOSInfo(); strReturn += "\n"; strReturn += GetSystemTime(); strReturn += "\n"; strReturn += GetUptime(); strReturn += "\n"; strReturn += GetUptimeMillis(); strReturn += "\n"; strReturn += GetSutUptimeMillis(); strReturn += "\n"; strReturn += GetScreenInfo(); strReturn += "\n"; strReturn += GetRotationInfo(); strReturn += "\n"; strReturn += GetMemoryInfo(); strReturn += "\n"; strReturn += GetPowerInfo(); strReturn += "\n"; strReturn += GetTemperatureInfo(); strReturn += "\n"; strReturn += GetProcessInfo(); strReturn += "\n"; strReturn += GetSutUserInfo(); strReturn += "\n"; strReturn += GetDiskInfo("/data"); strReturn += "\n"; strReturn += GetDiskInfo("/system"); strReturn += "\n"; strReturn += GetDiskInfo("/mnt/sdcard"); } else { cSubCmd = Command.getCmd(Argv[1]); switch (cSubCmd) { case ID: strReturn = SUTAgentAndroid.sUniqueID; break; case SCREEN: strReturn = GetScreenInfo(); break; case ROTATION: strReturn = GetRotationInfo(); break; case PROCESS: strReturn = GetProcessInfo(); break; case OS: strReturn = GetOSInfo(); break; case SYSTIME: strReturn = GetSystemTime(); break; case UPTIME: strReturn = GetUptime(); break; case UPTIMEMILLIS: strReturn = GetUptimeMillis(); break; case SUTUPTIMEMILLIS: strReturn = GetSutUptimeMillis(); break; case MEMORY: strReturn = GetMemoryInfo(); break; case POWER: strReturn += GetPowerInfo(); break; case SUTUSERINFO: strReturn += GetSutUserInfo(); break; case TEMPERATURE: strReturn += GetTemperatureInfo(); break; case DISK: strReturn += "\n"; strReturn += GetDiskInfo("/data"); strReturn += "\n"; strReturn += GetDiskInfo("/system"); strReturn += "\n"; strReturn += GetDiskInfo("/mnt/sdcard"); break; default: break; } } break; case STAT: if (Argc == 2) strReturn = StatProcess(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for ping command!"; break; case PING: if (Argc == 2) strReturn = SendPing(Argv[1], cmdOut); else strReturn = sErrorPrefix + "Wrong number of arguments for ping command!"; break; case HASH: if (Argc == 2) strReturn = HashFile(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for hash command!"; break; case PRUNE: if (Argc == 2) strReturn = PruneDir(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for prune command!"; break; case FTPG: if (Argc == 4) strReturn = FTPGetFile(Argv[1], Argv[2], Argv[3], cmdOut); else strReturn = sErrorPrefix + "Wrong number of arguments for ftpg command!"; break; case CAT: if (Argc == 2) strReturn = Cat(Argv[1], cmdOut); else strReturn = sErrorPrefix + "Wrong number of arguments for cat command!"; break; case DIRWRITABLE: if (Argc == 2) strReturn = IsDirWritable(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for dirwritable command!"; break; case TIME: if (Argc == 2) strReturn = PrintFileTimestamp(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for time command!"; break; case MKDR: if (Argc == 2) strReturn = MakeDir(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for mkdr command!"; break; case RM: if (Argc == 2) strReturn = RemoveFile(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for rm command!"; break; case MV: if (Argc == 3) strReturn = Move(Argv[1], Argv[2]); else strReturn = sErrorPrefix + "Wrong number of arguments for mv command!"; break; case CP: if (Argc == 3) strReturn = CopyFile(Argv[1], Argv[2]); else strReturn = sErrorPrefix + "Wrong number of arguments for cp command!"; break; case QUIT: case EXIT: strReturn = Argv[0]; break; case DBG: Debug.waitForDebugger(); strReturn = "waitForDebugger on"; break; case ADB: if (Argc == 2) { if (Argv[1].contains("ip") || Argv[1].contains("usb")) { strReturn = SetADB(Argv[1]); } else { strReturn = sErrorPrefix + "Unrecognized argument for adb command!"; } } else { strReturn = sErrorPrefix + "Wrong number of arguments for adb command!"; } break; case TEST: long lFreeMemory = Runtime.getRuntime().freeMemory(); long lTotMemory = Runtime.getRuntime().totalMemory(); long lMaxMemory = Runtime.getRuntime().maxMemory(); if (lFreeMemory > 0) { strReturn = "Max memory: " + lMaxMemory + "\nTotal Memory: " + lTotMemory + "\nFree memory: " + lFreeMemory; break; } ContentResolver cr = contextWrapper.getContentResolver(); Uri ffxFiles = null; if (Argv[1].contains("fennec")) { ffxFiles = Uri.parse("content://" + fenProvider + "/dir"); } else if (Argv[1].contains("firefox")) { ffxFiles = Uri.parse("content://" + ffxProvider + "/dir"); } // Uri ffxFiles = Uri.parse("content://org.mozilla.fencp/file"); String[] columns = new String[] { "_id", "isdir", "filename", "length" }; // String[] columns = new String[] { // "_id", // "chunk" // }; Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return (Argc > 1 ? Argv[1] : null), // Which rows to return (all rows) null, // Selection arguments (none) null); // Put the results in ascending order by name /* if (myCursor != null) { int nRows = myCursor.getCount(); String [] colNames = myCursor.getColumnNames(); int nID = 0; int nBytesRecvd = 0; for (int lcv = 0; lcv < nRows; lcv++) { if (myCursor.moveToPosition(lcv)) { nID = myCursor.getInt(0); byte [] buf = myCursor.getBlob(1); if (buf != null) { nBytesRecvd += buf.length; strReturn += new String(buf); buf = null; } } } strReturn += "[eof - " + nBytesRecvd + "]"; myCursor.close(); } */ if (myCursor != null) { int nRows = myCursor.getCount(); int nID = 0; String sFileName = ""; long lFileSize = 0; boolean bIsDir = false; for (int lcv = 0; lcv < nRows; lcv++) { if (myCursor.moveToPosition(lcv)) { nID = myCursor.getInt(0); bIsDir = (myCursor.getInt(1) == 1 ? true : false); sFileName = myCursor.getString(2); lFileSize = myCursor.getLong(3); strReturn += "" + nID + "\t" + (bIsDir ? "<dir> " : " ") + sFileName + "\t" + lFileSize + "\n"; } } myCursor.close(); } break; case EXEC: case ENVRUN: if (Argc >= 2) { String[] theArgs = new String[Argc - 1]; for (int lcv = 1; lcv < Argc; lcv++) { theArgs[lcv - 1] = Argv[lcv]; } strReturn = StartPrg2(theArgs, cmdOut, null, false, DEFAULT_STARTPRG_TIMEOUT_SECONDS); } else { strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!"; } break; case EXECSU: if (Argc >= 2) { String[] theArgs = new String[Argc - 1]; for (int lcv = 1; lcv < Argc; lcv++) { theArgs[lcv - 1] = Argv[lcv]; } strReturn = StartPrg2(theArgs, cmdOut, null, true, DEFAULT_STARTPRG_TIMEOUT_SECONDS); } else { strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!"; } break; case EXECCWD: if (Argc >= 3) { String[] theArgs = new String[Argc - 2]; for (int lcv = 2; lcv < Argc; lcv++) { theArgs[lcv - 2] = Argv[lcv]; } strReturn = StartPrg2(theArgs, cmdOut, Argv[1], false, DEFAULT_STARTPRG_TIMEOUT_SECONDS); } else { strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!"; } break; case EXECCWDSU: if (Argc >= 3) { String[] theArgs = new String[Argc - 2]; for (int lcv = 2; lcv < Argc; lcv++) { theArgs[lcv - 2] = Argv[lcv]; } strReturn = StartPrg2(theArgs, cmdOut, Argv[1], true, DEFAULT_STARTPRG_TIMEOUT_SECONDS); } else { strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!"; } break; case RUN: if (Argc >= 2) { String[] theArgs = new String[Argc - 1]; for (int lcv = 1; lcv < Argc; lcv++) { theArgs[lcv - 1] = Argv[lcv]; } if (Argv[1].contains("/") || Argv[1].contains("\\") || !Argv[1].contains(".")) strReturn = StartPrg(theArgs, cmdOut, false, DEFAULT_STARTPRG_TIMEOUT_SECONDS); else strReturn = StartJavaPrg(theArgs, null); } else { strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!"; } break; case EXECEXT: // An "extended" exec command with format: // execext [su] [cwd=<path>] [t=<timeout in seconds>] arg1 ... if (Argc >= 2) { boolean su = false; String cwd = null; int timeout = DEFAULT_STARTPRG_TIMEOUT_SECONDS; int extra; for (extra = 1; extra < Argc; extra++) { if (Argv[extra].equals("su")) { su = true; } else if (Argv[extra].startsWith("cwd=")) { cwd = Argv[extra].substring(4); } else if (Argv[extra].startsWith("t=")) { timeout = Integer.parseInt(Argv[extra].substring(2)); if (timeout < 1 || timeout > 4 * 60 * 60) { Log.e("SUTAgentAndroid", "invalid execext timeout " + Argv[extra].substring(2) + "; using default instead"); timeout = DEFAULT_STARTPRG_TIMEOUT_SECONDS; } } else { break; } } if (extra < Argc) { String[] theArgs = new String[Argc - extra]; for (int lcv = extra; lcv < Argc; lcv++) { theArgs[lcv - extra] = Argv[lcv]; } strReturn = StartPrg2(theArgs, cmdOut, cwd, su, timeout); } else { strReturn = sErrorPrefix + "No regular arguments for " + Argv[0] + " command!"; } } else { strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!"; } break; case KILL: if (Argc == 2) strReturn = KillProcess(Argv[1], cmdOut); else strReturn = sErrorPrefix + "Wrong number of arguments for kill command!"; break; case DISK: strReturn = GetDiskInfo((Argc == 2 ? Argv[1] : "/")); break; case UNZP: strReturn = Unzip(Argv[1], (Argc == 3 ? Argv[2] : "")); break; case ZIP: strReturn = Zip(Argv[1], (Argc == 3 ? Argv[2] : "")); break; case CHMOD: if (Argc == 2) strReturn = ChmodDir(Argv[1]); else strReturn = sErrorPrefix + "Wrong number of arguments for chmod command!"; break; case TOPACTIVITY: strReturn = TopActivity(); break; case HELP: strReturn = PrintUsage(); break; default: strReturn = sErrorPrefix + "[" + Argv[0] + "] command"; if (Argc > 1) { strReturn += " with arg(s) ="; for (int lcv = 1; lcv < Argc; lcv++) { strReturn += " [" + Argv[lcv] + "]"; } } strReturn += " is currently not implemented."; break; } return (strReturn); }
From source file:com.android.mail.compose.ComposeActivity.java
/** * Send or Save a message.//from w w w . j av a2 s . c o m */ private void sendOrSaveMessage(SendOrSaveCallback callback, final long messageIdToSave, final SendOrSaveMessage sendOrSaveMessage, final ReplyFromAccount selectedAccount) { final ContentResolver resolver = getContentResolver(); final boolean updateExistingMessage = messageIdToSave != UIProvider.INVALID_MESSAGE_ID; final String accountMethod = sendOrSaveMessage.mSave ? UIProvider.AccountCallMethods.SAVE_MESSAGE : UIProvider.AccountCallMethods.SEND_MESSAGE; try { if (updateExistingMessage) { sendOrSaveMessage.mValues.put(BaseColumns._ID, messageIdToSave); callAccountSendSaveMethod(resolver, selectedAccount.account, accountMethod, sendOrSaveMessage); } else { Uri messageUri = null; final Bundle result = callAccountSendSaveMethod(resolver, selectedAccount.account, accountMethod, sendOrSaveMessage); if (result != null) { // If a non-null value was returned, then the provider handled the call // method messageUri = result.getParcelable(UIProvider.MessageColumns.URI); } if (sendOrSaveMessage.mSave && messageUri != null) { final Cursor messageCursor = resolver.query(messageUri, UIProvider.MESSAGE_PROJECTION, null, null, null); if (messageCursor != null) { try { if (messageCursor.moveToFirst()) { // Broadcast notification that a new message has // been allocated callback.notifyMessageIdAllocated(sendOrSaveMessage, new Message(messageCursor)); } } finally { messageCursor.close(); } } } } } finally { // Close any opened file descriptors closeOpenedAttachmentFds(sendOrSaveMessage); } }
From source file:com.enadein.carlogbook.core.DataLoader.java
@Override public DataInfo loadInBackground() { data = new DataInfo(); ContentResolver cr = getContext().getContentResolver(); switch (type) { case DASHBOARD: { long carId = DBUtils.getActiveCarId(cr); Dashboard dashboard = data.getDashboard(); dashboard.setTotalOdometerCount(DBUtils.getOdometerCount(carId, cr, 0, 0, -1)); dashboard.setTotalPrice(DBUtils.getTotalPrice(carId, cr)); dashboard.setTotalFuelCount(DBUtils.getTotalFuel(carId, cr, 0, 0, false)); dashboard.setPricePer1(DBUtils.getPricePer1km(carId, cr, 0, 0)); dashboard.setPriceFuelPer1(DBUtils.getPriceFuelPer1km(carId, cr, 0, 0)); UnitFacade customUnit = new UnitFacade(getContext()); customUnit.setConsumptionValue(2); dashboard.setFuelRateAvg(DBUtils.getAvgFuel(carId, cr, 0, 0, customUnit)); customUnit.setConsumptionValue(0); dashboard.setFuelRateAvg100(DBUtils.getAvgFuel(carId, cr, 0, 0, customUnit)); customUnit.setConsumptionValue(1); dashboard.setFuelRateAvg2(DBUtils.getAvgFuel(carId, cr, 0, 0, customUnit)); dashboard.setTotalFuelPrice(DBUtils.getTotalPrice(carId, cr, 0, 0, ProviderDescriptor.Log.Type.FUEL)); dashboard.setTotalServicePrice(//from ww w . j a v a 2 s . c om DBUtils.getTotalPrice(carId, cr, 0, 0, ProviderDescriptor.Log.Type.OTHER, DataInfo.service)); dashboard.setTotalOtherPrice( DBUtils.getTotalPrice(carId, cr, 0, 0, ProviderDescriptor.Log.Type.OTHER, DataInfo.other)); dashboard.setTotalParkingPrice( DBUtils.getTotalPrice(carId, cr, 0, 0, ProviderDescriptor.Log.Type.OTHER, DataInfo.parking)); dashboard.setTotalPartsPrice( DBUtils.getTotalPrice(carId, cr, 0, 0, ProviderDescriptor.Log.Type.OTHER, DataInfo.parts)); Calendar c = Calendar.getInstance(); CommonUtils.trunkMonth(c); c.add(Calendar.MONTH, -3); ArrayList<BarInfo> bars = new ArrayList<BarInfo>(); addMonthTotalPrice(c, cr, bars); addMonthTotalPrice(c, cr, bars); addMonthTotalPrice(c, cr, bars); addMonthTotalPrice(c, cr, bars); dashboard.setCostLast4Months(bars); c = Calendar.getInstance(); CommonUtils.trunkMonth(c); c.add(Calendar.MONTH, -3); bars = new ArrayList<BarInfo>(); addMonthTotalRun(c, cr, bars); addMonthTotalRun(c, cr, bars); addMonthTotalRun(c, cr, bars); addMonthTotalRun(c, cr, bars); dashboard.setRunLast4Months(bars); break; } case TYPE: { long from = 0; long to = 0; if (params != null) { from = params.getLong(FROM); to = params.getLong(TO); } String[] logTypes = getContext().getResources().getStringArray(R.array.log_type); ArrayList<ReportItem> reportItems = new ArrayList<ReportItem>(); long carId = DBUtils.getActiveCarId(cr); double allCost = DBUtils.getTotalPrice(carId, cr, from, to, -1, null); double fuelTotal = DBUtils.getTotalPrice(carId, cr, from, to, ProviderDescriptor.Log.Type.FUEL, null); if (fuelTotal > 0.) { ReportItem reportItem = new ReportItem(); String p = CommonUtils.wrapPt(unitFacade, fuelTotal, allCost); reportItem.setName(getContext().getString(R.string.total_fuel_cost) + p); reportItem.setResId(R.drawable.fuel); reportItem.setValue(fuelTotal); reportItems.add(reportItem); } for (int i = 1; i < logTypes.length; i++) { double total = DBUtils.getTotalPrice(carId, cr, from, to, ProviderDescriptor.Log.Type.OTHER, new int[] { i }); String p = CommonUtils.wrapPt(unitFacade, total, allCost); if (total > 0) { ReportItem reportItem = new ReportItem(); reportItem.setName(logTypes[i] + p); reportItem.setResId(DataInfo.images.get(i)); reportItem.setValue(total); reportItems.add(reportItem); } } Cursor othersCursor = cr.query(ProviderDescriptor.DataValue.CONTENT_URI, null, ProviderDescriptor.DataValue.Cols.TYPE + " = " + ProviderDescriptor.DataValue.Type.OTHERS, null, null); while (othersCursor.moveToNext()) { long otherId = othersCursor .getLong(othersCursor.getColumnIndex(ProviderDescriptor.DataValue.Cols._ID)); String name = othersCursor .getString(othersCursor.getColumnIndex(ProviderDescriptor.DataValue.Cols.NAME)); double total = DBUtils.getTotalPrice(carId, cr, from, to, ProviderDescriptor.Log.Type.OTHER, new int[] { 0 }, false, otherId); if (total > 0) { ReportItem reportItem = new ReportItem(); String p = CommonUtils.wrapPt(unitFacade, total, allCost); reportItem.setName(name + p); reportItem.setResId(DataInfo.images.get(0)); reportItem.setValue(total); reportItems.add(reportItem); } } othersCursor.close(); if (reportItems.size() > 0) { Collections.sort(reportItems, new Comparator<ReportItem>() { @Override public int compare(ReportItem reportItem, ReportItem reportItem2) { return reportItem.getValue() > reportItem2.getValue() ? -1 : 0; } }); ReportItem reportItem = new ReportItem(); reportItem.setName(getContext().getString(R.string.total_cost)); reportItem.setResId(R.drawable.coint); reportItem.setValue(allCost); reportItems.add(reportItem); } else { addNotFoundItem(reportItems); } data.setReportData(reportItems); break; } case LAST_EVENTS: { long currentTime = System.currentTimeMillis(); String daysLb = getContext().getString(R.string.days); ArrayList<ReportItem> reportItems = new ArrayList<ReportItem>(); String[] logTypes = getContext().getResources().getStringArray(R.array.log_type); long date = DBUtils.getLastEventDate(cr, ProviderDescriptor.Log.Type.FUEL, -1); if (date > 0) { double dayPassed = DBUtils.calcDayPassedTrunk(date, currentTime); String dS = DBUtils.formatDays(dayPassed, daysLb); ReportItem reportItem = new ReportItem(); reportItem.setName(getContext().getString(R.string.total_fuel_cost) + dS); reportItem.setResId(R.drawable.fuel); reportItem.setValue2(date); reportItems.add(reportItem); } for (int i = 1; i < logTypes.length; i++) { date = DBUtils.getLastEventDate(cr, ProviderDescriptor.Log.Type.OTHER, i); if (date > 0) { double dayPassed = DBUtils.calcDayPassedTrunk(date, currentTime); String dS = DBUtils.formatDays(dayPassed, daysLb); ReportItem reportItem = new ReportItem(); reportItem.setName(logTypes[i] + dS); reportItem.setResId(DataInfo.images.get(i)); reportItem.setValue2(date); reportItems.add(reportItem); } } Cursor othersCursor = cr.query(ProviderDescriptor.DataValue.CONTENT_URI, null, ProviderDescriptor.DataValue.Cols.TYPE + " = " + ProviderDescriptor.DataValue.Type.OTHERS, null, null); while (othersCursor.moveToNext()) { long otherId = othersCursor .getLong(othersCursor.getColumnIndex(ProviderDescriptor.DataValue.Cols._ID)); String name = othersCursor .getString(othersCursor.getColumnIndex(ProviderDescriptor.DataValue.Cols.NAME)); date = DBUtils.getLastEventDate(cr, ProviderDescriptor.Log.Type.OTHER, 0, otherId); if (date > 0) { double dayPassed = DBUtils.calcDayPassedTrunk(date, currentTime); String dS = DBUtils.formatDays(dayPassed, daysLb); ReportItem reportItem = new ReportItem(); reportItem.setName(name + dS); reportItem.setResId(DataInfo.images.get(0)); reportItem.setValue2(date); reportItems.add(reportItem); } } othersCursor.close(); if (reportItems.size() > 0) { Collections.sort(reportItems, new Comparator<ReportItem>() { @Override public int compare(ReportItem reportItem, ReportItem reportItem2) { return reportItem.getValue2() > reportItem2.getValue2() ? -1 : 0; } }); } else { addNotFoundItem(reportItems); } data.setReportData(reportItems); break; } case CALC_RATE: { ReportFacade reportFacade = new ReportFacade(getContext()); reportFacade.calculateFuelRate(unitFacade); break; } case DETAILED: { ReportFacade reportFacade = new ReportFacade(getContext()); long carId = DBUtils.getActiveCarId(cr); XReport xReport = new XReport(); xReport.fuelCountTotal = reportFacade.getFuelCountTotal(cr, carId); xReport.fillupCount = reportFacade.getFillupCount(cr, carId); xReport.minFillupVolume = reportFacade.getMinFillupVolume(cr, carId); xReport.maxFillupVolume = reportFacade.getMaxFillupVolume(cr, carId); xReport.avgFillupVolume = reportFacade.getAvgFillupVolume(cr, carId); xReport.fuelVolumeCurrentMonth = reportFacade.getFuelCountCurrentMonth(cr, carId); xReport.fuelVolumeLastMonth = reportFacade.getFuelCountLastMonth(cr, carId); xReport.fuelVolumeCurrentYear = reportFacade.getFuelCountCurrentYear(cr, carId); xReport.fuelVolumeLastYear = reportFacade.getFuelCountLastYear(cr, carId); xReport.totalDist = reportFacade.getTotalDistance(cr, carId); xReport.odometer_count = reportFacade.getOdometer(cr, carId); xReport.month_dist = reportFacade.getCurrentMonthDistance(cr, carId); xReport.last_month_dist = reportFacade.getLastMonthDistance(cr, carId); xReport.year_dist = reportFacade.getCurrentYearDistance(cr, carId); xReport.last_year_dist = reportFacade.getLastYearDistance(cr, carId); xReport.per_day_dist = reportFacade.getAVGDistancePerDay(cr, carId); xReport.per_month_dist = reportFacade.getAVGDistancePerMonth(cr, carId); xReport.per_year_dist = reportFacade.getAVGDistancePerYear(cr, carId); xReport.cost_total = reportFacade.getTotalCost(cr, carId); xReport.cost_per1 = reportFacade.getCostPer1Dist(cr, carId); xReport.cost_fuel_per1 = DBUtils.getPriceFuelPer1km(carId, cr, 0, 0); xReport.cost_total_month = reportFacade.getTotalCostThisMonth(cr, carId); xReport.cost_total_last_month = reportFacade.getTotalCostLastMonth(cr, carId); xReport.cost_total_year = reportFacade.getTotalCostThisYear(cr, carId); xReport.cost_total_last_year = reportFacade.getTotalCostLastYear(cr, carId); xReport.cost_price_min = reportFacade.getMinFuelPrice1Unit(cr, carId); xReport.cost_price_max = reportFacade.getMaxFuelPrice1Unit(cr, carId); xReport.cost_price_avg = reportFacade.getAvgFuelPrice1Unit(cr, carId); xReport.cost_fillup_min = reportFacade.getMinCostFillup(cr, carId); xReport.cost_fillup_max = reportFacade.getMaxCostFillup(cr, carId); xReport.cost_fillup_avg = reportFacade.getAvgCostFillup(cr, carId); xReport.cost_total_per_day = reportFacade.getAvgTotalCostPerDay(cr, carId); xReport.cost_total_per_month = reportFacade.getAvgTotalCostPerMonth(cr, carId); xReport.cost_total_per_year = reportFacade.getAvgTotalCostPerYear(cr, carId); xReport.cost_total_per_day_fuel = reportFacade.getAvgFuelCostPerDay(cr, carId); xReport.cost_total_per_month_fuel = reportFacade.getAvgFuelCostPerMonth(cr, carId); xReport.cost_total_per_year_fuel = reportFacade.getAvgFuelCostPerYear(cr, carId); xReport.cost_total_per_day_other = reportFacade.getAvgOtherExpensesCostPerDay(cr, carId); xReport.cost_total_per_month_other = reportFacade.getAvgOhterExpensesCostPerMonth(cr, carId); xReport.cost_total_per_year_other = reportFacade.getAvgOtherExpensesCostPerYear(cr, carId); xReport.avg100 = reportFacade.getAvgLPer100(cr, carId); xReport.avglperkm = reportFacade.getAvgLPer1Km(cr, carId); xReport.avgkmperl = reportFacade.getAvgKmPerL(cr, carId); reportFacade.calculateXReport(xReport, cr, carId); data.setxReport(xReport); break; } case CARS: { CarsDataInfo cdi = new CarsDataInfo(); Cursor cursor = cr.query(ProviderDescriptor.Car.CONTENT_URI, null, null, null, null); // if (cursor != null) { // String[] adapterCols = new String[]{ProviderDescriptor.DataValue.Cols.NAME}; // int[] adapterRowViews = new int[]{android.R.id.text1}; // SimpleCursorAdapter carsAdapter = new SimpleCursorAdapter(getContext(), R.layout.nav_item, // cursor, adapterCols, adapterRowViews, 0); // carsAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item); // int position = getPositionFromAdapterById(carsAdapter, DBUtils.getActiveCarId(cr)); // // cdi.setAdapter(carsAdapter); // cdi.setPosition(position); // } cdi.setCursor(cursor); cdi.setPosition(getPosition(cursor, DBUtils.getActiveCarId(cr))); data.setCarsDataInfo(cdi); break; } } return data; }
From source file:com.xmobileapp.rockplayer.RockPlayer.java
/********************************************** * //from w w w . j a v a2 s . c o m * External function from MusicUtils.java of * Android's Music App * * --- still needs to be tested * **********************************************/ public boolean isMediaScannerScanning(Context context, ContentResolver contentResolver) { boolean result = false; Cursor cursor = contentResolver.query(MediaStore.getMediaScannerUri(), new String[] { MediaStore.MEDIA_SCANNER_VOLUME }, null, null, null); if (cursor != null) { if (cursor.getCount() == 1) { cursor.moveToFirst(); result = "external".equals(cursor.getString(0)); } cursor.close(); } return result; }
From source file:edu.mit.mobile.android.locast.data.Sync.java
/** * Given a live cursor pointing to a data item and/or a set of contentValues loaded from the network, * attempt to sync.//from w w w . j a v a 2s . co m * Either c or cvNet can be null, but not both. * @param c A cursor pointing to the data item. Null is OK here. * @param jsonObject JSON object for the item as loaded from the network. null is OK here. * @param sync An empty JsonSyncableItem object. * @param publicPath TODO * * @return True if the item has been modified on either end. * @throws IOException */ private boolean syncItem(Uri toSync, Cursor c, JSONObject jsonObject, JsonSyncableItem sync, SyncProgressNotifier syncProgress, String publicPath) throws SyncException, IOException { boolean modified = false; boolean needToCloseCursor = false; boolean toSyncIsIndex = false; final SyncMap syncMap = sync.getSyncMap(); Uri locUri = null; final Uri origToSync = toSync; ContentValues cvNet = null; final Context context = getApplicationContext(); final ContentResolver cr = context.getContentResolver(); if (jsonObject != null) { if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) { // we successfully loaded it from the 'net, but toSync is really for local URIs. Erase it. toSync = sync.getContentUri(); if (toSync == null) { if (DEBUG) { Log.w(TAG, "cannot get local URI for " + origToSync + ". Skipping..."); } return false; } } try { cvNet = JsonSyncableItem.fromJSON(context, null, jsonObject, syncMap); } catch (final Exception e) { final SyncException se = new SyncException("Problem loading JSON object."); se.initCause(e); throw se; } } final String contentType = cr.getType(toSync); if (c != null) { if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) { locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID))) .buildUpon().query(null).build(); toSyncIsIndex = true; } else { locUri = toSync; } // skip any items already sync'd if (mLastUpdated.isUpdatedRecently(locUri)) { return false; } final int draftCol = c.getColumnIndex(TaggableItem._DRAFT); if (draftCol != -1 && c.getInt(draftCol) != 0) { if (DEBUG) { Log.d(TAG, locUri + " is marked a draft. Not syncing."); } return false; } syncMap.onPreSyncItem(cr, locUri, c); } else if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) { // strip any query strings toSync = toSync.buildUpon().query(null).build(); } // if (c != null){ // MediaProvider.dumpCursorToLog(c, sync.getFullProjection()); // } // when the PUBLIC_URI is null, that means it's only local final int pubUriColumn = (c != null) ? c.getColumnIndex(JsonSyncableItem._PUBLIC_URI) : -1; if (c != null && (c.isNull(pubUriColumn) || c.getString(pubUriColumn) == "")) { // new content on the local side only. Gotta publish. try { jsonObject = JsonSyncableItem.toJSON(context, locUri, c, syncMap); if (publicPath == null) { publicPath = MediaProvider.getPostPath(this, locUri); } if (DEBUG) { Log.d(TAG, "Posting " + locUri + " to " + publicPath); } // The response from a post to create a new item should be the newly created item, // which contains the public ID that we need. jsonObject = nc.postJson(publicPath, jsonObject); final ContentValues cvUpdate = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap); if (cr.update(locUri, cvUpdate, null, null) == 1) { // at this point, server and client should be in sync. mLastUpdated.markUpdated(locUri); if (DEBUG) { Log.i(TAG, "Hooray! " + locUri + " has been posted succesfully."); } } else { Log.e(TAG, "update of " + locUri + " failed"); } modified = true; } catch (final Exception e) { final SyncException se = new SyncException(getString(R.string.error_sync_no_post)); se.initCause(e); throw se; } // only on the remote side, so pull it in. } else if (c == null && cvNet != null) { if (DEBUG) { Log.i(TAG, "Only on the remote side, using network-provided values."); } final String[] params = { cvNet.getAsString(JsonSyncableItem._PUBLIC_URI) }; c = cr.query(toSync, sync.getFullProjection(), JsonSyncableItem._PUBLIC_URI + "=?", params, null); needToCloseCursor = true; if (!c.moveToFirst()) { locUri = cr.insert(toSync, cvNet); modified = true; } else { locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID))) .buildUpon().query(null).build(); syncMap.onPreSyncItem(cr, locUri, c); } } // we've now found data on both sides, so sync them. if (!modified && c != null) { publicPath = c.getString(c.getColumnIndex(JsonSyncableItem._PUBLIC_URI)); try { if (cvNet == null) { try { if (publicPath == null && toSyncIsIndex && !MediaProvider.canSync(locUri)) { // At this point, we've already checked the index and it doesn't contain the item (otherwise it would be in the syncdItems). // If we can't sync individual items, it's possible that the index is paged or the item has been deleted. if (DEBUG) { Log.w(TAG, "Asked to sync " + locUri + " but item wasn't in server index and cannot sync individual entries. Skipping and hoping it is up to date."); } return false; } else { if (mLastUpdated.isUpdatedRecently(nc.getFullUri(publicPath))) { if (DEBUG) { Log.d(TAG, "already sync'd! " + publicPath); } return false; } if (jsonObject == null) { jsonObject = nc.getObject(publicPath); } cvNet = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap); } } catch (final HttpResponseException hre) { if (hre.getStatusCode() == HttpStatus.SC_NOT_FOUND) { final SyncItemDeletedException side = new SyncItemDeletedException(locUri); side.initCause(hre); throw side; } } } if (cvNet == null) { Log.e(TAG, "got null values from fromJSON() on item " + locUri + ": " + (jsonObject != null ? jsonObject.toString() : "<< no json object >>")); return false; } final Date netLastModified = new Date(cvNet.getAsLong(JsonSyncableItem._MODIFIED_DATE)); final Date locLastModified = new Date(c.getLong(c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE))); if (netLastModified.equals(locLastModified)) { // same! yay! We don't need to do anything. if (DEBUG) { Log.d("LocastSync", locUri + " doesn't need to sync."); } } else if (netLastModified.after(locLastModified)) { // remote is more up to date, update! cr.update(locUri, cvNet, null, null); if (DEBUG) { Log.d("LocastSync", cvNet + " is newer than " + locUri); } modified = true; } else if (netLastModified.before(locLastModified)) { // local is more up to date, propagate! jsonObject = nc.putJson(publicPath, JsonSyncableItem.toJSON(context, locUri, c, syncMap)); if (DEBUG) { Log.d("LocastSync", cvNet + " is older than " + locUri); } modified = true; } mLastUpdated.markUpdated(nc.getFullUri(publicPath)); } catch (final JSONException e) { final SyncException se = new SyncException( "Item sync error for path " + publicPath + ": invalid JSON."); se.initCause(e); throw se; } catch (final NetworkProtocolException e) { final SyncException se = new SyncException( "Item sync error for path " + publicPath + ": " + e.getHttpResponseMessage()); se.initCause(e); throw se; } finally { if (needToCloseCursor) { c.close(); needToCloseCursor = false; } } } if (needToCloseCursor) { c.close(); } if (locUri == null) { throw new RuntimeException("Never got a local URI for a sync'd item."); } // two calls are made in two different contexts. Which context you use depends on the application. syncMap.onPostSyncItem(context, locUri, jsonObject, modified); sync.onPostSyncItem(context, locUri, jsonObject, modified); mLastUpdated.markUpdated(locUri); // needed for things that may have requested a sync with a different URI than what was eventually produced. if (origToSync != locUri) { mLastUpdated.markUpdated(origToSync); cr.notifyChange(origToSync, null); } return modified; }
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 .j a v a2s .co 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:me.ububble.speakall.fragment.ConversationChatFragment.java
private String getName(Uri uri) { String name = null;//from w w w . ja v a2s . c o m ContentResolver contentResolver = activity.getContentResolver(); Cursor c = contentResolver.query(uri, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null); if (c.moveToFirst()) { name = c.getString(0); } c.close(); return name; }