Example usage for java.util.concurrent CancellationException CancellationException

List of usage examples for java.util.concurrent CancellationException CancellationException

Introduction

In this page you can find the example usage for java.util.concurrent CancellationException CancellationException.

Prototype

public CancellationException(String message) 

Source Link

Document

Constructs a CancellationException with the specified detail message.

Usage

From source file:org.droid2droid.internal.AbstractRemoteAndroidImpl.java

public void pushMe(final Context context, final PublishListener listener, final int bufsize, final int flags,
        final long timeout) throws RemoteException, IOException {
    new AsyncTask<PublishListener, Integer, Object>() {

        private PublishListener listener;

        @Override//from   ww w . j av  a 2s . co m
        protected Object doInBackground(PublishListener... params) {
            listener = params[0];
            FileInputStream in = null;
            int fd = -1;
            int connid = -1;
            int s;
            byte[] buf = new byte[bufsize];
            byte[] signature = null;
            try {
                PackageManager pm = context.getPackageManager();
                ApplicationInfo info = Droid2DroidManagerImpl.sAppInfo;
                String label = context.getString(info.labelRes);
                PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
                File filename = new File(info.publicSourceDir);

                int versionCode = pi.versionCode;
                signature = pi.signatures[0].toByteArray();

                long length = filename.length();
                connid = getConnectionId();
                if (V)
                    Log.v(TAG_INSTALL, PREFIX_LOG + "CLI propose apk " + info.packageName);
                fd = proposeApk(connid, label, info.packageName, versionCode, signature, length, flags,
                        timeout);
                if (fd > 0) {
                    // TODO: ask sender before send datas
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI it's accepted");
                    in = new FileInputStream(filename);
                    StringBuilder prog = new StringBuilder();
                    // TODO: multi thread for optimize read latency ?
                    long timeoutSendFile = 30000; // FIXME: Time out pour send file en dur.
                    long pos = 0;
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI send file");
                    while ((s = in.read(buf, 0, buf.length)) > 0) {
                        if (V) {
                            prog.append('*');
                            if (V)
                                Log.v(TAG_INSTALL, PREFIX_LOG + "" + prog.toString()); // TODO: A garder ?
                        }
                        if (!sendFileData(connid, fd, buf, s, pos, length, timeoutSendFile)) {
                            if (E)
                                Log.e(TAG_INSTALL, PREFIX_LOG + "Impossible to send file data");
                            throw new RemoteException();
                        }
                        pos += s;
                        publishProgress((int) ((double) pos / length * 10000L));
                    }
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI send file done");
                    if (installApk(connid, label, fd, flags, timeout)) {
                        if (V)
                            Log.v(TAG_INSTALL, PREFIX_LOG + "CLI apk is installed");
                        return 1;
                    } else {
                        if (V)
                            Log.v(TAG_INSTALL, PREFIX_LOG + "CLI install apk is canceled");
                        return new CancellationException("Install apk " + pi.packageName + " is canceled");
                    }
                } else {
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI install apk is accepted (" + fd + ")");
                    return fd;
                }
            } catch (NameNotFoundException e) {
                cancelCurrentUpload(timeout, fd, connid);
                return e;
            } catch (IOException e) {
                cancelCurrentUpload(timeout, fd, connid);
                return e;
            } catch (RemoteException e) {
                if (D)
                    Log.d(TAG_INSTALL, "Impossible to push apk (" + e.getMessage() + ")", e);
                cancelCurrentUpload(timeout, fd, connid);
                return e;
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // Ignore
                    }
                }
            }
        }

        private void cancelCurrentUpload(final long timeout, int fd, int connid) {
            if (connid != -1 && fd != -1) {
                try {
                    cancelFileData(connid, fd, timeout);
                } catch (RemoteException e1) {
                    // Ignore
                }
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            postPublishProgress(listener, values[0]);
        }

        @Override
        protected void onPostExecute(Object result) {
            if (result instanceof Throwable) {
                postPublishError(listener, (Throwable) result);
            } else
                postPublishFinish(listener, ((Integer) result).intValue());
        }
    }.execute(listener);
}

From source file:com.mobilyzer.MeasurementScheduler.java

private synchronized void handleMeasurement() {
    alarmManager.cancel(measurementIntentSender);
    setCurrentTask(null);//  w  w w .j  a v  a 2s.c om
    try {
        Logger.d("MeasurementScheduler -> In handleMeasurement " + mainQueue.size() + " "
                + waitingTasksQueue.size());
        MeasurementTask task = mainQueue.peek();
        // update the waiting queue. It contains all the tasks that are ready
        // to be executed. Here we extract all those ready tasks from main queue
        while (task != null && task.timeFromExecution() <= 0) {
            mainQueue.poll();

            if (task.getDescription().getType().equals(RRCTask.TYPE)
                    && phoneUtils.getNetwork().equals(PhoneUtils.NETWORK_WIFI)) {
                long updatedStartTime = System.currentTimeMillis() + (long) (10 * 60 * 1000);
                task.getDescription().startTime.setTime(updatedStartTime);
                mainQueue.add(task);
                Logger.i("MeasurementScheduler: handleMeasurement: delaying RRC task on "
                        + phoneUtils.getNetwork());
                task = mainQueue.peek();
                continue;
            }
            Logger.i("MeasurementScheduler: handleMeasurement: " + task.getDescription().key + " "
                    + task.getDescription().type + " added to waiting list");
            waitingTasksQueue.add(task);
            task = mainQueue.peek();
        }

        if (!phoneUtils.isNetworkAvailable()) {
            Logger.i("No connection is available, set an alarm for 5 min");
            measurementIntentSender = PendingIntent.getBroadcast(this, 0,
                    new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 60 * 1000),
                    measurementIntentSender);
            return;
        }

        if (waitingTasksQueue.size() != 0) {
            Logger.i("waiting list size is " + waitingTasksQueue.size());
            MeasurementTask ready = waitingTasksQueue.poll();
            Logger.i("ready: " + ready.getDescription().getType());

            MeasurementDesc desc = ready.getDescription();
            long newStartTime = desc.startTime.getTime() + (long) desc.intervalSec * 1000;

            if (desc.count == MeasurementTask.INFINITE_COUNT
                    && desc.priority != MeasurementTask.USER_PRIORITY) {
                if (serverTasks.containsKey(desc.toString())
                        && serverTasks.get(desc.toString()).after(desc.endTime)) {
                    ready.getDescription().endTime.setTime(serverTasks.get(desc.toString()).getTime());
                }
            }

            /**
             * Add a clone of the task if it's still valid it does not change the taskID (hashCode)
             */
            if (newStartTime < ready.getDescription().endTime.getTime()
                    && (desc.count == MeasurementTask.INFINITE_COUNT || desc.count > 1)) {
                MeasurementTask newTask = ready.clone();
                if (desc.count != MeasurementTask.INFINITE_COUNT) {
                    newTask.getDescription().count--;
                }
                newTask.getDescription().startTime.setTime(newStartTime);
                tasksStatus.put(newTask.getTaskId(), TaskStatus.SCHEDULED);
                mainQueue.add(newTask);
            } else {
                if (desc.priority != MeasurementTask.USER_PRIORITY) {
                    serverTasks.remove(desc.toString());
                }
            }

            if (ready.getDescription().endTime.before(new Date())) {
                Intent intent = new Intent();
                intent.setAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);
                intent.putExtra(UpdateIntent.TASK_STATUS_PAYLOAD, Config.TASK_CANCELED);
                MeasurementResult[] tempResults = MeasurementResult.getFailureResult(ready,
                        new CancellationException("Task cancelled!"));
                intent.putExtra(UpdateIntent.RESULT_PAYLOAD, tempResults);
                intent.putExtra(UpdateIntent.TASKID_PAYLOAD, ready.getTaskId());
                intent.putExtra(UpdateIntent.CLIENTKEY_PAYLOAD, ready.getKey());
                MeasurementScheduler.this.sendBroadcast(intent);

                if (desc.priority != MeasurementTask.USER_PRIORITY) {
                    serverTasks.remove(desc.toString());
                }

                handleMeasurement();
            } else {
                Logger.d("MeasurementScheduler -> " + ready.getDescription().getType() + " is gonna run");
                Future<MeasurementResult[]> future;
                setCurrentTask(ready);
                setCurrentTaskStartTime(Calendar.getInstance().getTime());
                if (ready.getDescription().priority == MeasurementTask.USER_PRIORITY) {
                    // User task can override the power policy. So a different task wrapper is used.
                    future = measurementExecutor.submit(new UserMeasurementTask(ready, this));
                } else {
                    future = measurementExecutor
                            .submit(new ServerMeasurementTask(ready, this, resourceCapManager));
                }

                synchronized (pendingTasks) {
                    pendingTasks.put(ready, future);
                }
            }
        } else {// if(task.timeFromExecution()>0){
            MeasurementTask waiting = mainQueue.peek();
            if (waiting != null) {
                long timeFromExecution = task.timeFromExecution();
                measurementIntentSender = PendingIntent.getBroadcast(this, 0,
                        new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
                alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeFromExecution,
                        measurementIntentSender);
                setCurrentTask(null);// TODO
                setCurrentTaskStartTime(null);
            }

        }
    } catch (IllegalArgumentException e) {
        // Task creation in clone can create this exception

    } catch (Exception e) {
        // We don't want any unexpected exception to crash the process
    }
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

/**
 * wait that a shell terminate or user cancel the notification.
 * @param shell the Thread returned by {@link it.evilsocket.dsploit.core.Shell#async(String, it.evilsocket.dsploit.core.Shell.OutputReceiver, boolean)}
 * @param cancellationMessage the message of the CancellationException
 * @throws java.io.IOException when cannot execute shell
 * @throws java.util.concurrent.CancellationException when user cancelled the notification
 *//*from  www.  j av  a 2  s .c om*/
private int execShell(Thread shell, String cancellationMessage)
        throws IOException, CancellationException, InterruptedException {
    if (!(shell instanceof Shell.StreamGobbler))
        throw new IOException("cannot execute shell commands");
    shell.start();
    while (mRunning && shell.getState() != Thread.State.TERMINATED)
        Thread.sleep(10);
    if (!mRunning) {
        shell.interrupt();
        throw new CancellationException(cancellationMessage);
    } else
        shell.join();

    int ret = ((Shell.StreamGobbler) shell).exitValue;

    if (ret != 0 && mErrorOutput.length() > 0)
        for (String line : mErrorOutput.toString().split("\n"))
            if (line.length() > 0)
                Logger.error(line);

    return ret;
}

From source file:org.csploit.android.core.UpdateService.java

/**
 * wait that a shell terminate or user cancel the notification.
 * @param child the Child returned by {@link org.csploit.android.tools.Tool#async(String)}
 * @param cancellationMessage the message of the CancellationException
 * @throws java.io.IOException when cannot execute shell
 * @throws java.util.concurrent.CancellationException when user cancelled the notification
 *//*from w w w. j a  v  a 2  s . c  om*/
private int execShell(Child child, String cancellationMessage)
        throws IOException, CancellationException, InterruptedException {
    while (mRunning && child.running)
        Thread.sleep(10);
    if (!mRunning) {
        child.kill();
        throw new CancellationException(cancellationMessage);
    }

    if ((child.exitValue != 0 || child.signal >= 0) && mErrorOutput.length() > 0)
        for (String line : mErrorOutput.toString().split("\n"))
            if (line.length() > 0)
                Logger.error(line);

    if (child.signal >= 0) {
        return 128 + child.signal;
    }
    return child.exitValue;
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

/**
 * check if an archive is valid by reading it.
 * @throws RuntimeException if trying to run this with no archive
 *///from   w w w  .j  a v  a  2  s .co m
private void verifyArchiveIntegrity() throws RuntimeException, KeyException {
    File f;
    long total;
    short old_percentage, percentage;
    CountingInputStream counter;
    ArchiveInputStream is;
    byte[] buffer;
    boolean dirToExtractFound;

    Logger.info("verifying archive integrity");

    if (mCurrentTask == null || mCurrentTask.path == null)
        throw new RuntimeException("no archive to test");

    mBuilder.setContentTitle(getString(R.string.checking)).setSmallIcon(android.R.drawable.ic_popup_sync)
            .setContentText("").setProgress(100, 0, false);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    f = new File(mCurrentTask.path);
    try {
        counter = new CountingInputStream(new FileInputStream(f));
    } catch (FileNotFoundException e) {
        throw new RuntimeException(String.format("archive '%s' does not exists", mCurrentTask.path));
    }

    dirToExtractFound = mCurrentTask.dirToExtract == null;

    try {
        is = openArchiveStream(counter);
        ArchiveEntry entry;
        buffer = new byte[2048];
        total = f.length();
        old_percentage = -1;
        // consume the archive
        while (mRunning && (entry = is.getNextEntry()) != null)
            if (!dirToExtractFound && entry.getName().startsWith(mCurrentTask.dirToExtract))
                dirToExtractFound = true;
        while (mRunning && is.read(buffer) > 0) {
            percentage = (short) (((double) counter.getBytesRead() / total) * 100);
            if (percentage != old_percentage) {
                mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                old_percentage = percentage;
            }
        }
    } catch (IOException e) {
        throw new KeyException("corrupted archive: " + e.getMessage());
    }

    if (!mRunning)
        throw new CancellationException("archive integrity check cancelled");

    if (!dirToExtractFound)
        throw new KeyException(String.format("archive '%s' does not contains required '%s' directory",
                mCurrentTask.path, mCurrentTask.dirToExtract));
}

From source file:org.csploit.android.services.UpdateService.java

/**
 * extract an archive into a directory/*from   w  w  w  . j  a v  a  2  s.c o  m*/
 *
 * @throws IOException if some I/O error occurs
 * @throws java.util.concurrent.CancellationException if task is cancelled by user
 * @throws java.lang.InterruptedException when the the running thread get cancelled.
 */
private void extract()
        throws RuntimeException, IOException, InterruptedException, ChildManager.ChildNotStartedException {
    ArchiveInputStream is = null;
    ArchiveEntry entry;
    CountingInputStream counter;
    OutputStream outputStream = null;
    File f, inFile;
    File[] list;
    String name;
    String envPath;
    final StringBuffer sb = new StringBuffer();
    int mode;
    int count;
    long total;
    boolean isTar, r, w, x, isElf, isScript;
    short percentage, old_percentage;
    Child which;

    if (mCurrentTask.path == null || mCurrentTask.outputDir == null)
        return;

    mBuilder.setContentTitle(getString(R.string.extracting)).setContentText("").setContentInfo("")
            .setSmallIcon(android.R.drawable.ic_popup_sync).setProgress(100, 0, false);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    Logger.info(String.format("extracting '%s' to '%s'", mCurrentTask.path, mCurrentTask.outputDir));

    envPath = null;
    which = null;

    try {
        if (mCurrentTask.fixShebang) {
            which = System.getTools().raw.async("which env", new Raw.RawReceiver() {
                @Override
                public void onNewLine(String line) {
                    sb.delete(0, sb.length());
                    sb.append(line);
                }
            });
        }

        inFile = new File(mCurrentTask.path);
        total = inFile.length();
        counter = new CountingInputStream(new FileInputStream(inFile));
        is = openArchiveStream(counter);
        isTar = mCurrentTask.archiver.equals(archiveAlgorithm.tar);
        old_percentage = -1;

        f = new File(mCurrentTask.outputDir);
        if (f.exists() && f.isDirectory() && (list = f.listFiles()) != null && list.length > 2)
            wipe();

        if (mCurrentTask.fixShebang) {
            if (execShell(which, "cancelled while retrieving env path") != 0) {
                throw new RuntimeException("cannot find 'env' executable");
            }
            envPath = sb.toString();
        }

        while (mRunning && (entry = is.getNextEntry()) != null) {
            name = entry.getName().replaceFirst("^\\./?", "");

            if (mCurrentTask.skipRoot) {
                if (name.contains("/"))
                    name = name.substring(name.indexOf('/') + 1);
                else if (entry.isDirectory())
                    continue;
            }

            f = new File(mCurrentTask.outputDir, name);

            isElf = isScript = false;

            if (entry.isDirectory()) {
                if (!f.exists()) {
                    if (!f.mkdirs()) {
                        throw new IOException(
                                String.format("Couldn't create directory '%s'.", f.getAbsolutePath()));
                    }
                }
            } else {
                byte[] buffer = null;
                byte[] writeMe = null;

                outputStream = new FileOutputStream(f);

                // check il file is an ELF or a script
                if ((!isTar || mCurrentTask.fixShebang) && entry.getSize() > 4) {
                    writeMe = buffer = new byte[4];

                    IOUtils.readFully(is, buffer);

                    if (buffer[0] == 0x7F && buffer[1] == 0x45 && buffer[2] == 0x4C && buffer[3] == 0x46) {
                        isElf = true;
                    } else if (buffer[0] == '#' && buffer[1] == '!') {
                        isScript = true;

                        ByteArrayOutputStream firstLine = new ByteArrayOutputStream();
                        int newline = -1;

                        // assume that '\n' is more far then 4 chars.
                        firstLine.write(buffer);
                        buffer = new byte[1024];
                        count = 0;

                        while (mRunning && (count = is.read(buffer)) >= 0
                                && (newline = Arrays.binarySearch(buffer, 0, count, (byte) 0x0A)) < 0) {
                            firstLine.write(buffer, 0, count);
                        }

                        if (!mRunning) {
                            throw new CancellationException("cancelled while searching for newline.");
                        } else if (count < 0) {
                            newline = count = 0;
                        } else if (newline < 0) {
                            newline = count;
                        }

                        firstLine.write(buffer, 0, newline);
                        firstLine.close();

                        byte[] newFirstLine = new String(firstLine.toByteArray())
                                .replace("/usr/bin/env", envPath).getBytes();

                        writeMe = new byte[newFirstLine.length + (count - newline)];

                        java.lang.System.arraycopy(newFirstLine, 0, writeMe, 0, newFirstLine.length);
                        java.lang.System.arraycopy(buffer, newline, writeMe, newFirstLine.length,
                                count - newline);
                    }
                }

                if (writeMe != null) {
                    outputStream.write(writeMe);
                }

                IOUtils.copy(is, outputStream);

                outputStream.close();
                outputStream = null;

                percentage = (short) (((double) counter.getBytesRead() / total) * 100);
                if (percentage != old_percentage) {
                    mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                    old_percentage = percentage;
                }
            }
            // Zip does not store file permissions.
            if (isTar) {
                mode = ((TarArchiveEntry) entry).getMode();

                r = (mode & 0400) > 0;
                w = (mode & 0200) > 0;
                x = (mode & 0100) > 0;
            } else if (isElf || isScript) {
                r = w = x = true;
            } else {
                continue;
            }

            if (!f.setExecutable(x, true)) {
                Logger.warning(String.format("cannot set executable permission of '%s'", name));
            }

            if (!f.setWritable(w, true)) {
                Logger.warning(String.format("cannot set writable permission of '%s'", name));
            }

            if (!f.setReadable(r, true)) {
                Logger.warning(String.format("cannot set readable permission of '%s'", name));
            }
        }

        if (!mRunning)
            throw new CancellationException("extraction cancelled.");

        Logger.info("extraction completed");

        f = new File(mCurrentTask.outputDir, ".nomedia");
        if (f.createNewFile())
            Logger.info(".nomedia created");

        mBuilder.setContentInfo("").setProgress(100, 100, true);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    } finally {
        if (is != null)
            is.close();
        if (outputStream != null)
            outputStream.close();
    }
}

From source file:org.csploit.android.core.UpdateService.java

/**
 * check if an archive is valid by reading it.
 * @throws RuntimeException if trying to run this with no archive
 *//*from w ww.  jav  a 2 s.  co  m*/
private void verifyArchiveIntegrity() throws RuntimeException, KeyException {
    File f;
    long total;
    short old_percentage, percentage;
    CountingInputStream counter;
    ArchiveInputStream is;
    byte[] buffer;
    String rootDirectory;

    Logger.info("verifying archive integrity");

    if (mCurrentTask == null || mCurrentTask.path == null)
        throw new RuntimeException("no archive to test");

    mBuilder.setContentTitle(getString(R.string.checking)).setSmallIcon(android.R.drawable.ic_popup_sync)
            .setContentText("").setProgress(100, 0, false);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    f = new File(mCurrentTask.path);
    try {
        counter = new CountingInputStream(new FileInputStream(f));
    } catch (FileNotFoundException e) {
        throw new RuntimeException(String.format("archive '%s' does not exists", mCurrentTask.path));
    }

    try {
        is = openArchiveStream(counter);
        ArchiveEntry entry;
        buffer = new byte[2048];
        total = f.length();
        old_percentage = -1;
        rootDirectory = null;

        // consume the archive
        while (mRunning && (entry = is.getNextEntry()) != null) {
            if (!mCurrentTask.skipRoot)
                continue;

            String name = entry.getName();

            if (rootDirectory == null) {
                if (name.contains("/")) {
                    rootDirectory = name.substring(0, name.indexOf('/'));
                } else if (entry.isDirectory()) {
                    rootDirectory = name;
                } else {
                    throw new IOException(
                            String.format("archive '%s' contains files under it's root", mCurrentTask.path));
                }
            } else {
                if (!name.startsWith(rootDirectory)) {
                    throw new IOException("multiple directories found in the archive root");
                }
            }
        }

        while (mRunning && is.read(buffer) > 0) {
            percentage = (short) (((double) counter.getBytesRead() / total) * 100);
            if (percentage != old_percentage) {
                mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                old_percentage = percentage;
            }
        }
    } catch (IOException e) {
        throw new KeyException("corrupted archive: " + e.getMessage());
    } finally {
        try {
            counter.close();
        } catch (IOException ignore) {
        }
    }

    if (!mRunning)
        throw new CancellationException("archive integrity check cancelled");

    if (mCurrentTask.skipRoot && rootDirectory == null)
        throw new KeyException(String.format("archive '%s' is empty", mCurrentTask.path));
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

/**
 * check if mLocalFile exists./*  www.j  a va  2  s  .c om*/
 *
 * @return true if file exists and match md5sum and sha1sum.
 * @throws java.util.concurrent.CancellationException when check is cancelled by user
 * @throws SecurityException bad file permissions
 * @throws IOException when IOException occurs
 * @throws java.security.NoSuchAlgorithmException when digests cannot be created
 * @throws java.security.KeyException when file checksum fails
 */
private boolean haveLocalFile()
        throws CancellationException, SecurityException, IOException, NoSuchAlgorithmException, KeyException {

    File file = null;
    InputStream reader = null;
    boolean exitForError = true;

    if (mCurrentTask.path == null)
        return false;

    try {
        MessageDigest md5, sha1;
        byte[] buffer;
        int read;
        short percentage, previous_percentage;
        long read_counter, total;

        file = new File(mCurrentTask.path);
        buffer = new byte[4096];
        total = file.length();
        read_counter = 0;
        previous_percentage = -1;

        if (!file.exists() || !file.isFile())
            return false;

        if (!file.canWrite() || !file.canRead()) {
            read = -1;
            try {
                read = Shell.exec(String.format("chmod 777 '%s'", mCurrentTask.path));
            } catch (Exception e) {
                System.errorLogging(e);
            }
            if (read != 0)
                throw new SecurityException(String.format("bad file permissions for '%s', chmod returned: %d",
                        mCurrentTask.path, read));
        }

        if (mCurrentTask.md5 != null || mCurrentTask.sha1 != null) {
            mBuilder.setContentTitle(getString(R.string.checking))
                    .setSmallIcon(android.R.drawable.ic_popup_sync).setContentText("")
                    .setProgress(100, 0, false);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

            md5 = (mCurrentTask.md5 != null ? MessageDigest.getInstance("MD5") : null);
            sha1 = (mCurrentTask.sha1 != null ? MessageDigest.getInstance("SHA-1") : null);

            reader = new FileInputStream(file);
            while (mRunning && (read = reader.read(buffer)) != -1) {
                if (md5 != null)
                    md5.update(buffer, 0, read);
                if (sha1 != null)
                    sha1.update(buffer, 0, read);

                read_counter += read;

                percentage = (short) (((double) read_counter / total) * 100);
                if (percentage != previous_percentage) {
                    mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                    previous_percentage = percentage;
                }
            }
            reader.close();
            reader = null;
            if (!mRunning) {
                exitForError = false;
                throw new CancellationException("local file check cancelled");
            }
            if (md5 != null && !mCurrentTask.md5.equals(digest2string(md5.digest())))
                throw new KeyException("wrong MD5");
            if (sha1 != null && !mCurrentTask.sha1.equals(digest2string(sha1.digest())))
                throw new KeyException("wrong SHA-1");
            Logger.info(String.format("checksum ok: '%s'", mCurrentTask.path));
        } else if (mCurrentTask.archiver != null) {
            verifyArchiveIntegrity();
        }
        Logger.info(String.format("file already exists: '%s'", mCurrentTask.path));
        mBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done)
                .setContentTitle(getString(R.string.update_available))
                .setContentText(getString(R.string.click_here_to_upgrade)).setProgress(0, 0, false) // remove progress bar
                .setAutoCancel(true);
        exitForError = false;
        return true;
    } finally {
        if (exitForError && file != null && file.exists() && !file.delete())
            Logger.error(String.format("cannot delete local file '%s'", mCurrentTask.path));
        try {
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            System.errorLogging(e);
        }
    }
}

From source file:org.csploit.android.core.UpdateService.java

/**
 * check if mLocalFile exists./*from w  ww. j  a va 2s .c o m*/
 *
 * @return true if file exists and match md5sum and sha1sum.
 * @throws java.util.concurrent.CancellationException when check is cancelled by user
 * @throws SecurityException bad file permissions
 * @throws IOException when IOException occurs
 * @throws java.security.NoSuchAlgorithmException when digests cannot be created
 * @throws java.security.KeyException when file checksum fails
 */
private boolean haveLocalFile()
        throws CancellationException, SecurityException, IOException, NoSuchAlgorithmException, KeyException {

    File file = null;
    InputStream reader = null;
    boolean exitForError = true;

    if (mCurrentTask.path == null)
        return false;

    try {
        MessageDigest md5, sha1;
        byte[] buffer;
        int read;
        short percentage, previous_percentage;
        long read_counter, total;

        file = new File(mCurrentTask.path);
        buffer = new byte[4096];
        total = file.length();
        read_counter = 0;
        previous_percentage = -1;

        if (!file.exists() || !file.isFile())
            return false;

        if (!file.canWrite() || !file.canRead()) {
            read = -1;
            try {
                read = System.getTools().raw.run(String.format("chmod 777 '%s'", mCurrentTask.path));
            } catch (Exception e) {
                System.errorLogging(e);
            }
            if (read != 0)
                throw new SecurityException(String.format("bad file permissions for '%s', chmod returned: %d",
                        mCurrentTask.path, read));
        }

        if (mCurrentTask.md5 != null || mCurrentTask.sha1 != null) {
            mBuilder.setContentTitle(getString(R.string.checking))
                    .setSmallIcon(android.R.drawable.ic_popup_sync).setContentText("")
                    .setProgress(100, 0, false);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

            md5 = (mCurrentTask.md5 != null ? MessageDigest.getInstance("MD5") : null);
            sha1 = (mCurrentTask.sha1 != null ? MessageDigest.getInstance("SHA-1") : null);

            reader = new FileInputStream(file);
            while (mRunning && (read = reader.read(buffer)) != -1) {
                if (md5 != null)
                    md5.update(buffer, 0, read);
                if (sha1 != null)
                    sha1.update(buffer, 0, read);

                read_counter += read;

                percentage = (short) (((double) read_counter / total) * 100);
                if (percentage != previous_percentage) {
                    mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                    previous_percentage = percentage;
                }
            }
            reader.close();
            reader = null;
            if (!mRunning) {
                exitForError = false;
                throw new CancellationException("local file check cancelled");
            }
            if (md5 != null && !mCurrentTask.md5.equals(digest2string(md5.digest())))
                throw new KeyException("wrong MD5");
            if (sha1 != null && !mCurrentTask.sha1.equals(digest2string(sha1.digest())))
                throw new KeyException("wrong SHA-1");
            Logger.info(String.format("checksum ok: '%s'", mCurrentTask.path));
        } else if (mCurrentTask.archiver != null) {
            verifyArchiveIntegrity();
        }
        Logger.info(String.format("file already exists: '%s'", mCurrentTask.path));
        mBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done)
                .setContentTitle(getString(R.string.update_available))
                .setContentText(getString(R.string.click_here_to_upgrade)).setProgress(0, 0, false) // remove progress bar
                .setAutoCancel(true);
        exitForError = false;
        return true;
    } finally {
        if (exitForError && file != null && file.exists() && !file.delete())
            Logger.error(String.format("cannot delete local file '%s'", mCurrentTask.path));
        try {
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            System.errorLogging(e);
        }
    }
}