List of usage examples for java.lang InterruptedException InterruptedException
public InterruptedException(String s)
InterruptedException
with the specified detail message. From source file:io.neba.core.resourcemodels.registration.MappableTypeHierarchyChangeListenerTest.java
private void withInterruptedExceptionThrownWhileBlocked() throws IllegalAccessException, InterruptedException { Field field = getField(MappableTypeHierarchyChangeListener.class, "invalidationRequests", true); BlockingQueue queue = mock(BlockingQueue.class); writeField(field, this.testee, queue); doThrow(new InterruptedException("THIS IS AN EXPECTED TEST EXCEPTION")).when(queue).poll(anyLong(), isA(TimeUnit.class)); }
From source file:com.laex.cg2d.screeneditor.handlers.RenderHandler.java
/** * the command has been executed, so extract extract the needed information * from the application context.// w w w . j a v a 2 s .c o m * * @param event * the event * @return the object * @throws ExecutionException * the execution exception */ public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); final IEditorPart editorPart = window.getActivePage().getActiveEditor(); editorPart.doSave(new NullProgressMonitor()); validate(window.getShell()); // Eclipse Jobs API final Job job = new Job("Render Game") { @Override protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { IFile file = ((IFileEditorInput) editorPart.getEditorInput()).getFile(); monitor.beginTask("Building rendering command", 5); ILog log = Activator.getDefault().getLog(); String mapFile = file.getLocation().makeAbsolute().toOSString(); String controllerFile = file.getLocation().removeFileExtension().addFileExtension("lua") .makeAbsolute().toOSString(); String[] command = buildRunnerCommandFromProperties(mapFile, controllerFile); monitor.worked(5); monitor.beginTask("Rendering external", 5); ProcessBuilder pb = new ProcessBuilder(command); Process p = pb.start(); monitor.worked(4); Scanner scn = new Scanner(p.getErrorStream()); while (scn.hasNext() && !monitor.isCanceled()) { if (monitor.isCanceled()) { throw new InterruptedException("Cancelled"); } log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, scn.nextLine())); } monitor.worked(5); monitor.done(); this.done(Status.OK_STATUS); return Status.OK_STATUS; } catch (RuntimeException e) { return handleException(e); } catch (IOException e) { return handleException(e); } catch (CoreException e) { return handleException(e); } catch (InterruptedException e) { return handleException(e); } } private IStatus handleException(Exception e) { Activator.log(e); return Status.CANCEL_STATUS; } }; job.setUser(true); job.setPriority(Job.INTERACTIVE); job.schedule(); return null; }
From source file:uk.ac.gda.client.hrpd.views.EpicsRunableWithProgress.java
@Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try {/*from www. j a v a 2 s. c om*/ totalWork = getTotalWorkListener().getValue(); monitor.beginTask(getEpicsProcessName(), totalWork); lastWorked = 0; work = getWorkedSoFarListener().getValue(); while (work < totalWork) { if (monitor.isCanceled()) { if (getStopScannable() != null) { try { getStopScannable().stop(); } catch (DeviceException e) { logger.error("Failed to stop EPICS operation.", e); } } throw new InterruptedException( getEpicsProcessName() + " is aborted by progress cancel operation."); } if (work != lastWorked) { monitor.worked(work - lastWorked); if (getMessageListener() != null) { monitor.subTask(getMessageListener().getValue()); } lastWorked = work; } Thread.sleep(1000); work = getWorkedSoFarListener().getValue(); } } finally { monitor.done(); } }
From source file:de.hybris.platform.b2b.WorkflowIntegrationTest.java
public boolean waitForProcessToEnd(final String businessProcessCode, final long maxWait) throws InterruptedException { final long start = System.currentTimeMillis(); while (true) { final B2BApprovalProcessModel bp = businessProcessService.getProcess(businessProcessCode); final String currentAction = bp.getCurrentTasks() != null && bp.getCurrentTasks().iterator().hasNext() ? bp.getCurrentTasks().iterator().next().getAction() : null;//from w w w .j a v a 2 s. c o m modelService.refresh(bp); // without refresh this object is stale if (ProcessState.SUCCEEDED.getCode().equals(bp.getProcessState().getCode()) || "FINISHED".equals(bp.getProcessState().getCode())) { return true; } else if (ProcessState.ERROR.getCode().equals(bp.getProcessState().getCode())) { return false; } if (System.currentTimeMillis() - start > maxWait) { LOG.debug("BusinessPRocess: " + ReflectionToStringBuilder.toString(bp)); throw new InterruptedException(String.format("BusinessProcess %s did not end! Waited for %s", bp.getCode(), Utilities.formatTime(System.currentTimeMillis() - start))); } else { Thread.sleep(1000); final OrderModel order = bp.getOrder(); if (LOG.isInfoEnabled() && order != null) { final WorkflowModel workflow = order.getWorkflow(); if (workflow != null) { LOG.info(String.format( "Workflow %s [%s] for order %s [%s] has status %s, BisunessProcess State %s running action %s", workflow.getCode(), workflow.getDescription(), order.getCode(), order.getStatus(), workflow.getStatus(), bp.getProcessState().getCode(), currentAction)); } } LOG.debug(String.format("Waited for process end for %s current state is %s", Utilities.formatTime(System.currentTimeMillis() - start), bp.getProcessState())); } } }
From source file:uk.ac.gda.epics.client.mythen.views.EpicsDetectorRunableWithProgress.java
@Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try {/*from w ww . ja v a 2 s .c o m*/ int totalWork = (int) (getExposureTimeListener().getValue() * 1000); //when exposure time less than 1 second, do not show progress. if (totalWork < 1000) return; monitor.beginTask(getEpicsProcessName(), totalWork); int lastWorked = 0; int work = totalWork - (int) (getTimeRemainingListener().getValue() * 1000); while (work < totalWork) { if (monitor.isCanceled()) { if (getStopScannable() != null) { try { getStopScannable().stop(); } catch (DeviceException e) { logger.error("Failed to stop EPICS operation.", e); } } throw new InterruptedException( getEpicsProcessName() + " is aborted by progress cancel operation."); } if (work != lastWorked) { monitor.worked(work - lastWorked); lastWorked = work; } Thread.sleep(1000); work = totalWork - (int) (getTimeRemainingListener().getValue() * 1000); } } finally { monitor.done(); } }
From source file:org.apache.druid.indexing.common.tasklogs.FileTaskLogs.java
@Override public void killOlderThan(final long timestamp) throws IOException { File taskLogDir = config.getDirectory(); if (taskLogDir.exists()) { if (!taskLogDir.isDirectory()) { throw new IOE("taskLogDir [%s] must be a directory.", taskLogDir); }/*from w w w.java2 s .co m*/ File[] files = taskLogDir.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.lastModified() < timestamp; } }); for (File file : files) { log.info("Deleting local task log [%s].", file.getAbsolutePath()); FileUtils.forceDelete(file); if (Thread.currentThread().isInterrupted()) { throw new IOException( new InterruptedException("Thread interrupted. Couldn't delete all tasklogs.")); } } } }
From source file:org.smartfrog.avalanche.client.sf.exec.simple.StartComponent.java
public void stopApplication() throws IOException, InterruptedException { readOutput();// ww w . j a v a 2 s . com try { proc.destroy(); proc.waitFor(); log.debug("Destroyed Process " + command + " forcibly"); stdInput.close(); stdError.close(); log.info(componentName + " : Process exited with return value " + proc.exitValue()); } catch (IOException ioe) { log.error("Unable to close InputStream and ErrorStream for " + command, ioe); throw new IOException(ioe.toString()); } catch (IllegalThreadStateException ite) { log.error("Unable to kill the process " + command, ite); throw new IllegalStateException(ite.toString()); } catch (InterruptedException ie) { log.error("Interrupted. Waiting for process " + command + " to die", ie); throw new InterruptedException(ie.toString()); } }
From source file:io.scigraph.owlapi.loader.BatchOwlLoader.java
public void loadOntology() throws InterruptedException, ExecutionException { CompletionService<Long> completionService = new ExecutorCompletionService<Long>(exec); Set<Future<?>> futures = new HashSet<>(); if (!ontologies.isEmpty()) { for (int i = 0; i < numConsumers; i++) { futures.add(completionService.submit(consumerProvider.get())); }//from w w w . j ava2s . c o m for (int i = 0; i < numProducers; i++) { futures.add(completionService.submit(producerProvider.get())); } for (OntologySetup ontology : ontologies) { urlQueue.offer(ontology); } for (int i = 0; i < numProducers; i++) { urlQueue.offer(POISON_STR); } } while (futures.size() > 0) { Future<?> completedFuture = completionService.take(); futures.remove(completedFuture); try { completedFuture.get(); } catch (ExecutionException e) { logger.log(Level.SEVERE, "Stopping batchLoading due to: " + e.getMessage(), e); e.printStackTrace(); exec.shutdownNow(); throw new InterruptedException(e.getCause().getMessage()); } } exec.shutdown(); exec.awaitTermination(10, TimeUnit.DAYS); graph.shutdown(); logger.info("Postprocessing..."); postprocessorProvider.get().postprocess(); if (cliqueConfiguration.isPresent()) { postprocessorProvider.runCliquePostprocessor(cliqueConfiguration.get()); } postprocessorProvider.shutdown(); }
From source file:com.flipkart.poseidon.serviceclients.FutureTaskResultToDomainObjectPromiseWrapper.java
@Override public DomainObject get() throws PromiseBrokenException, InterruptedException { try {//from w w w . j a v a 2 s. c o m ServiceResponse<DomainObject> serviceResponse = new ServiceResponse<>(); for (Future<TaskResult> futureResult : futureList) { TaskResult result = futureResult.get(); if (result == null) { throw new PromiseBrokenException("Task result is null"); } ServiceResponse<DomainObject> response = (ServiceResponse<DomainObject>) result.getData(); if (!response.getIsSuccess()) throw response.getException(); serviceResponse.addData(response.getDataList()); } if (responseMerger != null) { return responseMerger.mergeResponse(serviceResponse.getDataList()); } else { return serviceResponse.getDataList().get(0); } } catch (ExecutionException exception) { checkAndThrowServiceClientException(exception); promiseBrokenException = new PromiseBrokenException(exception); throw new InterruptedException(exception.getMessage()); } catch (CancellationException exception) { promiseBrokenException = new PromiseBrokenException(exception); throw new PromiseBrokenException(promiseBrokenException); } }
From source file:org.grouplens.lenskit.eval.traintest.TrainTestJob.java
@SuppressWarnings("PMD.AvoidCatchingThrowable") private void runEvaluation() throws IOException, RecommenderBuildException { EventBus bus = task.getProject().getEventBus(); bus.post(JobEvents.started(this)); Closer closer = Closer.create();/*from w w w.ja v a 2s .c o m*/ try { outputs = task.getOutputs().getPrefixed(algorithmInfo, dataSet); TableWriter userResults = outputs.getUserWriter(); List<Object> outputRow = Lists.newArrayList(); logger.info("Building {} on {}", algorithmInfo, dataSet); StopWatch buildTimer = new StopWatch(); buildTimer.start(); buildRecommender(); buildTimer.stop(); logger.info("Built {} in {}", algorithmInfo.getName(), buildTimer); logger.info("Measuring {} on {}", algorithmInfo.getName(), dataSet.getName()); StopWatch testTimer = new StopWatch(); testTimer.start(); List<Object> userRow = Lists.newArrayList(); List<MetricWithAccumulator<?>> accumulators = Lists.newArrayList(); for (Metric<?> eval : outputs.getMetrics()) { accumulators.add(makeMetricAccumulator(eval)); } LongSet testUsers = dataSet.getTestData().getUserDAO().getUserIds(); final NumberFormat pctFormat = NumberFormat.getPercentInstance(); pctFormat.setMaximumFractionDigits(2); pctFormat.setMinimumFractionDigits(2); final int nusers = testUsers.size(); logger.info("Testing {} on {} ({} users)", algorithmInfo, dataSet, nusers); int ndone = 0; for (LongIterator iter = testUsers.iterator(); iter.hasNext();) { if (Thread.interrupted()) { throw new InterruptedException("eval job interrupted"); } long uid = iter.nextLong(); userRow.add(uid); userRow.add(null); // placeholder for the per-user time assert userRow.size() == 2; Stopwatch userTimer = Stopwatch.createStarted(); TestUser test = getUserResults(uid); userRow.add(test.getTrainHistory().size()); userRow.add(test.getTestHistory().size()); for (MetricWithAccumulator<?> accum : accumulators) { List<Object> ures = accum.measureUser(test); if (ures != null) { userRow.addAll(ures); } } userTimer.stop(); userRow.set(1, userTimer.elapsed(TimeUnit.MILLISECONDS) * 0.001); if (userResults != null) { try { userResults.writeRow(userRow); } catch (IOException e) { throw new RuntimeException("error writing user row", e); } } userRow.clear(); ndone += 1; if (ndone % 100 == 0) { testTimer.split(); double time = testTimer.getSplitTime(); double tpu = time / ndone; double tleft = (nusers - ndone) * tpu; logger.info("tested {} of {} users ({}), ETA {}", ndone, nusers, pctFormat.format(((double) ndone) / nusers), DurationFormatUtils.formatDurationHMS((long) tleft)); } } testTimer.stop(); logger.info("Tested {} in {}", algorithmInfo.getName(), testTimer); writeMetricValues(buildTimer, testTimer, outputRow, accumulators); bus.post(JobEvents.finished(this)); } catch (Throwable th) { bus.post(JobEvents.failed(this, th)); throw closer.rethrow(th, RecommenderBuildException.class); } finally { try { cleanup(); } finally { outputs = null; closer.close(); } } }