/** * Creates a {@link InMemoryConfigurator} to run through the process of generation of {@link * AdapterDefinition} * * @param deploymentInfo Location of the input and output location */ @Override public void process(AdapterDeploymentInfo deploymentInfo) throws Exception { InMemoryAdapterConfigurator inMemoryAdapterConfigurator = new InMemoryAdapterConfigurator( cConf, namespace, templateJarLocation, adapterName, deploymentInfo.getAdapterConfig(), deploymentInfo.getTemplateSpec(), pluginRepository); ConfigResponse configResponse; try { configResponse = inMemoryAdapterConfigurator.config().get(120, TimeUnit.SECONDS); } catch (ExecutionException e) { if (e.getCause() instanceof Exception) { throw (Exception) e.getCause(); } throw e; } InputSupplier<? extends Reader> configSupplier = configResponse.get(); if (configResponse.getExitCode() != 0 || configSupplier == null) { throw new IllegalArgumentException("Failed to configure adapter: " + deploymentInfo); } Reader reader = configSupplier.getInput(); try { emit(GSON.fromJson(reader, AdapterDefinition.class)); } finally { Closeables.closeQuietly(reader); } }
/** Demonstrate how to handle an Exception from an asynchronous call. */ private void callAsyncWithFailure() throws InterruptedException { Future<String> x; try { x = accessBean .failure(); // this method will return successfully, because the invocation will be // successful! } catch (IllegalAccessException e) { throw new RuntimeException("Unexpected failure during start asynchronous execution!", e); } try { x.get(); // this will not return successfully } catch (ExecutionException e) { // the IllegalAccessException is thrown by the bean method if (e.getCause() instanceof IllegalAccessException) { // This is the expected behavior LOGGER.info("Catch the expected Exception of the asynchronous execution!"); } else if (e.getCause().getCause() instanceof IllegalAccessException) { LOGGER.info( "Catch the covered Exception of the asynchronous execution, you may be using an older release of JBoss EAP!"); } else { throw new RuntimeException("Unexpected ExecutionException during asynchronous call!", e); } } }
/** Handle new connection or report failure. */ public void completed(IoFuture<AsynchronousSocketChannel, Void> result) { try { try { AsynchronousSocketChannel newChannel = result.getNow(); logger.log(Level.FINER, "Accepted {0}", newChannel); /* The handler will call addHandler if login succeeds */ new ClientSessionHandler( ClientSessionServiceImpl.this, dataService, new AsynchronousMessageChannel(newChannel, readBufferSize)); // Resume accepting connections acceptFuture = acceptor.accept(this); } catch (ExecutionException e) { throw (e.getCause() == null) ? e : e.getCause(); } } catch (CancellationException e) { logger.logThrow(Level.FINE, e, "acceptor cancelled"); // ignore } catch (Throwable e) { SocketAddress addr = null; try { addr = acceptor.getLocalAddress(); } catch (IOException ioe) { // ignore } logger.logThrow(Level.SEVERE, e, "acceptor error on {0}", addr); // TBD: take other actions, such as restarting acceptor? } }
@Override public boolean injectMotionEvent(final MotionEvent event) throws InjectEventSecurityException { checkNotNull(event); checkState(Looper.myLooper() == mainLooper, "Expecting to be on main thread!"); initialize(); FutureTask<Boolean> injectTask = new SignalingTask<Boolean>( new Callable<Boolean>() { @Override public Boolean call() throws Exception { return eventInjector.injectMotionEvent(event); } }, IdleCondition.MOTION_INJECTION_HAS_COMPLETED, generation); keyEventExecutor.submit(injectTask); loopUntil(IdleCondition.MOTION_INJECTION_HAS_COMPLETED); try { checkState(injectTask.isDone(), "Key injection was signaled - but it wasnt done."); return injectTask.get(); } catch (ExecutionException ee) { if (ee.getCause() instanceof InjectEventSecurityException) { throw (InjectEventSecurityException) ee.getCause(); } else { throw propagate(ee.getCause() != null ? ee.getCause() : ee); } } catch (InterruptedException neverHappens) { // we only call get() after done() is signaled. // we should never block. throw propagate(neverHappens); } finally { loopMainThreadUntilIdle(); } }
public void execute(final OfficeTask task) throws OfficeException { Future<?> futureTask = taskExecutor.submit( new Runnable() { public void run() { if (settings.getMaxTasksPerProcess() > 0 && ++taskCount == settings.getMaxTasksPerProcess() + 1) { logger.info( String.format( "reached limit of %d maxTasksPerProcess: restarting", settings.getMaxTasksPerProcess())); taskExecutor.setAvailable(false); stopping = true; managedOfficeProcess.restartAndWait(); // FIXME taskCount will be 0 rather than 1 at this point } task.execute(managedOfficeProcess.getConnection()); } }); currentTask = futureTask; try { futureTask.get(settings.getTaskExecutionTimeout(), TimeUnit.MILLISECONDS); } catch (TimeoutException timeoutException) { managedOfficeProcess.restartDueToTaskTimeout(); throw new OfficeException("task did not complete within timeout", timeoutException); } catch (ExecutionException executionException) { if (executionException.getCause() instanceof OfficeException) { throw (OfficeException) executionException.getCause(); } else { throw new OfficeException("task failed", executionException.getCause()); } } catch (Exception exception) { throw new OfficeException("task failed", exception); } }
@Override @Test public void win7DisconnectTest() throws Throwable { final AtomicInteger count = new AtomicInteger(0); AsyncHttpClient client = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().build()); AsyncCompletionHandler<Response> handler = new AsyncCompletionHandlerAdapter() { @Override public Response onCompleted(Response response) throws Exception { count.incrementAndGet(); StackTraceElement e = new StackTraceElement("sun.nio.ch.SocketDispatcher", "read0", null, -1); IOException t = new IOException(); t.setStackTrace(new StackTraceElement[] {e}); throw t; } }; try { client.prepareGet(getTargetUrl()).execute(handler).get(); fail("Must have received an exception"); } catch (ExecutionException ex) { assertNotNull(ex); assertNotNull(ex.getCause()); assertEquals(ex.getCause().getClass(), IOException.class); assertEquals(count.get(), 1); } client.close(); }
/** Invokes the effector so that its progress is tracked. */ public static <T> T invokeEffector(Entity entity, Effector<T> eff, Object[] args) { String id = entity.getId(); String name = eff.getName(); try { if (log.isDebugEnabled()) log.debug("Invoking effector {} on {}", new Object[] {name, entity}); if (log.isTraceEnabled()) log.trace("Invoking effector {} on {} with args {}", new Object[] {name, entity, args}); EntityManagementSupport mgmtSupport = ((EntityInternal) entity).getManagementSupport(); if (!mgmtSupport.isDeployed()) { mgmtSupport.attemptLegacyAutodeployment(name); } ManagementContextInternal mgmtContext = (ManagementContextInternal) ((EntityInternal) entity).getManagementContext(); mgmtSupport.getEntityChangeListener().onEffectorStarting(eff); try { return mgmtContext.invokeEffectorMethodSync(entity, eff, args); } finally { mgmtSupport.getEntityChangeListener().onEffectorCompleted(eff); } } catch (CancellationException ce) { log.info("Execution of effector {} on entity {} was cancelled", name, id); throw ce; } catch (ExecutionException ee) { log.info("Execution of effector {} on entity {} failed with {}", new Object[] {name, id, ee}); // Exceptions thrown in Futures are wrapped // FIXME Shouldn't pretend exception came from this thread?! Should we remove this unwrapping? if (ee.getCause() != null) throw Exceptions.propagate(ee.getCause()); else throw Exceptions.propagate(ee); } }
public void testScheduledListensBeforeCompletesWithException() throws Exception { RunWaiter waiter = new RunWaiter(); sq.execute(waiter); Object result = new Object(); Caller runner = new Caller(result, true); ListeningFuture<Object> task = sq.schedule((Callable<Object>) runner, 500, TimeUnit.MILLISECONDS); Listener listener = new Listener(); task.addFutureListener(listener); waiter.latch.countDown(); assertTrue(listener.latch.await(1, TimeUnit.SECONDS)); assertNotNull(listener.event); assertNull(listener.event.getResult()); assertEquals(FutureEvent.Type.EXCEPTION, listener.event.getType()); ExecutionException ee = listener.event.getException(); assertNotNull(ee); assertInstanceof(RuntimeException.class, ee.getCause()); assertEquals("Boo!", ee.getCause().getMessage()); assertEquals(runner.thread, listener.thread); assertEquals(1, serviceStub.getExceptionCount()); assertEquals("Boo!", serviceStub.getException(0).getMessage()); serviceStub.clear(); }
/** @see java.lang.Process#exitValue() */ @Override public int exitValue() { if (!DsfSession.isSessionActive(getSession().getId())) { return fExitCode.get(); } try { getSession() .getExecutor() .submit( new Callable<Object>() { @Override public Object call() throws Exception { if (fMIBackend.getState() != IMIBackend.State.TERMINATED) { throw new IllegalThreadStateException( "Backend Process has not exited"); //$NON-NLS-1$ } return null; } }) .get(); } catch (RejectedExecutionException e) { } catch (InterruptedException e) { } catch (ExecutionException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } } return fExitCode.get(); }
/** * This test will tell the launch to set some arguments for the program. We will then check that * the program has the same arguments. */ @Test public void testSettingArguments() throws Throwable { setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, "1 2 3\n4 5 6"); doLaunch(); MIStoppedEvent stoppedEvent = getInitialStoppedEvent(); // Check that argc is correct final IExpressionDMContext argcDmc = SyncUtil.createExpression(stoppedEvent.getDMContext(), "argc"); Query<FormattedValueDMData> query = new Query<FormattedValueDMData>() { @Override protected void execute(DataRequestMonitor<FormattedValueDMData> rm) { fExpService.getFormattedExpressionValue( fExpService.getFormattedValueContext(argcDmc, MIExpressions.DETAILS_FORMAT), rm); } }; try { fExpService.getExecutor().execute(query); FormattedValueDMData value = query.get(500, TimeUnit.MILLISECONDS); // Argc should be 7: the program name and the six arguments assertTrue( "Expected 7 but got " + value.getFormattedValue(), value.getFormattedValue().trim().equals("7")); } catch (InterruptedException e) { fail(e.getMessage()); } catch (ExecutionException e) { fail(e.getCause().getMessage()); } catch (TimeoutException e) { fail(e.getMessage()); } // Check that argv is also correct. For simplicity we only check the last argument final IExpressionDMContext argvDmc = SyncUtil.createExpression(stoppedEvent.getDMContext(), "argv[argc-1]"); Query<FormattedValueDMData> query2 = new Query<FormattedValueDMData>() { @Override protected void execute(DataRequestMonitor<FormattedValueDMData> rm) { fExpService.getFormattedExpressionValue( fExpService.getFormattedValueContext(argvDmc, MIExpressions.DETAILS_FORMAT), rm); } }; try { fExpService.getExecutor().execute(query2); FormattedValueDMData value = query2.get(500, TimeUnit.MILLISECONDS); assertTrue( "Expected \"6\" but got " + value.getFormattedValue(), value.getFormattedValue().trim().endsWith("\"6\"")); } catch (InterruptedException e) { fail(e.getMessage()); } catch (ExecutionException e) { fail(e.getCause().getMessage()); } catch (TimeoutException e) { fail(e.getMessage()); } }
@Override protected EncounterAddFailedEvent doInBackground(Void... params) { RequestFuture<Encounter> encounterFuture = RequestFuture.newFuture(); mServer.addEncounter(mPatient, mEncounter, encounterFuture, encounterFuture); Encounter encounter; try { encounter = encounterFuture.get(); } catch (InterruptedException e) { return new EncounterAddFailedEvent(EncounterAddFailedEvent.Reason.INTERRUPTED, e); } catch (ExecutionException e) { LOG.e(e, "Server error while adding encounter"); EncounterAddFailedEvent.Reason reason = EncounterAddFailedEvent.Reason.UNKNOWN_SERVER_ERROR; if (e.getCause() != null) { String errorMessage = e.getCause().getMessage(); if (errorMessage.contains("failed to validate")) { reason = EncounterAddFailedEvent.Reason.FAILED_TO_VALIDATE; } else if (errorMessage.contains("Privileges required")) { reason = EncounterAddFailedEvent.Reason.FAILED_TO_AUTHENTICATE; } } LOG.e("Error response: %s", ((VolleyError) e.getCause()).networkResponse); return new EncounterAddFailedEvent(reason, (VolleyError) e.getCause()); } if (encounter.uuid == null) { LOG.e( "Although the server reported an encounter successfully added, it did not " + "return a UUID for that encounter. This indicates a server error."); return new EncounterAddFailedEvent( EncounterAddFailedEvent.Reason.FAILED_TO_SAVE_ON_SERVER, null /*exception*/); } AppEncounter appEncounter = AppEncounter.fromNet(mPatient.uuid, encounter); if (appEncounter.observations.length > 0) { int inserted = mContentResolver.bulkInsert( Contracts.Observations.CONTENT_URI, appEncounter.toContentValuesArray()); if (inserted != appEncounter.observations.length) { LOG.w( "Inserted %d observations for encounter. Expected: %d", inserted, appEncounter.observations.length); return new EncounterAddFailedEvent( EncounterAddFailedEvent.Reason.INVALID_NUMBER_OF_OBSERVATIONS_SAVED, null /*exception*/); } } else { LOG.w("Encounter was sent to the server but contained no observations."); } mUuid = encounter.uuid; return null; }
/** * @param runnable the <code>Retriever</code> running on the thread * @param throwable an exception thrown during retrieval, will be null if no exception occurred * @throws IllegalArgumentException if <code>runnable</code> is null */ @Override protected void afterExecute(Runnable runnable, Throwable throwable) { if (runnable == null) { String msg = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } super.afterExecute(runnable, throwable); RetrievalTask task = (RetrievalTask) runnable; DownloaderRetrievalService.this.activeTasks.remove(task); task.retriever.setEndTime(System.currentTimeMillis()); try { if (throwable != null) { Logging.logger() .log( Level.FINE, Logging.getMessage( "BasicRetrievalService.ExceptionDuringRetrieval", task.getRetriever().getName()), throwable); } task.get(); // Wait for task to finish, cancel or break } catch (java.util.concurrent.ExecutionException e) { String message = Logging.getMessage( "BasicRetrievalService.ExecutionExceptionDuringRetrieval", task.getRetriever().getName()); if (e.getCause() instanceof SocketTimeoutException) { Logging.logger().fine(message + " " + e.getCause().getLocalizedMessage()); } else if (e.getCause() instanceof SSLHandshakeException) { if (sslExceptionListener != null) sslExceptionListener.onException(e.getCause(), task.getRetriever().getName()); else Logging.logger().fine(message + " " + e.getCause().getLocalizedMessage()); } else { Logging.logger().log(Level.FINE, message, e); } } catch (InterruptedException e) { Logging.logger() .log( Level.FINE, Logging.getMessage( "BasicRetrievalService.RetrievalInterrupted", task.getRetriever().getName()), e); } catch (java.util.concurrent.CancellationException e) { Logging.logger() .fine( Logging.getMessage( "BasicRetrievalService.RetrievalCancelled", task.getRetriever().getName())); } finally { Thread.currentThread().setName(IDLE_THREAD_NAME_PREFIX); } }
/** * This blocking function attempts to send the message passed in as a parameter. This {@link * AmqpsIotHubConnection} handles all calls to this method. * * <p>Only the first call to this method will result in an attempt to send. Until the message has * been sent, all other calls to this method will block. Once a message has been sent and this * method notified that it has been sent, this method will be invoked again if was previously * another call to send a message. * * <p>If a message has been passed down to the handler for sending but the message isn't sent * after a default constant number of seconds, the {@link AmqpsTransport} will set an ERROR status * code on the message and it will placed back onto the queue. * * @throws IOException If {@link AmqpsIotHubConnectionBaseHandler} has not been initialized. */ protected synchronized void send(Tuple<CompletableFuture<Boolean>, byte[], Object> message) throws IOException { if (this.state == ReactorState.CLOSED) { throw new IllegalStateException( "The AMQPS IotHub Connection is currently closed. Call open() before attempting to send a message."); } if (message != null) { if (this.inProgressMessageMap.size() >= this.maxQueueSize * 0.9) { message.V1.completeExceptionally( new Throwable("Insufficient link credit to send message.")); } else { try { // Use the content and ID fields of the input message to have the handler create and send // the message CompletableFuture<Integer> deliveryFuture = amqpsHandler.createBinaryMessage((byte[]) message.V2, message.V3); // Wait for a period of time before rejecting the message new Thread( () -> { try { Thread.sleep(DEFAULT_DELIVERY_WAIT_TIME_SECONDS * 1000); deliveryFuture.completeExceptionally( new Throwable("Default timeout exceeded before this message was sent.")); } catch (InterruptedException e) { e.printStackTrace(); } }) .start(); // Wait for the deliveryFuture to be completed, providing the delivery hash code. // When this future completes, the message has been SENT Integer deliveryHash = deliveryFuture.get(); inProgressMessageMap.put(deliveryHash, message); } catch (InterruptedException e) { e.printStackTrace(); } // The message was unable to be sent, exceptionally complete that future causing the message // to be put back on the queue. catch (ExecutionException e) { message.V1.completeExceptionally(e.getCause()); this.fail(e.getCause()); } // There was some other problem sending, exceptionally complete that future causing the // message to be put back on the queue. catch (Exception e) { if (message != null) { message.V1.completeExceptionally(e); } this.fail(e); } } } else { throw new IOException("Cannot send an unitialized message."); } }
@Test public void multipleThreadsOfCurrentJvmDistinctVersion() throws Exception { final PathLocker<SrcVersion> pathLocker = new PathLocker<>(); final Path dir1 = lockerDirectory.resolve(UUID.randomUUID().toString()); final SrcVersion srcVersion1 = SrcVersion.parse("1.2.3-SRC-revision-deadbeef"); final SrcVersion srcVersion2 = SrcVersion.parse("2.3.4-SRC-revision-coffeebabe"); Future<PathLock> concurrLockFuture = null; try (PathLock lock1 = pathLocker.lockDirectory(dir1, srcVersion1)) { /* locked for the current thread */ /* * now try to lock for a distinct version from another thread which should fail with a * CannotAcquireLockException because we have locked the path above */ try { concurrLockFuture = lockConcurrently(pathLocker, dir1, srcVersion2); concurrLockFuture.get(1, TimeUnit.SECONDS); Assert.fail("CannotAcquireLockException expected"); } catch (InterruptedException e) { throw e; } catch (ExecutionException e) { Assert.assertTrue( "Should throw CannotAcquireLockException", CannotAcquireLockException.class.equals(e.getCause().getClass())); } catch (TimeoutException e) { throw e; } } /* the above concurrent attempt should still fail, even if lock1 has been released in between */ try { concurrLockFuture.get(1, TimeUnit.SECONDS); Assert.fail("CannotAcquireLockException expected"); } catch (ExecutionException e) { Assert.assertTrue( "Should throw CannotAcquireLockException", CannotAcquireLockException.class.equals(e.getCause().getClass())); } /* but a fresh attempt must succeed */ try { Future<PathLock> concurrLockFuture2 = lockConcurrently(pathLocker, dir1, srcVersion2); Assert.assertNotNull(concurrLockFuture2.get(1, TimeUnit.SECONDS)); } catch (InterruptedException e) { throw e; } catch (ExecutionException e) { throw e; } catch (TimeoutException e) { throw e; } }
/* * computes t(Omega) %*% v in multithreaded fashion */ public Vector mutlithreadedTRightMultiply(final Vector v) { int nThreads = Runtime.getRuntime().availableProcessors(); ExecutorService es = new ThreadPoolExecutor( nThreads, nThreads, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(kp)); try { List<Future<Double>> dotFutures = new ArrayList<Future<Double>>(kp); for (int i = 0; i < kp; i++) { final int index = i; Future<Double> dotFuture = es.submit( new Callable<Double>() { @Override public Double call() throws Exception { double result = 0.0; if (v.isDense()) { for (int k = 0; k < v.size(); k++) // it's ok, this is reentrant result += getQuick(k, index) * v.getQuick(k); } else { for (Iterator<Vector.Element> iter = v.iterateNonZero(); iter.hasNext(); ) { Vector.Element el = iter.next(); int k = el.index(); result += getQuick(k, index) * el.get(); } } return result; } }); dotFutures.add(dotFuture); } try { Vector res = new DenseVector(kp); for (int i = 0; i < kp; i++) { res.setQuick(i, dotFutures.get(i).get()); } return res; } catch (InterruptedException exc) { throw new RuntimeException("Interrupted", exc); } catch (ExecutionException exc) { if (exc.getCause() instanceof RuntimeException) throw (RuntimeException) exc.getCause(); else throw new RuntimeException(exc.getCause()); } } finally { es.shutdown(); } }
@SuppressWarnings("unchecked") static <T> void checkCompletedExceptionally(CompletableFuture<T> cf, boolean cancelled) throws Exception { try { cf.join(); fail("Excepted exception to be thrown"); } catch (CompletionException x) { if (cancelled) fail(); else pass(); } catch (CancellationException x) { if (cancelled) pass(); else fail(); } try { cf.getNow(null); fail("Excepted exception to be thrown"); } catch (CompletionException x) { if (cancelled) fail(); else pass(); } catch (CancellationException x) { if (cancelled) pass(); else fail(); } try { cf.get(); fail("Excepted exception to be thrown"); } catch (CancellationException x) { if (cancelled) pass(); else fail(); } catch (ExecutionException x) { if (cancelled) check(x.getCause() instanceof CancellationException); else pass(); } try { cf.get(0L, SECONDS); fail("Excepted exception to be thrown"); } catch (CancellationException x) { if (cancelled) pass(); else fail(); } catch (ExecutionException x) { if (cancelled) check(x.getCause() instanceof CancellationException); else pass(); } check(cf.isDone(), "Expected isDone to be true, got:" + cf); check( cf.isCancelled() == cancelled, "Expected isCancelled: " + cancelled + ", got:" + cf.isCancelled()); check( cf.cancel(true) == cancelled, "Expected cancel: " + cancelled + ", got:" + cf.cancel(true)); check(cf.toString().contains("[Completed exceptionally]")); // ## TODO: 'E'xceptionally check(cf.complete((T) new Object()) == false, "Expected complete() to fail"); check( cf.completeExceptionally(new Throwable()) == false, "Expected completeExceptionally() to fail, already completed"); }
private static ExecutionException addSubmissionTrace( StackTraceElement[] submissionTrace, ExecutionException e) { if (e.getCause() == null) { return filterTrace(e); } Throwable cause = e.getCause(); StackTraceElement[] combined = filterTrace(concat(cause.getStackTrace(), submissionTrace, StackTraceElement.class)); cause.setStackTrace(combined); return filterTrace(e); }
@Override public ListenableFuture<ServiceFilterResponse> handleRequest( final ServiceFilterRequest request, final NextServiceFilterCallback nextServiceFilterCallback) { // In this example, if authentication is already in progress we block the request // until authentication is complete to avoid unnecessary authentications as // a result of HTTP status code 401. // If authentication was detected, add the token to the request. waitAndUpdateRequestToken(request); // Send the request down the filter chain // retrying up to 5 times on 401 response codes. ListenableFuture<ServiceFilterResponse> future = null; ServiceFilterResponse response = null; int responseCode = 401; for (int i = 0; (i < 5) && (responseCode == 401); i++) { future = nextServiceFilterCallback.onNext(request); try { response = future.get(); responseCode = response.getStatus().getStatusCode(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { if (e.getCause().getClass() == MobileServiceException.class) { MobileServiceException mEx = (MobileServiceException) e.getCause(); responseCode = mEx.getResponse().getStatus().getStatusCode(); if (responseCode == 401) { // Two simultaneous requests from independent threads could get HTTP status 401. // Protecting against that right here so multiple authentication requests are // not setup to run on the UI thread. // We only want to authenticate once. Requests should just wait and retry // with the new token. if (mAtomicAuthenticatingFlag.compareAndSet(false, true)) { // Authenticate on UI thread runOnUiThread( new Runnable() { @Override public void run() { // Force a token refresh during authentication. authenticate(true); } }); } // Wait for authentication to complete then update the token in the request. waitAndUpdateRequestToken(request); mAtomicAuthenticatingFlag.set(false); } } } } return future; }
private void tryCancellation(Future<?> f) throws Exception { f.cancel(true); assertTrue(f.isCancelled()); assertTrue(f.isDone()); try { Object o = f.get(); fail("Expected cancellation, got " + o); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof RuntimeException); assertEquals("Cancelled", e.getCause().getMessage()); } }
// TODO: move this to a utility package private static <T, X extends Throwable> T getFutureResult(Future<T> future, Class<X> type) throws X { try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } catch (ExecutionException e) { Throwables.propagateIfPossible(e.getCause(), type); throw Throwables.propagate(e.getCause()); } }
@Override @SuppressWarnings("unchecked") public synchronized void futureDone(Future<Object> objectFuture) { SenderContainer sc = futures.get(objectFuture); if (sc.processed) { // This can happen - it is a race condition in JGroups' NotifyingFuture.setListener() where // a listener // could be notified twice. if (trace) log.tracef( "Not processing callback; already processed callback for sender %s", sc.address); } else { sc.processed = true; Address sender = sc.address; boolean done = false; try { if (retval == null) { Object response = objectFuture.get(); if (trace) log.tracef("Received response: %s from %s", response, sender); filter.isAcceptable(response, sender); if (!filter.needMoreResponses()) { retval = new RspList(Collections.singleton(new Rsp(sender, response))); done = true; // TODO cancel other tasks? } } else { if (trace) log.tracef( "Skipping response from %s since a valid response for this request has already been received", sender); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { exception = e; if (e.getCause() instanceof org.jgroups.TimeoutException) exception = new TimeoutException("Timeout!", e); else if (e.getCause() instanceof Exception) exception = (Exception) e.getCause(); else exception = new CacheException("Caught a throwable", e.getCause()); if (log.isDebugEnabled()) log.debugf( "Caught exception %s from sender %s. Will skip this response.", exception.getClass().getName(), sender); log.trace("Exception caught: ", exception); } finally { expectedResponses--; if (expectedResponses == 0 || done) { this.notify(); // make sure to awake waiting thread, but avoid unnecessary wakeups! } } } }
public Instance getInstance(final ThreadContext callContext) throws OpenEJBException { final BeanContext beanContext = callContext.getBeanContext(); Data data = (Data) beanContext.getContainerData(); AtomicReference<Future<Instance>> singleton = data.singleton; try { // Has the singleton been created yet? // If there is a Future object in the AtomicReference, then // it's either been created or is being created now. Future<Instance> singletonFuture = singleton.get(); if (singletonFuture != null) return singletonFuture.get(); // The singleton has not been created nor is being created // We will construct this FutureTask and compete with the // other threads for the right to create the singleton FutureTask<Instance> task = new FutureTask<Instance>( new Callable<Instance>() { public Instance call() throws Exception { return createInstance(callContext, beanContext); } }); do { // If our FutureTask was the one to win the slot // than we are the ones responsible for creating // the singleton while the others wait. if (singleton.compareAndSet(null, task)) { task.run(); } // If we didn't win the slot and no other FutureTask // has been set by a different thread, than we need // to try again. } while ((singletonFuture = singleton.get()) == null); // At this point we can safely return the singleton return singletonFuture.get(); } catch (InterruptedException e) { Thread.interrupted(); throw new ApplicationException( new NoSuchEJBException("Singleton initialization interrupted").initCause(e)); } catch (ExecutionException e) { Throwable throwable = e.getCause(); if (throwable instanceof ApplicationException) { throw (ApplicationException) throwable; } throw new ApplicationException( new NoSuchEJBException("Singleton initialization failed").initCause(e.getCause())); } }
private static RspList<Object> processCalls( Map<Address, ReplicableCommand> commands, long timeout, ResponseMode mode, Marshaller marshaller, CommandAwareRpcDispatcher card, boolean oob, boolean ignoreLeavers) throws Exception { if (trace) log.tracef("Replication task sending %s with response mode %s", commands, mode); if (commands.isEmpty()) return new RspList<>(); RequestOptions opts = new RequestOptions(mode, timeout); // opts.setExclusionList(card.getChannel().getAddress()); Map<Address, Future<Object>> futures = new HashMap<Address, Future<Object>>(commands.size()); RspList<Object> retval = new RspList<>(); for (Map.Entry<Address, ReplicableCommand> cmd : commands.entrySet()) { Buffer buf = marshallCall(marshaller, cmd.getValue()); Address dest = cmd.getKey(); boolean rsvp = isRsvpCommand(cmd.getValue()); futures.put( dest, card.sendMessageWithFuture(constructMessage(buf, dest, oob, mode, rsvp, false), opts)); } // a get() on each future will block till that call completes. TimeService timeService = card.timeService; long waitTime = timeService.expectedEndTime(timeout, MILLISECONDS); for (Map.Entry<Address, Future<Object>> entry : futures.entrySet()) { Address target = entry.getKey(); try { retval.addRsp( target, entry.getValue().get(timeService.remainingTime(waitTime, MILLISECONDS), MILLISECONDS)); } catch (java.util.concurrent.TimeoutException te) { throw new TimeoutException( formatString( "Timed out after %s waiting for a response from %s", prettyPrintTime(timeout), target)); } catch (ExecutionException e) { if (ignoreLeavers && e.getCause() instanceof SuspectedException) { retval.addRsp(target, new ExceptionResponse((SuspectedException) e.getCause())); } else { throw wrapThrowableInException(e.getCause()); } } } return retval; }
private <T> T submitAndWait(final Callable<T> callable) { try { return m_executor.submit(callable).get(); } catch (final InterruptedException e) { throw new RuntimeException(e); } catch (final ExecutionException e) { if (e.getCause() instanceof RuntimeException) { throw ((RuntimeException) e.getCause()); } else { throw new RuntimeException(e.getCause()); } } }
public <T> T get(final Future<T> future) { try { return future.get(); } catch (InterruptedException e1) { throw new InternalException("Future.get interrupted:" + e1.getMessage()); } catch (ExecutionException e1) { if (e1.getCause() instanceof RuntimeException) { throw (RuntimeException) e1.getCause(); } else { throw new InternalException("Caught exception thrown by Future.get:" + e1.getMessage()); } } }
public V txGet() throws ElasticSearchException { try { return get(); } catch (InterruptedException e) { throw new ElasticSearchInterruptedException(e.getMessage()); } catch (ExecutionException e) { if (e.getCause() instanceof ElasticSearchException) { throw (ElasticSearchException) e.getCause(); } else { throw new TransportException("Failed execution", e); } } }
@Override public MuleEvent process(MuleEvent event) throws MuleException { HttpRestRequest request = getHttpRestRequest(event); String path = request.getResourcePath(); MuleEvent handled = handleEvent(event, path); if (handled != null) { return handled; } // check for raml descriptor request if (path.equals(getApi().getUri()) && ActionType.GET.toString().equals(request.getMethod().toUpperCase()) && request.getAdapter().getAcceptableResponseMediaTypes().contains(APPLICATION_RAML)) { String raml = config.getApikitRaml(event); event.getMessage().setPayload(raml); event.getMessage().setOutboundProperty(HttpConstants.HEADER_CONTENT_TYPE, APPLICATION_RAML); event.getMessage().setOutboundProperty(HttpConstants.HEADER_CONTENT_LENGTH, raml.length()); event.getMessage().setOutboundProperty("Access-Control-Allow-Origin", "*"); return event; } URIPattern uriPattern; URIResolver uriResolver; path = path.isEmpty() ? "/" : path; try { uriPattern = getUriPatternCache().get(path); uriResolver = getUriResolverCache().get(path); } catch (ExecutionException e) { if (e.getCause() instanceof MuleRestException) { throw (MuleRestException) e.getCause(); } throw new DefaultMuleException(e); } Resource resource = getRoutingTable().get(uriPattern); if (resource.getAction(request.getMethod()) == null) { throw new MethodNotAllowedException(resource.getUri(), request.getMethod()); } ResolvedVariables resolvedVariables = uriResolver.resolve(uriPattern); processUriParameters(resolvedVariables, resource, event); Flow flow = getFlow(resource, request.getMethod()); if (flow == null) { throw new ApikitRuntimeException("Flow not found for resource: " + resource); } return request.process(flow, resource.getAction(request.getMethod())); }
@Test(groups = {"standalone", "default_provider"}) public void unexpectingTimeoutTest() throws IOException { final AtomicInteger counts = new AtomicInteger(); final int timeout = 100; final AsyncHttpClient client = getAsyncHttpClient( new AsyncHttpClientConfig.Builder().setRequestTimeoutInMs(timeout).build()); try { Future<Response> responseFuture = client .prepareGet(getTargetUrl()) .execute( new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { counts.incrementAndGet(); return response; } @Override public void onThrowable(Throwable t) { counts.incrementAndGet(); super.onThrowable(t); } }); // currently, an exception is expected // because the grizzly provider would throw IllegalStateException if WWW-Authenticate header // doesn't exist with 401 response status. try { Response response = responseFuture.get(); assertNull(response); } catch (InterruptedException e) { fail("Interrupted.", e); } catch (ExecutionException e) { assertFalse(e.getCause() instanceof TimeoutException); assertEquals(e.getCause().getMessage(), getExpectedTimeoutMessage()); } // wait for timeout again. try { Thread.sleep(timeout * 2); } catch (InterruptedException e) { fail("Interrupted.", e); } // the result should be either onCompleted or onThrowable. assertEquals(1, counts.get(), "result should be one"); } finally { client.close(); } }
@Override public V txGet() { try { return get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Future got interrupted", e); } catch (ExecutionException e) { if (e.getCause() instanceof ElasticsearchException) { throw (ElasticsearchException) e.getCause(); } else { throw new TransportException("Failed execution", e); } } }
/** * Waits for the computation embodied by the given {@code future} to complete and then retrieves * its result. * * <p>This method requires that {@code future}'s computation may only throw a {@link VException} - * any other exception type will result in a {@link RuntimeException}. * * <p>Likewise, if the {@code future}'s execution raises an {@link InterruptedException}, this * method will raise a {@link RuntimeException}. * * @param future the future being executed * @return the computed result of the future * @throws VException if the computation embodied by the future threw a {@link VException} * @throws RuntimeException if the computation embodied by the future threw an exception other * than {@link VException}, or if the future's executions raised an {@link * InterruptedException} */ public static <T> T sync(Future<T> future) throws VException { try { return future.get(); } catch (ExecutionException e) { if (e.getCause() instanceof VException) { throw (VException) e.getCause(); } else if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException( "Vanadium futures may only raise a VException or a RuntimeException.", e.getCause()); } catch (InterruptedException e) { throw new RuntimeException("Vanadium future may not raise an InterruptedException.", e); } }