Example usage for android.database Cursor moveToPosition

List of usage examples for android.database Cursor moveToPosition

Introduction

In this page you can find the example usage for android.database Cursor moveToPosition.

Prototype

boolean moveToPosition(int position);

Source Link

Document

Move the cursor to an absolute position.

Usage

From source file:org.getlantern.firetweet.util.Utils.java

public static int[] getAccountColors(final Context context, final long[] accountIds) {
    if (context == null || accountIds == null)
        return new int[0];
    final String[] cols = new String[] { Accounts.ACCOUNT_ID, Accounts.COLOR };
    final String where = Expression.in(new Column(Accounts.ACCOUNT_ID), new RawItemArray(accountIds)).getSQL();
    final Cursor cur = ContentResolverUtils.query(context.getContentResolver(), Accounts.CONTENT_URI, cols,
            where, null, null);/*from  w ww.  jav a  2 s .  c om*/
    if (cur == null)
        return new int[0];
    try {
        final int[] colors = new int[cur.getCount()];
        for (int i = 0, j = cur.getCount(); i < j; i++) {
            cur.moveToPosition(i);
            colors[ArrayUtils.indexOf(accountIds, cur.getLong(0))] = cur.getInt(1);
        }
        return colors;
    } finally {
        cur.close();
    }
}

From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java

private void showMentionsNotification(AccountPreferences pref, long position) {
    final long accountId = pref.getAccountId();
    final Context context = getContext();
    final Resources resources = context.getResources();
    final NotificationManager nm = getNotificationManager();
    final Expression selection;
    if (pref.isNotificationFollowingOnly()) {
        selection = Expression.and(Expression.equals(Statuses.ACCOUNT_ID, accountId),
                Expression.greaterThan(Statuses.STATUS_ID, position),
                Expression.equals(Statuses.IS_FOLLOWING, 1));
    } else {//  ww w . j  a  va2 s  .co  m
        selection = Expression.and(Expression.equals(Statuses.ACCOUNT_ID, accountId),
                Expression.greaterThan(Statuses.STATUS_ID, position));
    }
    final String filteredSelection = Utils.buildStatusFilterWhereClause(Mentions.TABLE_NAME, selection)
            .getSQL();
    final String[] userProjection = { Statuses.USER_ID, Statuses.USER_NAME, Statuses.USER_SCREEN_NAME };
    final String[] statusProjection = { Statuses.STATUS_ID, Statuses.USER_ID, Statuses.USER_NAME,
            Statuses.USER_SCREEN_NAME, Statuses.TEXT_UNESCAPED, Statuses.STATUS_TIMESTAMP };
    final Cursor statusCursor = mDatabaseWrapper.query(Mentions.TABLE_NAME, statusProjection, filteredSelection,
            null, null, null, Statuses.SORT_ORDER_TIMESTAMP_DESC);
    final Cursor userCursor = mDatabaseWrapper.query(Mentions.TABLE_NAME, userProjection, filteredSelection,
            null, Statuses.USER_ID, null, Statuses.SORT_ORDER_TIMESTAMP_DESC);
    try {
        final int usersCount = userCursor.getCount();
        final int statusesCount = statusCursor.getCount();
        if (statusesCount == 0 || usersCount == 0)
            return;
        final String accountName = Utils.getAccountName(context, accountId);
        final String accountScreenName = Utils.getAccountScreenName(context, accountId);
        final int idxStatusText = statusCursor.getColumnIndex(Statuses.TEXT_UNESCAPED),
                idxStatusId = statusCursor.getColumnIndex(Statuses.STATUS_ID),
                idxStatusTimestamp = statusCursor.getColumnIndex(Statuses.STATUS_TIMESTAMP),
                idxStatusUserName = statusCursor.getColumnIndex(Statuses.USER_NAME),
                idxStatusUserScreenName = statusCursor.getColumnIndex(Statuses.USER_SCREEN_NAME),
                idxUserName = userCursor.getColumnIndex(Statuses.USER_NAME),
                idxUserScreenName = userCursor.getColumnIndex(Statuses.USER_NAME),
                idxUserId = userCursor.getColumnIndex(Statuses.USER_NAME);

        final CharSequence notificationTitle = resources.getQuantityString(R.plurals.N_new_mentions,
                statusesCount, statusesCount);
        final String notificationContent;
        userCursor.moveToFirst();
        final String displayName = UserColorNameUtils.getUserNickname(context, userCursor.getLong(idxUserId),
                mNameFirst ? userCursor.getString(idxUserName) : userCursor.getString(idxUserScreenName));
        if (usersCount == 1) {
            notificationContent = context.getString(R.string.notification_mention, displayName);
        } else {
            notificationContent = context.getString(R.string.notification_mention_multiple, displayName,
                    usersCount - 1);
        }

        // Add rich notification and get latest tweet timestamp
        long when = -1, statusId = -1;
        final InboxStyle style = new InboxStyle();
        for (int i = 0, j = Math.min(statusesCount, 5); statusCursor.moveToPosition(i) && i < j; i++) {
            if (when == -1) {
                when = statusCursor.getLong(idxStatusTimestamp);
            }
            if (statusId == -1) {
                statusId = statusCursor.getLong(idxStatusId);
            }
            final SpannableStringBuilder sb = new SpannableStringBuilder();
            sb.append(UserColorNameUtils.getUserNickname(context, statusCursor.getLong(idxUserId),
                    mNameFirst ? statusCursor.getString(idxStatusUserName)
                            : statusCursor.getString(idxStatusUserScreenName)));
            sb.setSpan(new StyleSpan(Typeface.BOLD), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            sb.append(' ');
            sb.append(statusCursor.getString(idxStatusText));
            style.addLine(sb);
        }
        if (mNameFirst) {
            style.setSummaryText(accountName);
        } else {
            style.setSummaryText("@" + accountScreenName);
        }

        // Setup notification
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true);
        builder.setSmallIcon(R.drawable.ic_stat_mention);
        builder.setTicker(notificationTitle);
        builder.setContentTitle(notificationTitle);
        builder.setContentText(notificationContent);
        builder.setCategory(NotificationCompat.CATEGORY_SOCIAL);
        builder.setContentIntent(getContentIntent(context, AUTHORITY_MENTIONS, accountId));
        builder.setDeleteIntent(getDeleteIntent(context, AUTHORITY_MENTIONS, accountId, statusId));
        builder.setNumber(statusesCount);
        builder.setWhen(when);
        builder.setStyle(style);
        builder.setColor(pref.getNotificationLightColor());
        setNotificationPreferences(builder, pref, pref.getMentionsNotificationType());
        nm.notify("mentions_" + accountId, NOTIFICATION_ID_MENTIONS_TIMELINE, builder.build());
        Utils.sendPebbleNotification(context, notificationContent);
    } finally {
        statusCursor.close();
        userCursor.close();
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String IsDirWritable(String sDir) {
    String sTmpDir = fixFileName(sDir);
    String sRet = sErrorPrefix + "[" + sTmpDir + "] is not a directory";

    if (sTmpDir.contains("org.mozilla.fennec") || sTmpDir.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;/*ww  w  .  j  a va 2 s.  c o m*/

        ffxFiles = Uri.parse("content://" + (sTmpDir.contains("fennec") ? fenProvider : ffxProvider) + "/dir");

        String[] columns = new String[] { "_id", "isdir", "filename", "length", "writable" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpDir, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            if (myCursor.getCount() > 0) {
                if (myCursor.moveToPosition(0)) {
                    if (myCursor.getLong(myCursor.getColumnIndex("isdir")) == 1) {
                        sRet = "[" + sTmpDir + "] "
                                + ((myCursor.getLong(myCursor.getColumnIndex("writable")) == 1) ? "is"
                                        : "is not")
                                + " writable";
                    }
                }
            }
        }
    } else {
        File dir = new File(sTmpDir);

        if (dir.isDirectory()) {
            sRet = "[" + sTmpDir + "] " + (dir.canWrite() ? "is" : "is not") + " writable";
        } else {
            sRet = sErrorPrefix + "[" + sTmpDir + "] is not a directory";
        }
    }
    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String PrintFileTimestamp(String sFile) {
    String sRet = "";
    String sTmpFileName = fixFileName(sFile);
    long lModified = -1;

    if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = Uri/*from   w w w. ja v  a  2  s .  c  o m*/
                .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/dir");

        String[] columns = new String[] { "_id", "isdir", "filename", "length", "ts" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpFileName, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            if (myCursor.getCount() > 0) {
                if (myCursor.moveToPosition(0)) {
                    lModified = myCursor.getLong(myCursor.getColumnIndex("ts"));
                }
            }
            myCursor.close();
        }
    } else {
        File theFile = new File(sTmpFileName);

        if (theFile.exists()) {
            lModified = theFile.lastModified();
        }
    }

    if (lModified != -1) {
        Date dtModified = new Date(lModified);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss:SSS");
        sRet = "Last modified: " + sdf.format(dtModified);
    } else {
        sRet = sErrorPrefix + "[" + sTmpFileName + "] doesn't exist";
    }

    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String changeDir(String newDir) {
    String tmpDir = fixFileName(newDir);
    String sRet = sErrorPrefix + "Couldn't change directory to " + tmpDir;
    int nFiles = 0;

    if (tmpDir.contains("org.mozilla.fennec") || tmpDir.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = Uri/*from w  w w .j  a  v a2 s.  c o  m*/
                .parse("content://" + (tmpDir.contains("fennec") ? fenProvider : ffxProvider) + "/dir");

        String[] columns = new String[] { "_id", "isdir", "filename" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                tmpDir, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            nFiles = myCursor.getCount();

            if (nFiles > 0) {
                if (myCursor.moveToPosition(0)) {
                    if (myCursor.getLong(myCursor.getColumnIndex("isdir")) == 1) {
                        currentDir = myCursor.getString(myCursor.getColumnIndex("filename"));
                        sRet = "";
                    }
                }
            } else {
                sRet = sErrorPrefix + tmpDir + " is not a valid directory";
            }
            myCursor.close();
        }
    } else {
        File tmpFile = new java.io.File(tmpDir);

        if (tmpFile.exists()) {
            try {
                if (tmpFile.isDirectory()) {
                    currentDir = tmpFile.getCanonicalPath();
                    sRet = "";
                } else
                    sRet = sErrorPrefix + tmpDir + " is not a valid directory";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return (sRet);
}

From source file:com.battlelancer.seriesguide.service.NotificationService.java

@SuppressLint("CommitPrefEdits")
@TargetApi(android.os.Build.VERSION_CODES.KITKAT)
@Override/*from www  .  ja  va2s  . co m*/
protected void onHandleIntent(Intent intent) {
    Timber.d("Waking up...");
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    /*
     * Handle a possible delete intent.
     */
    if (handleDeleteIntent(this, intent)) {
        return;
    }

    /*
     * Unschedule notification service wake-ups for disabled notifications
     * and non-supporters.
     */
    if (!NotificationSettings.isNotificationsEnabled(this) || !Utils.hasAccessToX(this)) {
        Timber.d("Notification service disabled, removing wakup-up alarm");
        // cancel any pending alarm
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(this, OnAlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        am.cancel(pi);

        resetLastEpisodeAirtime(prefs);

        return;
    }

    long wakeUpTime = 0;

    /*
     * Get pool of episodes which air from 12 hours ago until eternity which
     * match the users settings.
     */
    StringBuilder selection = new StringBuilder(SELECTION);
    boolean isFavsOnly = NotificationSettings.isNotifyAboutFavoritesOnly(this);
    Timber.d("Do notify about " + (isFavsOnly ? "favorites ONLY" : "ALL"));
    if (isFavsOnly) {
        selection.append(" AND ").append(Shows.SELECTION_FAVORITES);
    }
    boolean isNoSpecials = DisplaySettings.isHidingSpecials(this);
    Timber.d("Do " + (isNoSpecials ? "NOT " : "") + "notify about specials");
    if (isNoSpecials) {
        selection.append(" AND ").append(Episodes.SELECTION_NO_SPECIALS);
    }
    // always exclude hidden shows
    selection.append(" AND ").append(Shows.SELECTION_NO_HIDDEN);

    final long customCurrentTime = TimeTools.getCurrentTime(this);
    final Cursor upcomingEpisodes = getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, PROJECTION,
            selection.toString(),
            new String[] { String.valueOf(customCurrentTime - 12 * DateUtils.HOUR_IN_MILLIS) }, SORTING);

    if (upcomingEpisodes != null) {
        int notificationThreshold = NotificationSettings.getLatestToIncludeTreshold(this);
        if (DEBUG) {
            Timber.d("DEBUG MODE: notification threshold is 1 week");
            // a week, for debugging (use only one show to get single
            // episode notifications)
            notificationThreshold = 10080;
            // notify again for same episodes
            resetLastEpisodeAirtime(prefs);
        }

        final long nextEpisodeReleaseTime = NotificationSettings.getNextToNotifyAbout(this);
        // wake user-defined amount of time earlier than next episode release time
        final long plannedWakeUpTime = TimeTools.getEpisodeReleaseTime(this, nextEpisodeReleaseTime).getTime()
                - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

        /*
         * Set to -1 as on first run nextTimePlanned will be 0. This assures
         * we still see notifications of upcoming episodes then.
         */
        int newEpisodesAvailable = -1;

        // Check if we did wake up earlier than planned
        if (System.currentTimeMillis() < plannedWakeUpTime) {
            Timber.d("Woke up earlier than planned, checking for new episodes");
            newEpisodesAvailable = 0;
            long latestTimeNotified = NotificationSettings.getLastNotified(this);

            // Check if there are any earlier episodes to notify about
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime < nextEpisodeReleaseTime) {
                    if (releaseTime > latestTimeNotified) {
                        /**
                         * This will not get new episodes which would have
                         * aired the same time as the last one we notified
                         * about. Sad, but the best we can do right now.
                         */
                        newEpisodesAvailable = 1;
                        break;
                    }
                } else {
                    break;
                }
            }
        }

        if (newEpisodesAvailable == 0) {
            // Go to sleep, wake up as planned
            Timber.d("No new episodes, going to sleep.");
            wakeUpTime = plannedWakeUpTime;
        } else {
            // Get episodes which are within the notification threshold
            // (user set) and not yet cleared
            final List<Integer> notifyPositions = new ArrayList<>();
            final long latestTimeCleared = NotificationSettings.getLastCleared(this);
            final long latestTimeToInclude = customCurrentTime
                    + DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

            int position = -1;
            upcomingEpisodes.moveToPosition(position);
            while (upcomingEpisodes.moveToNext()) {
                position++;

                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime <= latestTimeToInclude) {
                    /*
                     * Only add those after the last one the user cleared.
                     * At most those of the last 24 hours (see query above).
                     */
                    if (releaseTime > latestTimeCleared) {
                        notifyPositions.add(position);
                    }
                } else {
                    // Too far into the future, stop!
                    break;
                }
            }

            // Notify if we found any episodes
            if (notifyPositions.size() > 0) {
                // store latest air time of all episodes we notified about
                upcomingEpisodes.moveToPosition(notifyPositions.get(notifyPositions.size() - 1));
                long latestAirtime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (!AndroidUtils.isHoneycombOrHigher()) {
                    /*
                     * Everything below HC does not have delete intents, so
                     * we just never notify about the same episode twice.
                     */
                    Timber.d("Delete intent NOT supported, setting last cleared to: " + latestAirtime);
                    prefs.edit().putLong(NotificationSettings.KEY_LAST_CLEARED, latestAirtime).commit();
                }
                Timber.d("Found " + notifyPositions.size() + " new episodes, setting last notified to: "
                        + latestAirtime);
                prefs.edit().putLong(NotificationSettings.KEY_LAST_NOTIFIED, latestAirtime).commit();

                onNotify(upcomingEpisodes, notifyPositions, latestAirtime);
            }

            /*
             * Plan next episode to notify about, calc wake-up alarm as
             * early as user wants.
             */
            upcomingEpisodes.moveToPosition(-1);
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime > latestTimeToInclude) {
                    // store next episode we plan to notify about
                    Timber.d("Storing next episode time to notify about: " + releaseTime);
                    prefs.edit().putLong(NotificationSettings.KEY_NEXT_TO_NOTIFY, releaseTime).commit();

                    // calc actual wake up time
                    wakeUpTime = TimeTools.getEpisodeReleaseTime(this, releaseTime).getTime()
                            - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

                    break;
                }
            }
        }

        upcomingEpisodes.close();
    }

    // Set a default wake-up time if there are no future episodes for now
    if (wakeUpTime <= 0) {
        wakeUpTime = System.currentTimeMillis() + 6 * DateUtils.HOUR_IN_MILLIS;
        Timber.d("No future episodes found, wake up in 6 hours");
    }

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    Timber.d("Going to sleep, setting wake-up alarm to: " + wakeUpTime);
    if (AndroidUtils.isKitKatOrHigher()) {
        am.setExact(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String isDirectory(String sDir) {
    String sRet = sErrorPrefix + sDir + " does not exist";
    String tmpDir = fixFileName(sDir);
    int nFiles = 0;

    if (tmpDir.contains("org.mozilla.fennec") || tmpDir.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = Uri/*from  ww  w .j a  v  a2 s  .  c o m*/
                .parse("content://" + (tmpDir.contains("fennec") ? fenProvider : ffxProvider) + "/dir");

        String[] columns = new String[] { "_id", "isdir", "filename", "length" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                tmpDir, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            nFiles = myCursor.getCount();

            // If no entries the dir is empty
            if (nFiles > 0) {
                if (myCursor.moveToPosition(0)) {
                    sRet = ((myCursor.getLong(myCursor.getColumnIndex("isdir")) == 1) ? "TRUE" : "FALSE");
                }
            }
            myCursor.close();
        }
    } else {
        File tmpFile = new java.io.File(tmpDir);

        if (tmpFile.exists()) {
            sRet = (tmpFile.isDirectory() ? "TRUE" : "FALSE");
        } else {
            try {
                pProc = Runtime.getRuntime().exec(this.getSuArgs("ls -l " + sDir));
                RedirOutputThread outThrd = new RedirOutputThread(pProc, null);
                outThrd.start();
                outThrd.joinAndStopRedirect(5000);
                sRet = outThrd.strOutput;
                if (!sRet.contains("No such file or directory") && sRet.startsWith("l"))
                    sRet = "FALSE";
            } catch (IOException e) {
                sRet = e.getMessage();
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String Cat(String fileName, OutputStream out) {
    String sTmpFileName = fixFileName(fileName);
    String sRet = sErrorPrefix + "Could not read the file " + sTmpFileName;
    byte[] buffer = new byte[4096];
    int nRead = 0;

    if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;//from  www .j  a v a  2  s.  c  o  m

        ffxFiles = Uri
                .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file");

        String[] columns = new String[] { "_id", "chunk" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpFileName, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            int nBytesRecvd = 0;

            for (int lcv = 0; lcv < nRows; lcv++) {
                if (myCursor.moveToPosition(lcv)) {
                    byte[] buf = myCursor.getBlob(1);
                    if (buf != null) {
                        nBytesRecvd += buf.length;
                        try {
                            out.write(buf);
                            sRet = "";
                        } catch (IOException e) {
                            e.printStackTrace();
                            sRet = sErrorPrefix + "Could not write to out " + sTmpFileName;
                        }
                        buf = null;
                    }
                }
            }
            if (nRows == 0) {
                sRet = "";
            }

            myCursor.close();
        }
    } else {
        try {
            FileInputStream fin = new FileInputStream(sTmpFileName);
            while ((nRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, nRead);
            }
            fin.close();
            out.flush();
            sRet = "";
        } catch (FileNotFoundException e) {
            sRet = sErrorPrefix + sTmpFileName + " No such file or directory";
        } catch (IOException e) {
            sRet = e.toString();
        }
    }
    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String HashFile(String fileName) {
    String sTmpFileName = fixFileName(fileName);
    String sRet = sErrorPrefix + "Couldn't calculate hash for file " + sTmpFileName;
    byte[] buffer = new byte[4096];
    int nRead = 0;
    long lTotalRead = 0;
    MessageDigest digest = null;//from  ww  w.j  a va 2  s .  c o  m

    try {
        digest = java.security.MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;

        ffxFiles = Uri
                .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file");

        String[] columns = new String[] { "_id", "chunk" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpFileName, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            int nBytesRecvd = 0;

            for (int lcv = 0; lcv < nRows; lcv++) {
                if (myCursor.moveToPosition(lcv)) {
                    byte[] buf = myCursor.getBlob(1);
                    if (buf != null) {
                        nBytesRecvd += buf.length;
                        digest.update(buf, 0, buf.length);
                        lTotalRead += nRead;
                        buf = null;
                    }
                }
            }
            myCursor.close();
            byte[] hash = digest.digest();

            sRet = getHex(hash);
        }
    } else {
        try {
            FileInputStream srcFile = new FileInputStream(sTmpFileName);
            while ((nRead = srcFile.read(buffer)) != -1) {
                digest.update(buffer, 0, nRead);
                lTotalRead += nRead;
            }
            srcFile.close();
            byte[] hash = digest.digest();

            sRet = getHex(hash);
        } catch (FileNotFoundException e) {
            sRet += " file not found";
        } catch (IOException e) {
            sRet += " io exception";
            e.printStackTrace();
        }
    }
    return (sRet);
}

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   w  w w.  j  ava 2  s  . 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);
}