List of usage examples for java.util.concurrent ExecutionException getCause
public synchronized Throwable getCause()
From source file:org.apache.http.HC4.impl.execchain.MinimalClientExec.java
@Override public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); rewriteRequestURI(request, route);/*from w ww . ja v a 2 s . co m*/ final ConnectionRequest connRequest = connManager.requestConnection(route, null); if (execAware != null) { if (execAware.isAborted()) { connRequest.cancel(); throw new RequestAbortedException("Request aborted"); } else { execAware.setCancellable(connRequest); } } final RequestConfig config = context.getRequestConfig(); final HttpClientConnection managedConn; try { final int timeout = config.getConnectionRequestTimeout(); managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS); } catch (final InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new RequestAbortedException("Request aborted", interrupted); } catch (final ExecutionException ex) { Throwable cause = ex.getCause(); if (cause == null) { cause = ex; } throw new RequestAbortedException("Request execution failed", cause); } final ConnectionHolder releaseTrigger = new ConnectionHolder(log, connManager, managedConn); try { if (execAware != null) { if (execAware.isAborted()) { releaseTrigger.close(); throw new RequestAbortedException("Request aborted"); } else { execAware.setCancellable(releaseTrigger); } } if (!managedConn.isOpen()) { final int timeout = config.getConnectTimeout(); this.connManager.connect(managedConn, route, timeout > 0 ? timeout : 0, context); this.connManager.routeComplete(managedConn, route, context); } final int timeout = config.getSocketTimeout(); if (timeout >= 0) { managedConn.setSocketTimeout(timeout); } HttpHost target = null; final HttpRequest original = request.getOriginal(); if (original instanceof HttpUriRequest) { final URI uri = ((HttpUriRequest) original).getURI(); if (uri.isAbsolute()) { target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); } } if (target == null) { target = route.getTargetHost(); } context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); httpProcessor.process(request, context); final HttpResponse response = requestExecutor.execute(request, managedConn, context); httpProcessor.process(response, context); // The connection is in or can be brought to a re-usable state. if (reuseStrategy.keepAlive(response, context)) { // Set the idle duration of this connection final long duration = keepAliveStrategy.getKeepAliveDuration(response, context); releaseTrigger.setValidFor(duration, TimeUnit.MILLISECONDS); releaseTrigger.markReusable(); } else { releaseTrigger.markNonReusable(); } // check for entity, release connection if possible final HttpEntity entity = response.getEntity(); if (entity == null || !entity.isStreaming()) { // connection not needed and (assumed to be) in re-usable state releaseTrigger.releaseConnection(); return new HttpResponseProxy(response, null); } else { return new HttpResponseProxy(response, releaseTrigger); } } catch (final ConnectionShutdownException ex) { final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down"); ioex.initCause(ex); throw ioex; } catch (final HttpException ex) { releaseTrigger.abortConnection(); throw ex; } catch (final IOException ex) { releaseTrigger.abortConnection(); throw ex; } catch (final RuntimeException ex) { releaseTrigger.abortConnection(); throw ex; } }
From source file:org.sonarsource.sonarlint.core.mediumtest.StandaloneIssueMediumTest.java
@Test public void concurrentAnalysis() throws Throwable { final ClientInputFile inputFile = prepareInputFile("Foo.java", "public class Foo {\n" + " public void foo() {\n" + " int x;\n" + " System.out.println(\"Foo\");\n" + " System.out.println(\"Foo\"); //NOSONAR\n" + " }\n" + "}", false);/* w ww. j a v a2 s . c om*/ final Path workDir = temp.newFolder().toPath(); int parallelExecutions = 4; ExecutorService executor = Executors.newFixedThreadPool(parallelExecutions); List<Future<?>> results = new ArrayList<>(); for (int i = 0; i < parallelExecutions; i++) { Runnable worker = new Runnable() { @Override public void run() { sonarlint.analyze(new StandaloneAnalysisConfiguration(baseDir.toPath(), workDir, Arrays.asList(inputFile), ImmutableMap.of()), issue -> { }); } }; results.add(executor.submit(worker)); } executor.shutdown(); while (!executor.isTerminated()) { } for (Future<?> future : results) { try { future.get(); } catch (ExecutionException e) { throw e.getCause(); } } }
From source file:com.ok2c.lightmtp.impl.protocol.ReceiveDataCodec.java
private void deliveryCompleted(final ServerState sessionState) { if (this.mode.equals(DataAckMode.SINGLE)) { try {/*from ww w . jav a 2 s .co m*/ DeliveryResult result = this.pendingDelivery.get(); this.pendingReplies.add(result.getReply()); } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause == null) { cause = ex; } this.pendingReplies.add(createErrorReply(cause)); } catch (InterruptedException ex) { this.pendingReplies.add(createErrorReply(ex)); } } else { List<String> recipients = sessionState.getRecipients(); try { DeliveryResult results = this.pendingDelivery.get(); Map<String, SMTPReply> map = new HashMap<String, SMTPReply>(); for (RcptResult res : results.getFailures()) { map.put(res.getRecipient(), res.getReply()); } for (String recipient : recipients) { SMTPReply reply = map.get(recipient); if (reply == null) { reply = results.getReply(); } this.pendingReplies.add(reply); } } catch (InterruptedException ex) { SMTPReply reply = createErrorReply(ex); for (String recipient : recipients) { this.pendingReplies.add(reply); } } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause == null) { cause = ex; } SMTPReply reply = createErrorReply(cause); for (String recipient : recipients) { this.pendingReplies.add(reply); } } } }
From source file:org.apache.http2.impl.conn.PoolingClientConnectionManager.java
ManagedClientConnection leaseConnection(final Future<HttpPoolEntry> future, final long timeout, final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { HttpPoolEntry entry;//w w w.j a va2s .c om try { entry = future.get(timeout, tunit); if (entry == null || future.isCancelled()) { throw new InterruptedException(); } if (entry.getConnection() == null) { throw new IllegalStateException("Pool entry with no connection"); } if (this.log.isDebugEnabled()) { this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute())); } return new ManagedClientConnectionImpl(this, this.operator, entry); } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause == null) { cause = ex; } this.log.error("Unexpected exception leasing connection from pool", cause); // Should never happen throw new InterruptedException(); } catch (TimeoutException ex) { throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool"); } }
From source file:org.openbaton.nfvo.vnfm_reg.tasks.ScalingTask.java
@Override protected NFVMessage doWork() throws Exception { log.debug("NFVO: SCALING"); log.trace("HB_VERSION == " + virtualNetworkFunctionRecord.getHb_version()); log.debug("The VNFR: " + virtualNetworkFunctionRecord.getName() + " is in status --> " + virtualNetworkFunctionRecord.getStatus()); saveVirtualNetworkFunctionRecord();/*from ww w . j a v a 2 s .com*/ VNFComponent componentToAdd = null; VirtualDeploymentUnit vdu = null; for (VirtualDeploymentUnit virtualDeploymentUnit : virtualNetworkFunctionRecord.getVdu()) { for (VNFComponent vnfComponent : virtualDeploymentUnit.getVnfc()) { boolean found = false; for (VNFCInstance vnfcInstance : virtualDeploymentUnit.getVnfc_instance()) { if (vnfComponent.getId().equals(vnfcInstance.getVnfComponent().getId())) { found = true; break; } } if (!found) { // new vnfComponent! componentToAdd = vnfComponent; vdu = virtualDeploymentUnit; break; } } } log.info("The component to add is: " + componentToAdd); if (checkQuota) { Map<String, VimInstance> vimInstanceMap = lifecycleOperationGranting .grantLifecycleOperation(virtualNetworkFunctionRecord); if (vimInstanceMap.size() == virtualNetworkFunctionRecord.getVdu().size()) { //TODO needs to be one? try { Future<String> future = resourceManagement.allocate(vdu, virtualNetworkFunctionRecord, componentToAdd, vimInstanceMap.get(vdu.getId()), userdata); log.debug("Added new component with id: " + future.get()); } catch (ExecutionException exe) { try { Throwable realException = exe.getCause(); if (realException instanceof VimException) throw (VimException) realException; if (realException instanceof VimDriverException) throw (VimDriverException) realException; throw exe; } catch (VimException e) { resourceManagement.release(vdu, e.getVnfcInstance()); virtualNetworkFunctionRecord.setStatus(Status.ACTIVE); saveVirtualNetworkFunctionRecord(); OrVnfmErrorMessage errorMessage = new OrVnfmErrorMessage(); errorMessage.setMessage("Error creating VM while scale out. " + e.getLocalizedMessage()); errorMessage.setVnfr(virtualNetworkFunctionRecord); errorMessage.setAction(Action.ERROR); vnfmManager.findAndSetNSRStatus(virtualNetworkFunctionRecord); return errorMessage; } catch (VimDriverException e) { virtualNetworkFunctionRecord.setStatus(Status.ACTIVE); saveVirtualNetworkFunctionRecord(); OrVnfmErrorMessage errorMessage = new OrVnfmErrorMessage(); errorMessage.setMessage("Error creating VM while scale out. " + e.getLocalizedMessage()); errorMessage.setVnfr(virtualNetworkFunctionRecord); errorMessage.setAction(Action.ERROR); vnfmManager.findAndSetNSRStatus(virtualNetworkFunctionRecord); return errorMessage; } } } else { log.error("Not enough resources for scale out."); log.error("VNFR " + virtualNetworkFunctionRecord.getName() + " stay in status ACTIVE."); virtualNetworkFunctionRecord.setStatus(Status.ACTIVE); OrVnfmErrorMessage errorMessage = new OrVnfmErrorMessage(); errorMessage.setMessage("Not enough resources for scale out."); errorMessage.setVnfr(virtualNetworkFunctionRecord); errorMessage.setAction(Action.ERROR); saveVirtualNetworkFunctionRecord(); vnfmManager.findAndSetNSRStatus(virtualNetworkFunctionRecord); return errorMessage; } } else { log.warn("Please consider turning the check quota (nfvo.quota.check in openbaton.properties) to true."); try { log.debug( "Added new component with id: " + resourceManagement .allocate(vdu, virtualNetworkFunctionRecord, componentToAdd, vnfPlacementManagement.choseRandom(vdu.getVimInstanceName()), userdata) .get()); } catch (VimDriverException e) { log.error(e.getLocalizedMessage()); virtualNetworkFunctionRecord.setStatus(Status.ACTIVE); OrVnfmErrorMessage errorMessage = new OrVnfmErrorMessage(); errorMessage .setMessage("Error creating VM while scale out. Please consider enabling checkQuota ;)"); errorMessage.setVnfr(virtualNetworkFunctionRecord); errorMessage.setAction(Action.ERROR); saveVirtualNetworkFunctionRecord(); vnfmManager.findAndSetNSRStatus(virtualNetworkFunctionRecord); return errorMessage; } catch (VimException e) { log.error(e.getLocalizedMessage()); if (e.getVnfcInstance() != null) resourceManagement.release(vdu, e.getVnfcInstance()); virtualNetworkFunctionRecord.setStatus(Status.ACTIVE); OrVnfmErrorMessage errorMessage = new OrVnfmErrorMessage(); errorMessage .setMessage("Error creating VM while scale out. Please consider enabling checkQuota ;)"); errorMessage.setVnfr(virtualNetworkFunctionRecord); errorMessage.setAction(Action.ERROR); saveVirtualNetworkFunctionRecord(); vnfmManager.findAndSetNSRStatus(virtualNetworkFunctionRecord); return errorMessage; } } log.trace("HB_VERSION == " + virtualNetworkFunctionRecord.getHb_version()); return new OrVnfmGenericMessage(virtualNetworkFunctionRecord, Action.SCALED); }
From source file:com.streamsets.pipeline.stage.processor.geolocation.GeolocationProcessor.java
@Override protected void process(Record record, SingleLaneBatchMaker batchMaker) throws StageException { try {// w w w .j av a 2 s .c om for (GeolocationFieldConfig config : configs) { Field field = record.get(config.inputFieldName); if (field == null) { throw new OnRecordErrorException(Errors.GEOIP_11, record.getHeader().getSourceId(), config.inputFieldName); } try { switch (config.targetType) { case COUNTRY_NAME: CountryResponse countryName = countries.get(field); record.set(config.outputFieldName, Field.create(countryName.getCountry().getName())); break; case COUNTRY_ISO_CODE: CountryResponse countryIso = countries.get(field); record.set(config.outputFieldName, Field.create(countryIso.getCountry().getIsoCode())); break; case CITY_NAME: CityResponse cityName = cities.get(field); record.set(config.outputFieldName, Field.create(cityName.getCity().getName())); break; case LATITUDE: CityResponse cityLat = cities.get(field); if (cityLat.getLocation() != null && cityLat.getLocation().getLatitude() != null) { record.set(config.outputFieldName, Field.create(cityLat.getLocation().getLatitude())); } break; case LONGITUDE: CityResponse cityLong = cities.get(field); if (cityLong.getLocation() != null && cityLong.getLocation().getLatitude() != null) { record.set(config.outputFieldName, Field.create(cityLong.getLocation().getLongitude())); } break; default: throw new IllegalStateException( Utils.format("Unknown configuration value: ", config.targetType)); } } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause == null) { cause = ex; } if (cause instanceof UnknownHostException || cause instanceof AddressNotFoundException) { throw new OnRecordErrorException(Errors.GEOIP_02, field.getValue(), cause); } Throwables.propagateIfInstanceOf(cause, OnRecordErrorException.class); Throwables.propagateIfInstanceOf(cause, GeoIp2Exception.class); Throwables.propagateIfInstanceOf(cause, IOException.class); Throwables.propagate(cause); } } } catch (GeoIp2Exception ex) { throw new StageException(Errors.GEOIP_03, ex); } catch (IOException ex) { throw new StageException(Errors.GEOIP_01, geoIP2DBFile, ex); } batchMaker.addRecord(record); }
From source file:com.pliu.azuremgmtsdk.BasicFilter.java
private AuthenticationResult getAccessTokenFromRefreshToken(String refreshToken) throws Throwable { AuthenticationContext context;// www.j a v a 2 s. c o m AuthenticationResult result = null; ExecutorService service = null; try { service = Executors.newFixedThreadPool(1); context = new AuthenticationContext(authority + userTenant + "/", true, service); Future<AuthenticationResult> future = context.acquireTokenByRefreshToken(refreshToken, new ClientCredential(clientId, clientSecret), null, null); result = future.get(); } catch (ExecutionException e) { throw e.getCause(); } finally { service.shutdown(); } if (result == null) { throw new ServiceUnavailableException("authentication result was null"); } return result; }
From source file:my.home.lehome.service.SendMsgIntentService.java
private void dispatchCommand(final Intent intent) { String cmd = intent.getStringExtra("cmdString"); String servelURL = intent.getStringExtra("serverUrl"); String deviceID = intent.getStringExtra("deviceID"); boolean local = intent.getBooleanExtra("local", false); Log.d(TAG, "dispatch cmd:" + cmd + " | servelURL:" + servelURL + " | deviceID:" + deviceID + " | local:" + local);/* w w w. j a v a 2 s . c om*/ final Context context = getApplicationContext(); if (local) { if (TextUtils.isEmpty(servelURL)) { saveAndNotify(intent, CommandRequest.getJsonStringResponse(400, context.getString(R.string.msg_local_saddress_not_set))); } } else { if (TextUtils.isEmpty(deviceID)) { saveAndNotify(intent, CommandRequest.getJsonStringResponse(400, context.getString(R.string.msg_no_deviceid))); } if (TextUtils.isEmpty(servelURL)) { saveAndNotify(intent, CommandRequest.getJsonStringResponse(400, context.getString(R.string.msg_saddress_not_set))); } } RequestFuture<String> future = RequestFuture.newFuture(); CommandRequest request = new CommandRequest(local ? Request.Method.POST : Request.Method.GET, // diff servelURL, cmd, future, future); mRequestQueue.add(request); try { String response = future.get(request.getTimeoutMs() + 10000, TimeUnit.MILLISECONDS); Log.d(TAG, "get cmd response:" + response); saveAndNotify(intent, CommandRequest.getJsonStringResponse(200, response)); } catch (ExecutionException e) { Throwable error = e.getCause(); Log.d(TAG, "get cmd error:" + error.toString()); String errorString = context.getString(R.string.error_unknown); int errorCode = 400; if (error instanceof ServerError) { errorString = context.getString(R.string.chat_error_conn); errorCode = 400; } else if (error instanceof TimeoutError) { errorString = context.getString(R.string.chat_error_http_error); errorCode = 400; } else if (error instanceof ParseError) { errorString = context.getString(R.string.chat_error_http_error); errorCode = 400; } else if (error instanceof NoConnectionError) { errorString = context.getString(R.string.chat_error_no_connection_error); errorCode = 400; } saveAndNotify(intent, CommandRequest.getJsonStringResponse(errorCode, errorString)); } catch (TimeoutException e) { saveAndNotify(intent, CommandRequest.getJsonStringResponse(400, context.getString(R.string.chat_error_http_error))); } catch (Exception e) { future.cancel(true); e.printStackTrace(); // saveAndNotify(intent, // CommandRequest.getJsonStringResponse( // 400, // context.getString(R.string.error_internal) // )); } }
From source file:com.pliu.azuremgmtsdk.BasicFilter.java
private AuthenticationResult getAccessToken(AuthorizationCode authorizationCode, String currentUri) throws Throwable { String authCode = authorizationCode.getValue(); ClientCredential credential = new ClientCredential(clientId, clientSecret); AuthenticationContext context;/* ww w . ja v a 2 s . c o m*/ AuthenticationResult result = null; ExecutorService service = null; try { service = Executors.newFixedThreadPool(1); context = new AuthenticationContext(authority + userTenant + "/", true, service); Future<AuthenticationResult> future = context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, apiEndpoint, null); result = future.get(); } catch (ExecutionException e) { throw e.getCause(); } finally { service.shutdown(); } if (result == null) { throw new ServiceUnavailableException("authentication result was null"); } return result; }
From source file:com.reactivetechnologies.platform.rest.WebbitRestServerBean.java
@Override public void run() { try {//from w ww . ja va 2 s.c o m server.start().get(); } catch (ExecutionException e) { throw new BeanInitializationException("[REST Listener] Server startup failed!", e.getCause()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new BeanInitializationException("[REST Listener] Server was interrupted while trying to start", e); } log.info("[REST Listener] Server started for POST/GET/DELETE on port- " + server.getPort()); }