List of usage examples for java.util.concurrent ExecutionException getCause
public synchronized Throwable getCause()
From source file:org.rhq.plugins.agent.AgentServerComponent.java
public OperationResult invokeOperation(String name, Configuration params) { OperationResult result = null;//from ww w.ja v a 2 s . co m // I know all operation names have identical MBean operations on the agent management MBean // I also know about all operations that have void and non-void parameters try { if ((params == null) || (params.getProperties().size() == 0)) { result = (OperationResult) getAgentBean().getOperation(name).invoke(); } else { if (name.equals("retrievePluginInfo")) { String pluginToUpdate = params.getSimple("pluginName").getStringValue(); result = (OperationResult) getAgentBean().getOperation(name).invoke(pluginToUpdate); } else if (name.equals("executeAvailabilityScan")) { Boolean changesOnly = params.getSimple("changesOnly").getBooleanValue(); result = (OperationResult) getAgentBean().getOperation(name).invoke(changesOnly); } else if (name.equals("retrieveCurrentDateTime")) { String timeZone = params.getSimple("timeZone").getStringValue(); result = new OperationResult(); result.getComplexResults().put( new PropertySimple("dateTime", getAgentBean().getOperation(name).invoke(timeZone))); } else if (name.equals("setDebugMode")) { Boolean enabled = params.getSimple("enabled").getBooleanValue(); Boolean traceMessaging = params.getSimple("traceMessaging").getBooleanValue(); result = new OperationResult(); getAgentBean().getOperation(name).invoke(enabled, traceMessaging); } else if (name.equals("executePromptCommand")) { String command = params.getSimple("command").getStringValue(); result = new OperationResult(); try { Object output = getAgentBean().getOperation(name).invoke(command); result.getComplexResults().put(new PropertySimple("output", output)); } catch (EmsInvocationException eie) { if (eie.getCause() instanceof MBeanException && eie.getCause().getCause() instanceof ExecutionException) { // the prompt command threw the exception - in this case: // the message is the prompt output and the cause is the actual prompt exception ExecutionException ee = (ExecutionException) eie.getCause().getCause(); String output = ee.getMessage(); CharArrayWriter caw = new CharArrayWriter(); ee.getCause().printStackTrace(new PrintWriter(caw)); String error = caw.toString(); result.getComplexResults().put(new PropertySimple("output", output)); result.getComplexResults().put(new PropertySimple("error", error)); } else { throw eie; } } } else if (name.equals("switchToServer")) { String server = params.getSimpleValue("server", null); getAgentBean().getOperation(name).invoke(server); } else { // this should really never happen throw new IllegalArgumentException("Operation [" + name + "] does not support params"); } } } catch (Exception e) { throw new RuntimeException("Failed to invoke operation [" + name + "]", e); } return result; }
From source file:org.apache.pulsar.client.impl.PulsarClientImpl.java
@Override public Reader createReader(String topic, MessageId startMessageId, ReaderConfiguration conf) throws PulsarClientException { try {/*ww w . j a va 2s .c o m*/ return createReaderAsync(topic, startMessageId, conf).get(); } catch (ExecutionException e) { Throwable t = e.getCause(); if (t instanceof PulsarClientException) { throw (PulsarClientException) t; } else { throw new PulsarClientException(t); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new PulsarClientException(e); } }
From source file:org.eclipse.smarthome.binding.openweathermap.internal.connection.OpenWeatherMapConnection.java
private String getResponse(String url) { try {/* w ww . j ava 2 s . c om*/ if (logger.isTraceEnabled()) { logger.trace("OpenWeatherMap request: URL = '{}'", uglifyApikey(url)); } ContentResponse contentResponse = httpClient.newRequest(url).method(GET).timeout(10, TimeUnit.SECONDS) .send(); int httpStatus = contentResponse.getStatus(); String content = contentResponse.getContentAsString(); String errorMessage = StringUtils.EMPTY; logger.trace("OpenWeatherMap response: status = {}, content = '{}'", httpStatus, content); switch (httpStatus) { case OK_200: return content; case BAD_REQUEST_400: case UNAUTHORIZED_401: case NOT_FOUND_404: errorMessage = getErrorMessage(content); logger.debug("OpenWeatherMap server responded with status code {}: {}", httpStatus, errorMessage); throw new OpenWeatherMapConfigurationException(errorMessage); case TOO_MANY_REQUESTS_429: // TODO disable refresh job temporarily (see https://openweathermap.org/appid#Accesslimitation) default: errorMessage = getErrorMessage(content); logger.debug("OpenWeatherMap server responded with status code {}: {}", httpStatus, errorMessage); throw new OpenWeatherMapCommunicationException(errorMessage); } } catch (ExecutionException e) { String errorMessage = e.getLocalizedMessage(); logger.trace("Exception occurred during execution: {}", errorMessage, e); if (e.getCause() instanceof HttpResponseException) { logger.debug("OpenWeatherMap server responded with status code {}: Invalid API key.", UNAUTHORIZED_401); throw new OpenWeatherMapConfigurationException("@text/offline.conf-error-invalid-apikey", e.getCause()); } else { throw new OpenWeatherMapCommunicationException(errorMessage, e.getCause()); } } catch (InterruptedException | TimeoutException e) { logger.debug("Exception occurred during execution: {}", e.getLocalizedMessage(), e); throw new OpenWeatherMapCommunicationException(e.getLocalizedMessage(), e.getCause()); } }
From source file:com.quantiply.druid.HTTPTranquilityLoader.java
protected void sendCmd(WriterCommand cmd) throws Throwable { try {// w w w. j ava 2 s . c o m //May block if queue is full so we must periodically check that writer is alive while (!writerCmdQueue.offer(cmd, 100, TimeUnit.MILLISECONDS)) { checkWriter(); } } catch (ExecutionException e) { logger.error("Tranquility writer died", e.getCause()); throw e.getCause(); } catch (InterruptedException firstEx) { /* If the main Samza thread is interrupted, it's likely a shutdown command Try for a clean shutdown by waiting a little longer to enqueue the message */ try { if (!writerCmdQueue.offer(cmd, SHUTDOWN_WAIT_MS, TimeUnit.MILLISECONDS)) { throw new IOException("Timed out trying to pass message to Tranquility writer on shutdown"); } } catch (InterruptedException e) { throw new IOException("Interrupted passing message to Tranquility writer", e); } } }
From source file:com.amazonaws.mobileconnectors.s3.transferutility.UploadTask.java
private Boolean uploadMultipartAndWaitForCompletion() throws ExecutionException { /*//from w ww . j a v a 2s .c o m * For a new multipart upload, upload.mMultipartId should be null. If * it's a resumed upload, upload.mMultipartId would not be null. */ long bytesAlreadyTransferrd = 0; if (upload.multipartId == null || upload.multipartId.isEmpty()) { final PutObjectRequest putObjectRequest = createPutObjectRequest(upload); TransferUtility.appendMultipartTransferServiceUserAgentString(putObjectRequest); try { upload.multipartId = initiateMultipartUpload(putObjectRequest); } catch (final AmazonClientException ace) { LOGGER.error("Error initiating multipart upload: " + upload.id + " due to " + ace.getMessage(), ace); updater.throwError(upload.id, ace); updater.updateState(upload.id, TransferState.FAILED); return false; } dbUtil.updateMultipartId(upload.id, upload.multipartId); } else { /* * For a resumed upload, we should calculate the bytes already * transferred. */ bytesAlreadyTransferrd = dbUtil.queryBytesTransferredByMainUploadId(upload.id); if (bytesAlreadyTransferrd > 0) { LOGGER.debug(String.format("Resume transfer %d from %d bytes", upload.id, bytesAlreadyTransferrd)); } } updater.updateProgress(upload.id, bytesAlreadyTransferrd, upload.bytesTotal); final List<UploadPartRequest> requestList = dbUtil.getNonCompletedPartRequestsFromDB(upload.id, upload.multipartId); LOGGER.debug("multipart upload " + upload.id + " in " + requestList.size() + " parts."); final ArrayList<Future<Boolean>> futures = new ArrayList<Future<Boolean>>(); for (final UploadPartRequest request : requestList) { TransferUtility.appendMultipartTransferServiceUserAgentString(request); request.setGeneralProgressListener(updater.newProgressListener(upload.id)); futures.add(TransferThreadPool.submitTask(new UploadPartTask(request, s3, dbUtil, networkInfo))); } try { boolean isSuccess = true; /* * Future.get() will block the current thread until the method * returns. */ for (final Future<Boolean> f : futures) { // UploadPartTask returns false when it's interrupted by user // and the state is set by caller final boolean b = f.get(); isSuccess &= b; } if (!isSuccess) { return false; } } catch (final InterruptedException e) { /* * Future.get() will catch InterruptedException, but it's not a * failure, it may be caused by a pause operation from applications. */ for (final Future<?> f : futures) { f.cancel(true); } // abort by user LOGGER.debug("Transfer " + upload.id + " is interrupted by user"); return false; } catch (final ExecutionException ee) { // handle pause, cancel, etc boolean isNetworkInterrupted = false; if (ee.getCause() != null && ee.getCause() instanceof Exception) { // check for network interruption and pause the transfer instead of failing them isNetworkInterrupted = dbUtil.checkWaitingForNetworkPartRequestsFromDB(upload.id); if (isNetworkInterrupted) { LOGGER.debug("Network Connection Interrupted: Transfer " + upload.id + " waits for network"); updater.updateState(upload.id, TransferState.WAITING_FOR_NETWORK); return false; } final Exception e = (Exception) ee.getCause(); if (RetryUtils.isInterrupted(e)) { /* * thread is interrupted by user. don't update the state as * it's set by caller who interrupted */ LOGGER.debug("Transfer " + upload.id + " is interrupted by user"); return false; } else if (e.getCause() != null && e.getCause() instanceof IOException && !networkInfo.isNetworkConnected()) { LOGGER.debug("Transfer " + upload.id + " waits for network"); updater.updateState(upload.id, TransferState.WAITING_FOR_NETWORK); } updater.throwError(upload.id, e); } updater.updateState(upload.id, TransferState.FAILED); return false; } try { completeMultiPartUpload(upload.id, upload.bucketName, upload.key, upload.multipartId); updater.updateProgress(upload.id, upload.bytesTotal, upload.bytesTotal); updater.updateState(upload.id, TransferState.COMPLETED); return true; } catch (final AmazonClientException ace) { LOGGER.error("Failed to complete multipart: " + upload.id + " due to " + ace.getMessage(), ace); updater.throwError(upload.id, ace); updater.updateState(upload.id, TransferState.FAILED); return false; } }
From source file:org.apache.hadoop.hbase.ipc.AsyncRpcClient.java
/** * Call method async//w w w .j a va2 s . c o m */ private void callMethod(Descriptors.MethodDescriptor md, final PayloadCarryingRpcController pcrc, Message param, Message returnType, User ticket, InetSocketAddress addr, final RpcCallback<Message> done) { final AsyncRpcChannel connection; try { connection = createRpcChannel(md.getService().getName(), addr, ticket); connection.callMethod(md, pcrc, param, returnType) .addListener(new GenericFutureListener<Future<Message>>() { @Override public void operationComplete(Future<Message> future) throws Exception { if (!future.isSuccess()) { Throwable cause = future.cause(); if (cause instanceof IOException) { pcrc.setFailed((IOException) cause); } else { pcrc.setFailed(new IOException(cause)); } } else { try { done.run(future.get()); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof IOException) { pcrc.setFailed((IOException) cause); } else { pcrc.setFailed(new IOException(cause)); } } catch (InterruptedException e) { pcrc.setFailed(new IOException(e)); } } } }); } catch (StoppedRpcClientException | FailedServerException e) { pcrc.setFailed(e); } }
From source file:org.apache.bookkeeper.client.MetadataUpdateLoopTest.java
/** * Test that if we have two conflicting updates, only one of the loops will complete. * The other will throw an exception./*from w w w.ja va 2 s .c o m*/ */ @Test public void testNewestValueCannotBeUsedAfterReadBack() throws Exception { try (BlockableMockLedgerManager lm = spy(new BlockableMockLedgerManager())) { lm.blockWrites(); long ledgerId = 1234L; BookieSocketAddress b0 = new BookieSocketAddress("0.0.0.0:3181"); BookieSocketAddress b1 = new BookieSocketAddress("0.0.0.1:3181"); LedgerMetadata initMeta = LedgerMetadataBuilder.create().withEnsembleSize(1) .withDigestType(DigestType.CRC32C).withPassword(new byte[0]).withWriteQuorumSize(1) .withAckQuorumSize(1).newEnsembleEntry(0L, Lists.newArrayList(b0)).build(); Versioned<LedgerMetadata> writtenMetadata = lm.createLedgerMetadata(ledgerId, initMeta).get(); AtomicReference<Versioned<LedgerMetadata>> reference = new AtomicReference<>(writtenMetadata); CompletableFuture<Versioned<LedgerMetadata>> loop1 = new MetadataUpdateLoop(lm, ledgerId, reference::get, (currentMetadata) -> !currentMetadata.isClosed(), (currentMetadata) -> { return LedgerMetadataBuilder.from(currentMetadata).withClosedState().withLastEntryId(10L) .withLength(100L).build(); }, reference::compareAndSet).run(); CompletableFuture<Versioned<LedgerMetadata>> loop2 = new MetadataUpdateLoop(lm, ledgerId, reference::get, (currentMetadata) -> { if (currentMetadata.isClosed()) { throw new BKException.BKLedgerClosedException(); } else { return currentMetadata.getEnsembleAt(0L).contains(b0); } }, (currentMetadata) -> { List<BookieSocketAddress> ensemble = Lists.newArrayList(currentMetadata.getEnsembleAt(0L)); ensemble.set(0, b1); return LedgerMetadataBuilder.from(currentMetadata).replaceEnsembleEntry(0L, ensemble) .build(); }, reference::compareAndSet).run(); lm.releaseWrites(); Versioned<LedgerMetadata> l1meta = loop1.get(); try { loop2.get(); Assert.fail("Update loop should have failed"); } catch (ExecutionException ee) { Assert.assertEquals(ee.getCause().getClass(), BKException.BKLedgerClosedException.class); } Assert.assertEquals(l1meta, reference.get()); Assert.assertEquals(l1meta.getValue().getEnsembleAt(0L).get(0), b0); Assert.assertTrue(l1meta.getValue().isClosed()); verify(lm, times(2)).writeLedgerMetadata(anyLong(), any(), any()); } }
From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ContainerLocalizer.java
/** * Create the payload for the HeartBeat. Mainly the list of * {@link LocalResourceStatus}es// w ww . j a va 2 s .c o m * * @return a {@link LocalizerStatus} that can be sent via heartbeat. * @throws InterruptedException */ private LocalizerStatus createStatus() throws InterruptedException { final List<LocalResourceStatus> currentResources = new ArrayList<LocalResourceStatus>(); // TODO: Synchronization?? for (Iterator<LocalResource> i = pendingResources.keySet().iterator(); i.hasNext();) { LocalResource rsrc = i.next(); LocalResourceStatus stat = recordFactory.newRecordInstance(LocalResourceStatus.class); stat.setResource(rsrc); Future<Path> fPath = pendingResources.get(rsrc); if (fPath.isDone()) { try { Path localPath = fPath.get(); stat.setLocalPath(URL.fromPath(localPath)); stat.setLocalSize(FileUtil.getDU(new File(localPath.getParent().toUri()))); stat.setStatus(ResourceStatusType.FETCH_SUCCESS); } catch (ExecutionException e) { stat.setStatus(ResourceStatusType.FETCH_FAILURE); stat.setException(SerializedException.newInstance(e.getCause())); } catch (CancellationException e) { stat.setStatus(ResourceStatusType.FETCH_FAILURE); stat.setException(SerializedException.newInstance(e)); } // TODO shouldn't remove until ACK i.remove(); } else { stat.setStatus(ResourceStatusType.FETCH_PENDING); } currentResources.add(stat); } LocalizerStatus status = recordFactory.newRecordInstance(LocalizerStatus.class); status.setLocalizerId(localizerId); status.addAllResources(currentResources); return status; }
From source file:org.peercast.pecaport.PecaPortFragmentBase.java
private void getFuture(Future<?> future) { try {/* w ww . j av a 2s . c o m*/ future.get(); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } catch (InterruptedException | CancellationException e) { throw new RuntimeException(e); } }
From source file:io.flutter.plugins.googlesignin.GoogleSignInPlugin.java
/** * Gets an OAuth access token with the scopes that were specified during {@link * #init(response,List<String>) initialization} for the user with the specified email * address./* ww w .j av a2s . c o m*/ */ private void getToken(Response response, final String email) { if (email == null) { response.error(ERROR_REASON_EXCEPTION, "Email is null", null); return; } if (checkAndSetPendingOperation(METHOD_GET_TOKEN, response)) { return; } Callable<String> getTokenTask = new Callable<String>() { @Override public String call() throws Exception { Account account = new Account(email, "com.google"); String scopesStr = "oauth2:" + Joiner.on(' ').join(requestedScopes); return GoogleAuthUtil.getToken(activity.getApplication(), account, scopesStr); } }; backgroundTaskRunner.runInBackground(getTokenTask, new BackgroundTaskRunner.Callback<String>() { @Override public void run(Future<String> tokenFuture) { try { finishWithSuccess(tokenFuture.get()); } catch (ExecutionException e) { Log.e(TAG, "Exception getting access token", e); finishWithError(ERROR_REASON_EXCEPTION, e.getCause().getMessage()); } catch (InterruptedException e) { finishWithError(ERROR_REASON_EXCEPTION, e.getMessage()); } } }); }