List of usage examples for java.util.concurrent ExecutionException getCause
public synchronized Throwable getCause()
From source file:org.apache.solr.cloud.RecoveryStrategy.java
private void sendPrepRecoveryCmd(String leaderBaseUrl, String leaderCoreName, Slice slice) throws SolrServerException, IOException, InterruptedException, ExecutionException { WaitForState prepCmd = new WaitForState(); prepCmd.setCoreName(leaderCoreName); prepCmd.setNodeName(zkController.getNodeName()); prepCmd.setCoreNodeName(coreZkNodeName); prepCmd.setState(Replica.State.RECOVERING); prepCmd.setCheckLive(true);/*from www . j a v a 2 s. c om*/ prepCmd.setOnlyIfLeader(true); final Slice.State state = slice.getState(); if (state != Slice.State.CONSTRUCTION && state != Slice.State.RECOVERY && state != Slice.State.RECOVERY_FAILED) { prepCmd.setOnlyIfLeaderActive(true); } final int maxTries = 30; for (int numTries = 0; numTries < maxTries; numTries++) { try { sendPrepRecoveryCmd(leaderBaseUrl, prepCmd); break; } catch (ExecutionException e) { SolrServerException solrException = (SolrServerException) e.getCause(); if (solrException.getRootCause() instanceof SocketTimeoutException && numTries < maxTries) { LOG.warn("Socket timeout when send prep recovery cmd, retrying.. "); continue; } throw e; } } }
From source file:org.apache.hadoop.hdfs.qjournal.client.TestIPCLoggerChannel.java
/** * Test that, if the remote node gets unsynchronized (eg some edits were * missed or the node rebooted), the client stops sending edits until * the next roll. Test for HDFS-3726./*w w w . ja v a 2 s . c o m*/ */ @Test public void testStopSendingEditsWhenOutOfSync() throws Exception { Mockito.doThrow(new IOException("injected error")).when(mockProxy).journal(Mockito.<RequestInfo>any(), Mockito.eq(1L), Mockito.eq(1L), Mockito.eq(1), Mockito.same(FAKE_DATA)); try { ch.sendEdits(1L, 1L, 1, FAKE_DATA).get(); fail("Injected JOOSE did not cause sendEdits() to throw"); } catch (ExecutionException ee) { GenericTestUtils.assertExceptionContains("injected", ee); } Mockito.verify(mockProxy).journal(Mockito.<RequestInfo>any(), Mockito.eq(1L), Mockito.eq(1L), Mockito.eq(1), Mockito.same(FAKE_DATA)); assertTrue(ch.isOutOfSync()); try { ch.sendEdits(1L, 2L, 1, FAKE_DATA).get(); fail("sendEdits() should throw until next roll"); } catch (ExecutionException ee) { GenericTestUtils.assertExceptionContains("disabled until next roll", ee.getCause()); } // It should have failed without even sending the edits, since it was not sync. Mockito.verify(mockProxy, Mockito.never()).journal(Mockito.<RequestInfo>any(), Mockito.eq(1L), Mockito.eq(2L), Mockito.eq(1), Mockito.same(FAKE_DATA)); // It should have sent a heartbeat instead. Mockito.verify(mockProxy).heartbeat(Mockito.<RequestInfo>any()); // After a roll, sending new edits should not fail. ch.startLogSegment(3L, NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION).get(); assertFalse(ch.isOutOfSync()); ch.sendEdits(3L, 3L, 1, FAKE_DATA).get(); }
From source file:org.springframework.messaging.simp.stomp.DefaultStompSession.java
private void execute(Message<byte[]> message) { if (logger.isTraceEnabled()) { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); if (accessor != null) { logger.trace("Sending " + accessor.getDetailedLogMessage(message.getPayload())); }/*from w w w . j a v a 2s . c om*/ } TcpConnection<byte[]> conn = this.connection; Assert.state(conn != null, "Connection closed"); try { conn.send(message).get(); } catch (ExecutionException ex) { throw new MessageDeliveryException(message, ex.getCause()); } catch (Throwable ex) { throw new MessageDeliveryException(message, ex); } }
From source file:eu.esdihumboldt.hale.io.haleconnect.internal.HaleConnectServiceImpl.java
/** * @see eu.esdihumboldt.hale.io.haleconnect.HaleConnectService#uploadProjectFile(java.lang.String, * eu.esdihumboldt.hale.io.haleconnect.Owner, java.io.File, * eu.esdihumboldt.hale.common.core.io.ProgressIndicator) *//*from w ww . j a va 2s. c o m*/ @Override public boolean uploadProjectFile(String projectId, Owner owner, File file, ProgressIndicator progress) throws HaleConnectException { if (!this.isLoggedIn()) { throw new HaleConnectException("Not logged in"); } String apiKey = this.getSession().getToken(); SettableFuture<Boolean> future = SettableFuture.create(); try { FilesApi filesApi = ProjectStoreHelper.getFilesApi(this, apiKey); // POST /raw int totalWork = computeTotalWork(file); ApiCallback<Feedback> apiCallback = createUploadFileCallback(future, progress, file, totalWork); progress.begin("Uploading project archive", totalWork); filesApi.addFilesAsync(owner.getType().getJsonValue(), owner.getId(), projectId, file, apiCallback); return future.get(); } catch (com.haleconnect.api.projectstore.v1.ApiException e1) { throw new HaleConnectException(e1.getMessage(), e1, e1.getCode(), e1.getResponseHeaders()); } catch (ExecutionException e2) { Throwable t = e2.getCause(); if (t instanceof HaleConnectException) { throw (HaleConnectException) t; } else { throw new HaleConnectException(t.getMessage(), t); } } catch (InterruptedException e3) { throw new HaleConnectException(e3.getMessage(), e3); } }
From source file:voldemort.restclient.R2Store.java
public String getSerializerInfoXml() throws VoldemortException { RestRequestBuilder rb = null;//w ww . ja v a 2 s. co m try { String base64Key = new String(Base64.encodeBase64(getName().getBytes("UTF-8"))); rb = new RestRequestBuilder( new URI(this.restBootstrapURL + "/" + SCHEMATA_STORE_NAME + "/" + base64Key)); rb.setHeader("Accept", "binary"); rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS, String.valueOf(System.currentTimeMillis())); if (this.routingTypeCode != null) { rb.setHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE, this.routingTypeCode); } if (this.zoneId != INVALID_ZONE_ID) { rb.setHeader(RestMessageHeaders.X_VOLD_ZONE_ID, String.valueOf(this.zoneId)); } RestResponse response = fetchGetResponse(rb, FETCH_SCHEMA_TIMEOUT_MS); return response.getEntity().asString("UTF-8"); } catch (ExecutionException e) { if (e.getCause() instanceof RestException) { RestException exception = (RestException) e.getCause(); if (logger.isDebugEnabled()) { logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus()); } } else { throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e); } } catch (InterruptedException e) { if (logger.isDebugEnabled()) { logger.debug("Operation interrupted : " + e.getMessage(), e); } throw new VoldemortException("Operation interrupted exception: " + e.getMessage(), e); } catch (URISyntaxException e) { throw new VoldemortException("Illegal HTTP URL" + e.getMessage(), e); } catch (UnsupportedEncodingException e) { throw new VoldemortException("Unsupported Encoding exception while encoding the key" + e.getMessage(), e); } return null; }
From source file:voldemort.restclient.R2Store.java
@Override public List<Versioned<byte[]>> get(ByteArray key, byte[] transforms) throws VoldemortException { List<Versioned<byte[]>> resultList = new ArrayList<Versioned<byte[]>>(); String base64Key = RestUtils.encodeVoldemortKey(key.get()); RestRequestBuilder rb = null;/*from ww w . ja v a2 s . c o m*/ try { rb = new RestRequestBuilder(new URI(this.restBootstrapURL + "/" + getName() + "/" + base64Key)); String timeoutStr = Long .toString(this.config.getTimeoutConfig().getOperationTimeout(VoldemortOpCode.GET_OP_CODE)); rb.setHeader("Accept", MULTIPART_CONTENT_TYPE); RestResponse response = fetchGetResponse(rb, timeoutStr); final ByteString entity = response.getEntity(); if (entity != null) { resultList = parseGetResponse(entity); } else { if (logger.isDebugEnabled()) { logger.debug("Did not get any response!"); } } } catch (ExecutionException e) { if (e.getCause() instanceof RestException) { RestException exception = (RestException) e.getCause(); if (logger.isDebugEnabled()) { logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus()); } } else { throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e); } } catch (InterruptedException e) { if (logger.isDebugEnabled()) { logger.debug("Operation interrupted : " + e.getMessage(), e); } throw new VoldemortException("Operation interrupted exception: " + e.getMessage(), e); } catch (URISyntaxException e) { throw new VoldemortException("Illegal HTTP URL" + e.getMessage(), e); } return resultList; }
From source file:com.isencia.passerelle.runtime.test.FlowProcessingTest1.java
public final void testWaitUntilFinishedOfFlowWithError() throws Exception { FlowHandle flowHandle = repositoryService.commit("testWaitUntilFinishedOfFlowWithError", buildPreInitErrorFlow("testWaitUntilFinishedOfFlowWithError")); ProcessHandle procHandle = processingService.start(StartMode.RUN, flowHandle, null, null, null); try {//from www. j a v a2 s . c om procHandle = processingService.waitUntilFinished(procHandle, 1, TimeUnit.SECONDS); // ico a remote execution, we're not able (yet?) to transfer ExecutionExceptions, and we'll just see that the status is ERROR assertEquals("Process should have finished in ERROR", ProcessStatus.ERROR, procHandle.getExecutionStatus()); } catch (ExecutionException e) { // for local execution, an InitializationException will be so severe that the execution fails completely // TODO check how to implement this uniformly for remote executions as well assertTrue("Error cause should be an InitializationException", e.getCause() instanceof InitializationException); } }
From source file:voldemort.restclient.R2Store.java
@Override public List<Version> getVersions(ByteArray key) { List<Version> resultList = new ArrayList<Version>(); String base64Key = RestUtils.encodeVoldemortKey(key.get()); RestRequestBuilder rb = null;//from w w w .j a v a2s .c o m try { rb = new RestRequestBuilder(new URI(this.restBootstrapURL + "/" + getName() + "/" + base64Key)); String timeoutStr = Long.toString( this.config.getTimeoutConfig().getOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE)); rb.setHeader(RestMessageHeaders.X_VOLD_GET_VERSION, "true"); RestResponse response = fetchGetResponse(rb, timeoutStr); final ByteString entity = response.getEntity(); if (entity != null) { resultList = parseGetVersionResponse(entity); } else { if (logger.isDebugEnabled()) { logger.debug("Did not get any response!"); } } } catch (ExecutionException e) { if (e.getCause() instanceof RestException) { RestException exception = (RestException) e.getCause(); if (logger.isDebugEnabled()) { logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus()); } } else { throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e); } } catch (InterruptedException e) { if (logger.isDebugEnabled()) { logger.debug("Operation interrupted : " + e.getMessage(), e); } throw new VoldemortException("Operation interrupted exception: " + e.getMessage(), e); } catch (URISyntaxException e) { throw new VoldemortException("Illegal HTTP URL" + e.getMessage(), e); } return resultList; }
From source file:backtype.storm.localizer.Localizer.java
/** * This function either returns the blobs in the existing cache or if they don't exist in the * cache, it downloads them in parallel (up to SUPERVISOR_BLOBSTORE_DOWNLOAD_THREAD_COUNT) * and will block until all of them have been downloaded *//*w ww. ja v a 2s. c o m*/ public synchronized List<LocalizedResource> getBlobs(List<LocalResource> localResources, String user, String topo, File userFileDir) throws AuthorizationException, KeyNotFoundException, IOException { LocalizedResourceSet newSet = new LocalizedResourceSet(user); LocalizedResourceSet lrsrcSet = _userRsrc.putIfAbsent(user, newSet); if (lrsrcSet == null) { lrsrcSet = newSet; } ArrayList<LocalizedResource> results = new ArrayList<>(); ArrayList<Callable<LocalizedResource>> downloads = new ArrayList<>(); ClientBlobStore blobstore = null; try { blobstore = getClientBlobStore(); for (LocalResource localResource : localResources) { String key = localResource.getBlobName(); boolean uncompress = localResource.shouldUncompress(); LocalizedResource lrsrc = lrsrcSet.get(key, localResource.shouldUncompress()); boolean isUpdate = false; if ((lrsrc != null) && (lrsrc.isUncompressed() == localResource.shouldUncompress()) && (isLocalizedResourceDownloaded(lrsrc))) { if (isLocalizedResourceUpToDate(lrsrc, blobstore)) { LOG.debug("blob already exists: {}", key); lrsrc.addReference(topo); results.add(lrsrc); continue; } LOG.debug("blob exists but isn't up to date: {}", key); isUpdate = true; } // go off to blobstore and get it // assume dir passed in exists and has correct permission LOG.debug("fetching blob: {}", key); File downloadDir = getCacheDirForFiles(userFileDir); File localFile = new File(downloadDir, key); if (uncompress) { // for compressed file, download to archives dir downloadDir = getCacheDirForArchives(userFileDir); localFile = new File(downloadDir, key); } downloadDir.mkdir(); downloads.add(new DownloadBlob(this, _conf, key, localFile, user, uncompress, isUpdate)); } } finally { if (blobstore != null) { blobstore.shutdown(); } } try { List<Future<LocalizedResource>> futures = _execService.invokeAll(downloads); for (Future<LocalizedResource> futureRsrc : futures) { LocalizedResource lrsrc = futureRsrc.get(); lrsrc.addReference(topo); lrsrcSet.addResource(lrsrc.getKey(), lrsrc, lrsrc.isUncompressed()); results.add(lrsrc); } } catch (ExecutionException e) { if (e.getCause() instanceof AuthorizationException) throw (AuthorizationException) e.getCause(); else if (e.getCause() instanceof KeyNotFoundException) { throw (KeyNotFoundException) e.getCause(); } else { throw new IOException("Error getting blobs", e); } } catch (RejectedExecutionException re) { throw new IOException("RejectedExecutionException: ", re); } catch (InterruptedException ie) { throw new IOException("Interrupted Exception", ie); } return results; }
From source file:com.epam.reportportal.apache.http.impl.execchain.MainClientExec.java
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"); AuthState targetAuthState = context.getTargetAuthState(); if (targetAuthState == null) { targetAuthState = new AuthState(); context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState); }/*from w w w . j a va 2 s .co m*/ AuthState proxyAuthState = context.getProxyAuthState(); if (proxyAuthState == null) { proxyAuthState = new AuthState(); context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState); } if (request instanceof HttpEntityEnclosingRequest) { Proxies.enhanceEntity((HttpEntityEnclosingRequest) request); } Object userToken = context.getUserToken(); final ConnectionRequest connRequest = connManager.requestConnection(route, userToken); 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); } context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); if (config.isStaleConnectionCheckEnabled()) { // validate connection if (managedConn.isOpen()) { this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); managedConn.close(); } } } final ConnectionHolder connHolder = new ConnectionHolder(this.log, this.connManager, managedConn); try { if (execAware != null) { execAware.setCancellable(connHolder); } HttpResponse response; for (int execCount = 1;; execCount++) { if (execCount > 1 && !Proxies.isRepeatable(request)) { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity."); } if (execAware != null && execAware.isAborted()) { throw new RequestAbortedException("Request aborted"); } if (!managedConn.isOpen()) { this.log.debug("Opening connection " + route); try { establishRoute(proxyAuthState, managedConn, route, request, context); } catch (final TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } } final int timeout = config.getSocketTimeout(); if (timeout >= 0) { managedConn.setSocketTimeout(timeout); } if (execAware != null && execAware.isAborted()) { throw new RequestAbortedException("Request aborted"); } if (this.log.isDebugEnabled()) { this.log.debug("Executing request " + request.getRequestLine()); } if (!request.containsHeader(AUTH.WWW_AUTH_RESP)) { if (this.log.isDebugEnabled()) { this.log.debug("Target auth state: " + targetAuthState.getState()); } this.authenticator.generateAuthResponse(request, targetAuthState, context); } if (!request.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) { if (this.log.isDebugEnabled()) { this.log.debug("Proxy auth state: " + proxyAuthState.getState()); } this.authenticator.generateAuthResponse(request, proxyAuthState, context); } response = requestExecutor.execute(request, managedConn, 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); if (this.log.isDebugEnabled()) { final String s; if (duration > 0) { s = "for " + duration + " " + TimeUnit.MILLISECONDS; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } connHolder.setValidFor(duration, TimeUnit.MILLISECONDS); connHolder.markReusable(); } else { connHolder.markNonReusable(); } if (needAuthentication(targetAuthState, proxyAuthState, route, response, context)) { // Make sure the response body is fully consumed, if present final HttpEntity entity = response.getEntity(); if (connHolder.isReusable()) { EntityUtils.consume(entity); } else { managedConn.close(); if (proxyAuthState.getState() == AuthProtocolState.SUCCESS && proxyAuthState.getAuthScheme() != null && proxyAuthState.getAuthScheme().isConnectionBased()) { this.log.debug("Resetting proxy auth state"); proxyAuthState.reset(); } if (targetAuthState.getState() == AuthProtocolState.SUCCESS && targetAuthState.getAuthScheme() != null && targetAuthState.getAuthScheme().isConnectionBased()) { this.log.debug("Resetting target auth state"); targetAuthState.reset(); } } // discard previous auth headers final HttpRequest original = request.getOriginal(); if (!original.containsHeader(AUTH.WWW_AUTH_RESP)) { request.removeHeaders(AUTH.WWW_AUTH_RESP); } if (!original.containsHeader(AUTH.PROXY_AUTH_RESP)) { request.removeHeaders(AUTH.PROXY_AUTH_RESP); } } else { break; } } if (userToken == null) { userToken = userTokenHandler.getUserToken(context); context.setAttribute(HttpClientContext.USER_TOKEN, userToken); } if (userToken != null) { connHolder.setState(userToken); } // 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 connHolder.releaseConnection(); return Proxies.enhanceResponse(response, null); } else { return Proxies.enhanceResponse(response, connHolder); } } catch (final ConnectionShutdownException ex) { final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down"); ioex.initCause(ex); throw ioex; } catch (final HttpException ex) { connHolder.abortConnection(); throw ex; } catch (final IOException ex) { connHolder.abortConnection(); throw ex; } catch (final RuntimeException ex) { connHolder.abortConnection(); throw ex; } }