List of usage examples for java.util.concurrent CancellationException CancellationException
public CancellationException(String message)
From source file:it.evilsocket.dsploit.core.UpdateService.java
/** * download mCurrentTask.url to mCurrentTask.path * * @throws KeyException when MD5 or SHA1 sum fails * @throws IOException when IOError occurs * @throws NoSuchAlgorithmException when required digest algorithm is not available * @throws CancellationException when user cancelled the download via notification */// w w w. j av a 2s . c o m private void downloadFile() throws SecurityException, KeyException, IOException, NoSuchAlgorithmException, CancellationException { if (mCurrentTask.url == null || mCurrentTask.path == null) return; File file = null; FileOutputStream writer = null; InputStream reader = null; HttpURLConnection connection = null; boolean exitForError = true; try { MessageDigest md5, sha1; URL url; byte[] buffer; int read; short percentage, previous_percentage; long downloaded, total; mBuilder.setContentTitle(getString(R.string.downloading_update)) .setContentText(getString(R.string.connecting)) .setSmallIcon(android.R.drawable.stat_sys_download).setProgress(100, 0, true); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); md5 = (mCurrentTask.md5 != null ? MessageDigest.getInstance("MD5") : null); sha1 = (mCurrentTask.sha1 != null ? MessageDigest.getInstance("SHA-1") : null); buffer = new byte[4096]; file = new File(mCurrentTask.path); if (file.exists() && file.isFile()) //noinspection ResultOfMethodCallIgnored file.delete(); HttpURLConnection.setFollowRedirects(true); url = new URL(mCurrentTask.url); connection = (HttpURLConnection) url.openConnection(); connection.connect(); writer = new FileOutputStream(file); reader = connection.getInputStream(); total = connection.getContentLength(); read = connection.getResponseCode(); if (read != 200) throw new IOException( String.format("cannot download '%s': responseCode: %d", mCurrentTask.url, read)); downloaded = 0; previous_percentage = -1; mBuilder.setContentText(file.getName()); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); Logger.info(String.format("downloading '%s' to '%s'", mCurrentTask.url, mCurrentTask.path)); while (mRunning && (read = reader.read(buffer)) != -1) { writer.write(buffer, 0, read); if (md5 != null) md5.update(buffer, 0, read); if (sha1 != null) sha1.update(buffer, 0, read); if (total >= 0) { downloaded += read; percentage = (short) (((double) downloaded / total) * 100); if (percentage != previous_percentage) { mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%"); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); previous_percentage = percentage; } } } if (!mRunning) throw new CancellationException("download cancelled"); Logger.info("download finished successfully"); if (md5 != null || sha1 != null) { if (md5 != null && !mCurrentTask.md5.equals(digest2string(md5.digest()))) { throw new KeyException("wrong MD5"); } else if (sha1 != null && !mCurrentTask.sha1.equals(digest2string(sha1.digest()))) { throw new KeyException("wrong SHA-1"); } } else if (mCurrentTask.archiver != null) { verifyArchiveIntegrity(); } exitForError = false; } finally { if (exitForError && file != null && file.exists() && !file.delete()) Logger.error(String.format("cannot delete file '%s'", mCurrentTask.path)); try { if (writer != null) writer.close(); if (reader != null) reader.close(); if (connection != null) connection.disconnect(); } catch (IOException e) { System.errorLogging(e); } } }
From source file:it.evilsocket.dsploit.core.UpdateService.java
/** * extract an archive into a directory/* ww w.java2s. co 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 CancellationException, RuntimeException, IOException, InterruptedException { ArchiveInputStream is = null; ArchiveEntry entry; CountingInputStream counter; File f, inFile; File[] list; String name; FileOutputStream fos = null; byte data[] = new byte[2048]; int mode; int count; long total; short percentage, old_percentage; 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)); try { inFile = new File(mCurrentTask.path); total = inFile.length(); counter = new CountingInputStream(new FileInputStream(inFile)); is = openArchiveStream(counter); old_percentage = -1; f = new File(mCurrentTask.outputDir); if (f.exists() && f.isDirectory() && (list = f.listFiles()) != null && list.length > 2) wipe(); if (is instanceof TarArchiveInputStream && mCurrentTask.modeMap == null) mCurrentTask.modeMap = new HashMap<Integer, String>(); while (mRunning && (entry = is.getNextEntry()) != null) { name = entry.getName().replaceFirst("^\\./?", ""); if (mCurrentTask.dirToExtract != null) { if (!name.startsWith(mCurrentTask.dirToExtract)) continue; else name = name.substring(mCurrentTask.dirToExtract.length()); } f = new File(mCurrentTask.outputDir, name); if (entry.isDirectory()) { if (!f.exists()) { if (!f.mkdirs()) { throw new IOException( String.format("Couldn't create directory '%s'.", f.getAbsolutePath())); } } } else { BufferedOutputStream bof = new BufferedOutputStream(new FileOutputStream(f)); while (mRunning && (count = is.read(data)) != -1) { bof.write(data, 0, count); 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; } } bof.flush(); bof.close(); } // Zip does not store file permissions. if (entry instanceof TarArchiveEntry) { mode = ((TarArchiveEntry) entry).getMode(); if (!mCurrentTask.modeMap.containsKey(mode)) mCurrentTask.modeMap.put(mode, entry.getName() + " "); else mCurrentTask.modeMap.put(mode, mCurrentTask.modeMap.get(mode).concat(entry.getName() + " ")); } } if (!mRunning) throw new CancellationException("extraction cancelled."); Logger.info("extraction completed"); f = new File(mCurrentTask.outputDir, ".nomedia"); if (f.createNewFile()) Logger.info(".nomedia created"); if (mCurrentTask.versionString != null && !mCurrentTask.versionString.isEmpty()) { f = new File(mCurrentTask.outputDir, "VERSION"); fos = new FileOutputStream(f); fos.write(mCurrentTask.versionString.getBytes()); } else Logger.warning("version string not found"); mBuilder.setContentInfo("").setProgress(100, 100, true); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } finally { if (is != null) is.close(); if (fos != null) fos.close(); } }
From source file:com.mobiperf.MeasurementScheduler.java
@SuppressWarnings("unchecked") private void uploadResults() { MeasurementResult result;/*from w w w.ja va 2s . c om*/ Future<MeasurementResult> future; JSONArray results = readResultsFromFile(); synchronized (this.pendingTasks) { try { for (MeasurementTask task : this.pendingTasks.keySet()) { future = this.pendingTasks.get(task); if (future != null) { sendStringMsg("Finished:\n" + task); if (future.isDone()) { try { this.pendingTasks.remove(task); if (!future.isCancelled()) { result = future.get(); } else { Logger.e("Task execution was canceled"); JSONObject cancelledResult = MeasurementJsonConvertor.encodeToJson(this .getFailureResult(task, new CancellationException("Task cancelled"))); results.put(cancelledResult); } } catch (InterruptedException e) { Logger.e("Task execution interrupted", e); } catch (ExecutionException e) { if (e.getCause() instanceof MeasurementSkippedException) { // Don't do anything with this - no need to report skipped measurements sendStringMsg("Task skipped - " + e.getCause().toString() + "\n" + task); Logger.i("Task skipped", e.getCause()); } else { // Log the error sendStringMsg("Task failed - " + e.getCause().toString() + "\n" + task); Logger.e("Task execution failed", e.getCause()); // Was already sent // finishedTasks.add(this.getFailureResult(task, e.getCause())); } } catch (CancellationException e) { Logger.e("Task cancelled", e); } } else if (task.isPassedDeadline()) { /* * If a task has reached its deadline but has not been run, remove it and report * failure */ this.pendingTasks.remove(task); future.cancel(true); JSONObject cancelledResult = MeasurementJsonConvertor .encodeToJson(this.getFailureResult(task, new RuntimeException("Deadline passed before execution"))); results.put(cancelledResult); } } if (future == null) { /* * Tasks that are scheduled after deadline are put into pendingTasks with a null future. */ this.pendingTasks.remove(task); JSONObject cancelledResult = MeasurementJsonConvertor.encodeToJson( this.getFailureResult(task, new RuntimeException("Task scheduled after deadline"))); results.put(cancelledResult); } } } catch (ConcurrentModificationException e) { /* * keySet is a synchronized view of the keys. However, changes during iteration will throw * ConcurrentModificationException. Since we have synchronized all changes to pendingTasks * this should not happen. */ Logger.e("Pending tasks is changed during measurement upload"); } catch (JSONException e) { e.printStackTrace(); } } if (results.length() > 0) { try { this.checkin.uploadMeasurementResult(results, resourceCapManager); } catch (IOException e) { Logger.e("Error when uploading message"); } } Logger.i("A total of " + results.length() + " uploaded"); Logger.i("A total of " + results.length() + " is in the results list"); }
From source file:org.csploit.android.core.UpdateService.java
/** * extract an archive into a directory//from w ww. j ava 2 s .co 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 CancellationException, 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; DiffMatchPatch dmp; 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; dmp = (mCurrentTask.patches != null && mCurrentTask.patches.size() > 0) ? new DiffMatchPatch() : null; 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; // patch the file if (dmp != null && mCurrentTask.patches.containsKey(name)) { buffer = new byte[(int) entry.getSize()]; IOUtils.readFully(is, buffer); writeMe = buffer = ((String) dmp.patch_apply(mCurrentTask.patches.get(name), new String(buffer))[0]).getBytes(); } outputStream = new FileOutputStream(f); // check il file is an ELF or a script if ((!isTar || mCurrentTask.fixShebang) && entry.getSize() > 4) { if (buffer == null) { 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); } } else { if (buffer[0] == 0x7F && buffer[1] == 0x45 && buffer[2] == 0x4C && buffer[3] == 0x46) { isElf = true; } else if (buffer[0] == '#' && buffer[1] == '!') { isScript = true; int newline = Arrays.binarySearch(buffer, (byte) 0x0A); if (newline < 0) newline = buffer.length; byte[] newFirstLine = new String(buffer, 0, newline) .replace("/usr/bin/env", envPath).getBytes(); writeMe = new byte[buffer.length + (newFirstLine.length - newline)]; java.lang.System.arraycopy(newFirstLine, 0, writeMe, 0, newFirstLine.length); java.lang.System.arraycopy(buffer, newline, writeMe, newFirstLine.length, newFirstLine.length - 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:com.mobilyzer.MeasurementScheduler.java
private void uploadResults() { Vector<MeasurementResult> finishedTasks = new Vector<MeasurementResult>(); MeasurementResult[] results;/*from www . ja va 2 s .c om*/ Future<MeasurementResult[]> future; Logger.d("pendingTasks: " + pendingTasks.size()); synchronized (this.pendingTasks) { try { for (MeasurementTask task : this.pendingTasks.keySet()) { future = this.pendingTasks.get(task); if (future != null) { if (future.isDone()) { this.pendingTasks.remove(task); if (future.isCancelled()) { Logger.e("Task execution was canceled"); results = MeasurementResult.getFailureResult(task, new CancellationException("Task cancelled")); for (MeasurementResult r : results) { finishedTasks.add(r); } } } } } } catch (ConcurrentModificationException e) { /* * keySet is a synchronized view of the keys. However, changes during iteration will throw * ConcurrentModificationException. Since we have synchronized all changes to pendingTasks * this should not happen. */ Logger.e("Pending tasks is changed during measurement upload"); } } Logger.i("A total of " + finishedTasks.size() + " from pendingTasks is uploaded"); Logger.i("A total of " + this.pendingTasks.size() + " is in pendingTasks"); try { for (MeasurementResult r : finishedTasks) { r.getMeasurementDesc().parameters = null; } this.checkin.uploadMeasurementResult(finishedTasks, resourceCapManager); } catch (IOException e) { Logger.e("Error when uploading message"); } }