List of usage examples for java.util.concurrent CancellationException CancellationException
public CancellationException()
From source file:ubic.gemma.core.loader.util.fetcher.FtpFetcher.java
protected Collection<LocalFile> fetch(String identifier, String seekFile) { File existingFile = null;/*from w w w. ja va 2s . c om*/ try { File newDir = mkdir(identifier); String outputFileName = formLocalFilePath(identifier, newDir); existingFile = new File(outputFileName); // if ( this.avoidDownload || ( existingFile.canRead() && allowUseExisting ) ) { // // log.info( outputFileName + " already exists." ); // } if (ftpClient == null || !ftpClient.isConnected()) { ftpClient = this.getNetDataSourceUtil().connect(FTP.BINARY_FILE_TYPE); assert ftpClient != null; // otherwise should have gotten an exception from connect() } long expectedSize = getExpectedSize(seekFile); FutureTask<Boolean> future = this.defineTask(outputFileName, seekFile); return this.doTask(future, expectedSize, seekFile, outputFileName); } catch (UnknownHostException e) { if (force || !allowUseExisting || existingFile == null) throw new RuntimeException(e); if (!avoidDownload) throw new RuntimeException(e); log.warn("Could not connect to " + this.getNetDataSourceUtil().getHost() + " to check size of " + seekFile + ", using existing file"); return getExistingFile(existingFile, seekFile); } catch (IOException e) { /* * Note: this block can trigger if you cancel. */ if (force || !allowUseExisting || existingFile == null) { /* * Printing to log here because runtime error does not deliver message when passed through * java.util.concurrent.FutureTask (only throws InterruptedException and ExecutionException) */ log.error("Runtime exception thrown: " + e.getMessage() + ". \n Stack trace follows:", e); throw new RuntimeException( "Cancelled, or couldn't fetch " + seekFile + ", make sure the file exists on the remote server and permissions are granted.", e); } if (Thread.currentThread().isInterrupted()) { throw new CancellationException(); } log.warn("Cancelled, or couldn't fetch " + seekFile + ", make sure the file exists on the remote server.," + e + ", using existing file"); return getExistingFile(existingFile, seekFile); } finally { try { if (ftpClient != null && ftpClient.isConnected()) ftpClient.disconnect(); } catch (IOException e) { //noinspection ThrowFromFinallyBlock throw new RuntimeException("Could not disconnect: " + e.getMessage()); } } }
From source file:com.diversityarrays.kdxplore.trialdesign.RscriptFinderPanel.java
private void doCheckScriptPath() { String scriptPath = scriptPathField.getText().trim(); BackgroundTask<Either<String, String>, Void> task = new BackgroundTask<Either<String, String>, Void>( "Checking...", true) { @Override/*w ww .j a v a 2 s . com*/ public Either<String, String> generateResult(Closure<Void> arg0) throws Exception { ProcessBuilder findRScript = new ProcessBuilder(scriptPath, "--version"); Process p = findRScript.start(); while (!p.waitFor(1000, TimeUnit.MILLISECONDS)) { if (backgroundRunner.isCancelRequested()) { p.destroy(); throw new CancellationException(); } } if (0 == p.exitValue()) { String output = Algorithms.readContent(null, p.getInputStream()); versionNumber = Algorithms.readContent(null, p.getErrorStream()); return Either.right(output); } errorOutput = Algorithms.readContent("Error Output:", p.getErrorStream()); if (errorOutput.isEmpty()) { errorOutput = "No error output available"; return Either.left(errorOutput); } return Either.left(errorOutput); } @Override public void onException(Throwable t) { onScriptPathChecked.accept(Either.left(t)); } @Override public void onCancel(CancellationException ce) { onScriptPathChecked.accept(Either.left(ce)); } @Override public void onTaskComplete(Either<String, String> either) { if (either.isLeft()) { MsgBox.error(RscriptFinderPanel.this, either.left(), "Error Output"); } else { TrialDesignPreferences.getInstance().setRscriptPath(scriptPath); onScriptPathChecked.accept(Either.right(scriptPath)); checkOutput = either.right(); } } }; backgroundRunner.runBackgroundTask(task); }
From source file:com.parse.ParseFileController.java
public Task<File> fetchAsync(final ParseFile.State state, @SuppressWarnings("UnusedParameters") String sessionToken, final ProgressCallback downloadProgressCallback, final Task<Void> cancellationToken) { if (cancellationToken != null && cancellationToken.isCancelled()) { return Task.cancelled(); }/*from ww w .j a v a 2 s . c o m*/ final File cacheFile = getCacheFile(state); return Task.call(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return cacheFile.exists(); } }, ParseExecutors.io()).continueWithTask(new Continuation<Boolean, Task<File>>() { @Override public Task<File> then(Task<Boolean> task) throws Exception { boolean result = task.getResult(); if (result) { return Task.forResult(cacheFile); } if (cancellationToken != null && cancellationToken.isCancelled()) { return Task.cancelled(); } // Generate the temp file path for caching ParseFile content based on ParseFile's url // The reason we do not write to the cacheFile directly is because there is no way we can // verify if a cacheFile is complete or not. If download is interrupted in the middle, next // time when we download the ParseFile, since cacheFile has already existed, we will return // this incomplete cacheFile final File tempFile = getTempFile(state); // network final ParseAWSRequest request = new ParseAWSRequest(ParseHttpRequest.Method.GET, state.url(), tempFile); // We do not need to delete the temp file since we always try to overwrite it return request.executeAsync(awsClient(), null, downloadProgressCallback, cancellationToken) .continueWithTask(new Continuation<Void, Task<File>>() { @Override public Task<File> then(Task<Void> task) throws Exception { // If the top-level task was cancelled, don't actually set the data -- just move on. if (cancellationToken != null && cancellationToken.isCancelled()) { throw new CancellationException(); } if (task.isFaulted()) { ParseFileUtils.deleteQuietly(tempFile); return task.cast(); } // Since we give the cacheFile pointer to developers, it is not safe to guarantee // cacheFile always does not exist here, so it is better to delete it manually, // otherwise moveFile may throw an exception. ParseFileUtils.deleteQuietly(cacheFile); ParseFileUtils.moveFile(tempFile, cacheFile); return Task.forResult(cacheFile); } }, ParseExecutors.io()); } }); }
From source file:ubic.gemma.loader.util.fetcher.FtpFetcher.java
/** * @param identifier// w w w . j a v a2 s . c o m * @param seekFile * @return */ protected Collection<LocalFile> fetch(String identifier, String seekFile) { File existingFile = null; try { File newDir = mkdir(identifier); String outputFileName = formLocalFilePath(identifier, newDir); existingFile = new File(outputFileName); if (this.avoidDownload || (existingFile.canRead() && allowUseExisting)) { // log.info( outputFileName + " already exists." ); } if (ftpClient == null || !ftpClient.isConnected()) { ftpClient = this.getNetDataSourceUtil().connect(FTP.BINARY_FILE_TYPE); assert ftpClient != null; // otherwise should have gotten an exception from connect() } long expectedSize = getExpectedSize(seekFile); FutureTask<Boolean> future = this.defineTask(outputFileName, seekFile); Collection<LocalFile> result = this.doTask(future, expectedSize, seekFile, outputFileName); return result; } catch (UnknownHostException e) { if (force || !allowUseExisting || existingFile == null) throw new RuntimeException(e); if (!avoidDownload) throw new RuntimeException(e); log.warn("Could not connect to " + this.getNetDataSourceUtil().getHost() + " to check size of " + seekFile + ", using existing file"); Collection<LocalFile> fallback = getExistingFile(existingFile, seekFile); return fallback; } catch (IOException e) { /* * Note: this block can trigger if you cancel. */ if (force || !allowUseExisting || existingFile == null) { /* * Printing to log here because runtime error does not deliver message when passed through * java.util.concurrent.FutureTask (only throws InterruptedException and ExecutionException) */ log.error("Runtime exception thrown: " + e.getMessage() + ". \n Stack trace follows:", e); throw new RuntimeException( "Cancelled, or couldn't fetch " + seekFile + ", make sure the file exists on the remote server and permissions are granted.", e); } if (Thread.currentThread().isInterrupted()) { throw new CancellationException(); } log.warn("Cancelled, or couldn't fetch " + seekFile + ", make sure the file exists on the remote server.," + e + ", using existing file"); Collection<LocalFile> fallback = getExistingFile(existingFile, seekFile); return fallback; } finally { try { if (ftpClient != null && ftpClient.isConnected()) ftpClient.disconnect(); } catch (IOException e) { throw new RuntimeException("Could not disconnect: " + e.getMessage()); } } }
From source file:org.rapidoid.http.HttpClientUtil.java
private static <T> FutureCallback<HttpResponse> callback(final CloseableHttpAsyncClient client, final Callback<HttpResp> callback, final Callback<HttpResp> promise, final boolean close) { return new FutureCallback<HttpResponse>() { @Override/* w ww . j a v a 2 s. c o m*/ public void completed(HttpResponse response) { HttpResp resp; try { resp = response(response); } catch (Exception e) { Callbacks.error(callback, e); Callbacks.error(promise, e); if (close) { close(client); } return; } Callbacks.success(callback, resp); Callbacks.success(promise, resp); if (close) { close(client); } } @Override public void failed(Exception e) { Callbacks.error(callback, e); Callbacks.error(promise, e); if (close) { close(client); } } @Override public void cancelled() { Callbacks.error(callback, new CancellationException()); Callbacks.error(promise, new CancellationException()); if (close) { close(client); } } }; }
From source file:org.gitools.analysis.clustering.kmeans.KMeansPlusPlusClusterer.java
public List<CentroidCluster<T>> cluster(final Collection<T> points, IProgressMonitor monitor) throws MathIllegalArgumentException, ConvergenceException { // number of clusters has to be smaller or equal the number of data points if (points.size() < k) { throw new NumberIsTooSmallException(points.size(), k, false); }/*from w w w .ja v a2s.c o m*/ // create the initial clusters List<CentroidCluster<T>> clusters = chooseInitialCenters(points); // create an array containing the latest assignment of a point to a cluster // no need to initialize the array, as it will be filled with the first assignment int[] assignments = new int[points.size()]; assignPointsToClusters(clusters, points, assignments); final int max = (maxIterations < 0) ? Integer.MAX_VALUE : maxIterations; for (int count = 0; count < max; count++) { // iterate through updating the centers until we're done monitor.begin("Iteration " + (count + 1), clusters.size()); boolean emptyCluster = false; List<CentroidCluster<T>> newClusters = new ArrayList<CentroidCluster<T>>(); for (final CentroidCluster<T> cluster : clusters) { monitor.worked(1); if (monitor.isCancelled()) { throw new CancellationException(); } final Clusterable newCenter; if (cluster.getPoints().isEmpty()) { switch (emptyStrategy) { case LARGEST_VARIANCE: newCenter = getPointFromLargestVarianceCluster(clusters); break; case LARGEST_POINTS_NUMBER: newCenter = getPointFromLargestNumberCluster(clusters); break; case FARTHEST_POINT: newCenter = getFarthestPoint(clusters); break; default: throw new ConvergenceException(LocalizedFormats.EMPTY_CLUSTER_IN_K_MEANS); } emptyCluster = true; } else { newCenter = centroidOf(cluster.getPoints(), cluster.getCenter().size()); } newClusters.add(new CentroidCluster<T>(newCenter)); } int changes = assignPointsToClusters(newClusters, points, assignments); clusters = newClusters; // if there were no more changes in the point-to-cluster assignment // and there are no empty clusters left, return the current clusters if (changes == 0 && !emptyCluster) { return clusters; } } return clusters; }
From source file:org.gitools.matrix.format.TdmMatrixFormat.java
private void writeCells(Writer writer, IMatrix resultsMatrix, IProgressMonitor progressMonitor) { RawFlatTextWriter out = new RawFlatTextWriter(writer, '\t', '"'); out.writeQuotedValue("column"); out.writeSeparator();// w ww. j a v a2 s. c o m out.writeQuotedValue("row"); for (IMatrixLayer layer : resultsMatrix.getLayers()) { out.writeSeparator(); out.writeQuotedValue(layer.getId()); } out.writeNewLine(); IMatrixDimension columns = resultsMatrix.getColumns(); IMatrixDimension rows = resultsMatrix.getRows(); IMatrixLayers layers = resultsMatrix.getLayers(); String[] values = new String[layers.size()]; for (String column : columns) { for (String row : rows) { boolean allNulls = true; for (int l = 0; l < layers.size(); l++) { IMatrixLayer layer = layers.get(l); Object value = resultsMatrix.get(layer, row, column); //TODO Use IMatrixLayer translator if (value instanceof Double) { Double v = (Double) value; values[l] = DoubleTranslator.get().valueToString(v); allNulls = false; } else if (value != null) { values[l] = value.toString(); allNulls = false; } else { values[l] = "-"; } } if (!allNulls) { out.writeValue(column); out.writeSeparator(); out.writeValue(row); for (int l = 0; l < layers.size(); l++) { out.writeSeparator(); out.writeValue(values[l]); } out.writeNewLine(); } } progressMonitor.worked(1); if (progressMonitor.isCancelled()) { throw new CancellationException(); } } }
From source file:org.rapidoid.http.HttpClient.java
private <T> FutureCallback<HttpResponse> callback(final Callback<byte[]> callback, final Callback<byte[]> promise, final boolean fullResponse) { return new FutureCallback<HttpResponse>() { @Override//from w w w. j ava 2 s. c o m public void completed(HttpResponse response) { int statusCode = response.getStatusLine().getStatusCode(); if (!fullResponse && statusCode != 200) { Callbacks.error(callback, new HttpException(statusCode)); Callbacks.error(promise, new HttpException(statusCode)); return; } byte[] bytes; if (response.getEntity() != null) { try { if (fullResponse) { bytes = responseToString(response).getBytes(); } else { InputStream resp = response.getEntity().getContent(); bytes = IOUtils.toByteArray(resp); } } catch (Exception e) { Callbacks.error(callback, e); Callbacks.error(promise, e); return; } } else { bytes = new byte[0]; } Callbacks.success(callback, bytes); Callbacks.success(promise, bytes); } @Override public void failed(Exception e) { Callbacks.error(callback, e); Callbacks.error(promise, e); } @Override public void cancelled() { Callbacks.error(callback, new CancellationException()); Callbacks.error(promise, new CancellationException()); } }; }
From source file:ca.sqlpower.wabit.dao.WorkspaceSAXHandler.java
@Override public void startElement(final String uri, final String localName, final String name, final Attributes attr) throws SAXException { if (isCancelled()) { throw new CancellationException(); }/*from w w w. j a v a 2 s . com*/ byteStream = new ByteArrayOutputStream(); final Attributes attributes = new AttributesImpl(attr); Runnable runner = new Runnable() { public void run() { try { context.startLoading(); startElementImpl(uri, localName, name, attributes); } catch (SAXException e) { setCancelled(true); throw new RuntimeException(e); } finally { context.endLoading(); } } }; session.runInForeground(runner); }
From source file:com.screenslicer.webapp.ScreenSlicerClient.java
@Path("create") @POST//ww w . ja v a2 s. c om @Consumes("application/json") @Produces("application/json") public static final Response create(String reqString) { if (reqString != null) { final String reqDecoded = Crypto.decode(reqString, CommonUtil.ip()); if (reqDecoded != null) { final Map<String, Object> args = CommonUtil.gson.fromJson(reqDecoded, CommonUtil.objectType); final Request request = CommonUtil.gson.fromJson(reqDecoded, Request.class); Field[] fields = request.getClass().getFields(); for (Field field : fields) { args.remove(field.getName()); } new Thread(new Runnable() { @Override public void run() { String myInstance = null; AtomicBoolean myDone = null; try { CommonFile.writeStringToFile( new File("./data/" + request.runGuid + "-meta" + request.appId), request.jobId + "\n" + request.jobGuid + "\n" + Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis(), false); CommonFile.writeStringToFile(new File("./data/" + request.runGuid + "-context"), Crypto.encode(reqDecoded), false); Map<String, AtomicBoolean> myDoneMap = new HashMap<String, AtomicBoolean>(); synchronized (doneMapLock) { for (int i = 0; i < request.instances.length; i++) { if (!doneMap.containsKey(request.instances[i])) { doneMap.put(request.instances[i], new AtomicBoolean(true)); } } myDoneMap.putAll(doneMap); } long myThread = latestThread.incrementAndGet(); while (true) { if (isCancelled(request.runGuid)) { curThread.incrementAndGet(); throw new CancellationException(); } if (myThread == curThread.get() + 1) { for (Map.Entry<String, AtomicBoolean> done : myDoneMap.entrySet()) { if (done.getValue().compareAndSet(true, false)) { if (ScreenSlicer.isBusy(done.getKey())) { done.getValue().set(true); } else { myInstance = done.getKey(); myDone = done.getValue(); break; } } } if (myInstance != null) { break; } } try { Thread.sleep(WAIT); } catch (Exception e) { Log.exception(e); } } curThread.incrementAndGet(); int outputNumber = 0; request.instances = new String[] { myInstance }; Map<String, List<List<String>>> tables = customApp.tableData(request, args); Map<String, Map<String, Object>> jsons = customApp.jsonData(request, args); Map<String, byte[]> binaries = customApp.binaryData(request, args); request.emailExport.attachments = new LinkedHashMap<String, byte[]>(); if (tables != null) { for (Map.Entry<String, List<List<String>>> table : tables.entrySet()) { if (table.getKey().toLowerCase().endsWith(".xls")) { byte[] result = Spreadsheet.xls(table.getValue()); CommonFile.writeByteArrayToFile( new File("./data/" + request.runGuid + "-result" + outputNumber), result, false); CommonFile.writeStringToFile( new File("./data/" + request.runGuid + "-result-names"), escapeName(table.getKey()) + "\n", true); ++outputNumber; if (request.emailResults) { request.emailExport.attachments.put(table.getKey(), result); } } else if (table.getKey().toLowerCase().endsWith(".csv")) { String result = Spreadsheet.csv(table.getValue()); CommonFile.writeStringToFile( new File("./data/" + request.runGuid + "-result" + outputNumber), result, false); CommonFile.writeStringToFile( new File("./data/" + request.runGuid + "-result-names"), escapeName(table.getKey()) + "\n", true); ++outputNumber; if (request.emailResults) { request.emailExport.attachments.put(table.getKey(), result.getBytes("utf-8")); } } else if (table.getKey().toLowerCase().endsWith(".xcsv")) { String result = Spreadsheet.csv(table.getValue()); CommonUtil.internalHttpCall(CommonUtil.ip(), "https://" + CommonUtil.ip() + ":8000/_/" + Crypto.fastHash(table.getKey() + ":" + request.runGuid), "PUT", CommonUtil.asMap("Content-Type", "text/csv; charset=utf-8"), result.getBytes("utf-8"), null); CommonFile.writeStringToFile( new File("./data/" + request.runGuid + "-result-names"), escapeName(table.getKey()) + "\n", true); ++outputNumber; if (request.emailResults) { request.emailExport.attachments.put(table.getKey(), result.getBytes("utf-8")); } } else { String result = CommonUtil.gson.toJson(table.getValue(), table.getValue().getClass()); CommonFile.writeStringToFile( new File("./data/" + request.runGuid + "-result" + outputNumber), result, false); CommonFile.writeStringToFile( new File("./data/" + request.runGuid + "-result-names"), escapeName(table.getKey()) + "\n", true); ++outputNumber; if (request.emailResults) { request.emailExport.attachments.put(table.getKey(), result.getBytes("utf-8")); } } } } if (jsons != null) { for (Map.Entry<String, Map<String, Object>> json : jsons.entrySet()) { String result = CommonUtil.gson.toJson(json.getValue(), CommonUtil.objectType); CommonFile.writeStringToFile( new File("./data/" + request.runGuid + "-result" + outputNumber), result, false); CommonFile.writeStringToFile( new File("./data/" + request.runGuid + "-result-names"), escapeName(json.getKey()) + "\n", true); ++outputNumber; if (request.emailResults) { request.emailExport.attachments.put(json.getKey(), result.getBytes("utf-8")); } } } if (binaries != null) { for (Map.Entry<String, byte[]> binary : binaries.entrySet()) { CommonFile.writeByteArrayToFile( new File("./data/" + request.runGuid + "-result" + outputNumber), binary.getValue(), false); CommonFile.writeStringToFile( new File("./data/" + request.runGuid + "-result-names"), escapeName(binary.getKey()) + "\n", true); ++outputNumber; if (request.emailResults) { request.emailExport.attachments.put(binary.getKey(), binary.getValue()); } } } if (request.emailResults) { ScreenSlicer.export(request, request.emailExport); } } catch (Throwable t) { Log.exception(t); } finally { try { CommonFile.writeStringToFile( new File("./data/" + request.runGuid + "-meta" + request.appId), "\n" + Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis(), true); } catch (Throwable t) { Log.exception(t); } myDone.set(true); synchronized (cancelledLock) { cancelledJobs.remove(request.runGuid); } } } }).start(); return Response.ok(Crypto.encode(request.runGuid, CommonUtil.ip())).build(); } } return null; }