List of usage examples for java.util.concurrent FutureTask get
public V get() throws InterruptedException, ExecutionException
From source file:info.pancancer.arch3.test.TestWorker.java
@Test public void testWorker_endless() throws Exception { byte[] body = setupMessage(); Delivery testDelivery = new Delivery(mockEnvelope, mockProperties, body); setupMockQueue(testDelivery);//from ww w .j av a2 s. c o m Mockito.when(Utilities.parseJSONStr(anyString())).thenCallRealMethod(); Mockito.when(Utilities.parseConfig(anyString())).thenCallRealMethod(); //Because the code that does cleanup in calls resultHandler.waitFor(); we need to actually execute something, even if it does nothing. Mockito.doNothing().when(mockExecutor).execute(any(CommandLine.class), any(DefaultExecuteResultHandler.class)); // This is to mock the cleanup command - we don't really want to execute the command for deleting contents of /datastore, at least not when unit testing on a workstation! PowerMockito.whenNew(DefaultExecutor.class).withNoArguments().thenReturn(mockExecutor); Mockito.when(mockExecHandler.hasResult()).thenReturn(true); PowerMockito.whenNew(DefaultExecuteResultHandler.class).withNoArguments().thenReturn(mockExecHandler); final FutureTask<String> tester = new FutureTask<>(new Callable<String>() { @Override public String call() { LOG.debug("tester thread started"); try { Worker.main(new String[] { "--config", "src/test/resources/workerConfig.ini", "--uuid", "vm123456", "--endless", "--pidFile", "/var/run/arch3_worker.pid" }); } catch (CancellationException | InterruptedException e) { LOG.error("Exception caught: " + e.getMessage()); return e.getMessage(); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception"); return null; } finally { Mockito.verify(mockAppender, Mockito.atLeastOnce()).doAppend(argCaptor.capture()); String s = appendEventsIntoString(argCaptor.getAllValues()); return s; } } }); final Thread killer = new Thread(new Runnable() { @Override public void run() { LOG.debug("killer thread started"); try { // The endless worker will not end on its own (because it's endless) so we need to wait a little bit (0.5 seconds) and // then kill it as if it were killed by the command-line script (kill_worker_daemon.sh). Thread.sleep(2500); } catch (InterruptedException e) { e.printStackTrace(); LOG.error(e.getMessage()); } tester.cancel(true); } }); ExecutorService es = Executors.newFixedThreadPool(2); es.execute(tester); es.execute(killer); try { tester.get(); } catch (CancellationException e) { Mockito.verify(mockAppender, Mockito.atLeastOnce()).doAppend(argCaptor.capture()); List<LoggingEvent> tmpList = new LinkedList<>(argCaptor.getAllValues()); String output = this.appendEventsIntoString(tmpList); assertTrue(output.contains("The \"--endless\" flag was set, this worker will run endlessly!")); int numJobsPulled = StringUtils.countMatches(output, " WORKER IS PREPARING TO PULL JOB FROM QUEUE "); LOG.info("Number of jobs attempted: " + numJobsPulled); assertTrue("number of jobs attempted > 1", numJobsPulled > 1); } catch (Exception e) { e.printStackTrace(); fail(); } }
From source file:ubic.gemma.loader.expression.geo.GeoFamilyParser.java
@Override public void parse(InputStream is) throws IOException { if (is == null) { throw new IOException("Inputstream was null"); }/* w ww . ja v a 2 s . c om*/ if (is.available() == 0) { throw new IOException("No bytes to read from the input stream."); } final BufferedReader dis = new BufferedReader(new InputStreamReader(is)); log.debug("Parsing...."); final ExecutorService executor = Executors.newSingleThreadExecutor(); FutureTask<Exception> future = new FutureTask<Exception>(new Callable<Exception>() { @Override public Exception call() { try { return doParse(dis); } catch (Exception e) { log.error(e, e); return e; } } }); executor.execute(future); executor.shutdown(); while (!future.isDone() && !future.isCancelled()) { try { TimeUnit.SECONDS.sleep(5L); } catch (InterruptedException e) { // probably cancelled. return; } log.info(parsedLines + " lines parsed."); } try { Exception e = future.get(); if (e != null) { log.error(e.getMessage()); throw new RuntimeException(e.getCause()); } } catch (ExecutionException e) { throw new RuntimeException("Parse failed", e.getCause()); } catch (java.util.concurrent.CancellationException e) { throw new RuntimeException("Parse was cancelled", e.getCause()); } catch (InterruptedException e) { throw new RuntimeException("Parse was interrupted", e.getCause()); } executor.shutdownNow(); assert future.isDone(); // assert executor.isTerminated(); log.info("Done parsing."); }
From source file:ubic.gemma.core.loader.expression.geo.GeoFamilyParser.java
@Override public void parse(InputStream is) throws IOException { if (is == null) { throw new IOException("Inputstream was null"); }//from www .j a va 2 s . c om if (is.available() == 0) { throw new IOException("No bytes to read from the input stream."); } try (final BufferedReader dis = new BufferedReader(new InputStreamReader(is))) { GeoFamilyParser.log.debug("Parsing...."); final ExecutorService executor = Executors.newSingleThreadExecutor(); FutureTask<Exception> future = new FutureTask<>(new Callable<Exception>() { @Override public Exception call() { try { GeoFamilyParser.this.doParse(dis); dis.close(); return null; } catch (Exception e) { GeoFamilyParser.log.error(e, e); return e; } } }); executor.execute(future); executor.shutdown(); while (!future.isDone() && !future.isCancelled()) { try { TimeUnit.SECONDS.sleep(5L); } catch (InterruptedException e) { // probably cancelled. dis.close(); return; } GeoFamilyParser.log.info(parsedLines + " lines parsed."); } try { Exception e = future.get(); if (e != null) { GeoFamilyParser.log.error(e.getMessage()); throw new RuntimeException(e.getCause()); } } catch (ExecutionException e) { throw new RuntimeException("Parse failed", e.getCause()); } catch (java.util.concurrent.CancellationException e) { throw new RuntimeException("Parse was cancelled", e.getCause()); } catch (InterruptedException e) { throw new RuntimeException("Parse was interrupted", e.getCause()); } executor.shutdownNow(); assert future.isDone(); // assert executor.isTerminated(); GeoFamilyParser.log.info("Done parsing."); } }
From source file:org.alfresco.repo.rendition.executer.AbstractTransformationRenderingEngine.java
@Override protected void render(RenderingContext context) { ContentReader contentReader = context.makeContentReader(); // There will have been an exception if there is no content data so contentReader is not null. String sourceUrl = contentReader.getContentUrl(); String sourceMimeType = contentReader.getMimetype(); String targetMimeType = getTargetMimeType(context); // The child NodeRef gets created here TransformationOptions options = getTransformOptions(context); // Log the following getTransform() as trace so we can see the wood for the trees ContentTransformer transformer;/*from w ww. j a va2 s . c om*/ boolean orig = TransformerDebug.setDebugOutput(false); try { transformer = this.contentService.getTransformer(sourceUrl, sourceMimeType, contentReader.getSize(), targetMimeType, options); } finally { TransformerDebug.setDebugOutput(orig); } if (null == transformer) { // There's no transformer available for the requested rendition! throw new RenditionServiceException( String.format(TRANSFORMER_NOT_EXISTS_MESSAGE_PATTERN, sourceMimeType, targetMimeType)); } if (!transformer.isTransformable(sourceMimeType, contentReader.getSize(), targetMimeType, options)) { throw new RenditionServiceException( String.format(NOT_TRANSFORMABLE_MESSAGE_PATTERN, sourceMimeType, targetMimeType)); } long startTime = new Date().getTime(); boolean actionCancelled = false; boolean actionCompleted = false; // Cache the execution summary to get details later ExecutionSummary executionSummary = null; try { executionSummary = getExecutionSummary(context); } catch (ActionServiceException e) { if (logger.isInfoEnabled()) { logger.info("Cancelling of multiple concurrent action instances " + "currently unsupported, this action can't be cancelled"); } } // Call the transform in a different thread so we can move on if cancelled FutureTask<ContentWriter> transformTask = new FutureTask<ContentWriter>(new TransformationCallable( contentReader, targetMimeType, options, context, AuthenticationUtil.getFullyAuthenticatedUser())); getExecutorService().execute(transformTask); // Start checking for cancellation or timeout while (true) { try { Thread.sleep(CANCELLED_ACTION_POLLING_INTERVAL); if (transformTask.isDone()) { actionCompleted = true; break; } // Check timeout in case transformer doesn't obey it if (options.getTimeoutMs() > 0 && new Date().getTime() - startTime > (options.getTimeoutMs() + CANCELLED_ACTION_POLLING_INTERVAL)) { // We hit a timeout, let the transform thread continue but results will be ignored if (logger.isDebugEnabled()) { logger.debug( "Transformation did not obey timeout limit, " + "rendition action is moving on"); } break; } if (executionSummary != null) { ExecutionDetails executionDetails = actionTrackingService.getExecutionDetails(executionSummary); if (executionDetails != null) { actionCancelled = executionDetails.isCancelRequested(); if (actionCancelled) { if (logger.isDebugEnabled()) { logger.debug("Cancelling transformation"); } transformTask.cancel(true); break; } } } } catch (InterruptedException e) { // entire thread was asked to stop actionCancelled = true; transformTask.cancel(true); break; } } if (actionCancelled) { throw new RenditionCancelledException("Rendition action cancelled"); } if (!actionCompleted && !actionCancelled) { throw new RenditionServiceException("Transformation failed to obey timeout limit"); } if (actionCompleted) { // Copy content from temp writer to real writer ContentWriter writer = context.makeContentWriter(); try { // We should not need another timeout here, things should be ready for us ContentWriter tempTarget = transformTask.get(); if (tempTarget == null) { // We should never be in this state, but just in case throw new RenditionServiceException("Target of transformation not present"); } writer.putContent(tempTarget.getReader().getContentInputStream()); } catch (ExecutionException e) { // Unwrap our cause and throw that Throwable transformException = e.getCause(); if (transformException instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RenditionServiceException(TRANSFORMING_ERROR_MESSAGE + e.getCause().getMessage(), e.getCause()); } catch (InterruptedException e) { // We were asked to stop transformTask.cancel(true); } } }
From source file:com.norman0406.slimgress.API.Interface.Interface.java
public AuthSuccess authenticate(final String token) { FutureTask<AuthSuccess> future = new FutureTask<AuthSuccess>(new Callable<AuthSuccess>() { @Override//from w w w. java 2s .c o m public AuthSuccess call() throws Exception { // see http://blog.notdot.net/2010/05/Authenticating-against-App-Engine-from-an-Android-app // also use ?continue= (?) String login = mApiBaseURL + mApiLogin + token; HttpGet get = new HttpGet(login); try { HttpResponse response = null; synchronized (Interface.this) { mClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); Log.i("Interface", "executing authentication"); response = mClient.execute(get); } assert (response != null); @SuppressWarnings("unused") String content = EntityUtils.toString(response.getEntity()); response.getEntity().consumeContent(); if (response.getStatusLine().getStatusCode() == 401) { // the token has expired Log.i("Interface", "401: authentication token has expired"); return AuthSuccess.TokenExpired; } else if (response.getStatusLine().getStatusCode() != 302) { // Response should be a redirect Log.i("Interface", "unknown error: " + response.getStatusLine().getReasonPhrase()); return AuthSuccess.UnknownError; } else { // get cookie synchronized (Interface.this) { for (Cookie cookie : mClient.getCookieStore().getCookies()) { if (cookie.getName().equals("SACSID")) { // secure cookie! (ACSID is non-secure http cookie) mCookie = cookie.getValue(); } } } if (mCookie == null) { Log.i("Interface", "authentication token has expired"); return AuthSuccess.TokenExpired; } Log.i("Interface", "authentication successful"); return AuthSuccess.Successful; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { synchronized (Interface.this) { mClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); } } return AuthSuccess.Successful; } }); // start thread new Thread(future).start(); // obtain authentication return value AuthSuccess retVal = AuthSuccess.UnknownError; try { retVal = future.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return retVal; }