List of usage examples for java.util.concurrent ExecutionException getCause
public synchronized Throwable getCause()
From source file:com.dilmus.dilshad.scabi.core.async.DComputeAsyncRun.java
void get() { HttpResponse httpResponse = null;/*from w w w .j av a 2 s . co m*/ String result = null; if (m_futureHttpResponse != null) { try { httpResponse = DComputeNoBlock.get(m_futureHttpResponse); result = DComputeNoBlock.getResult(httpResponse); log.debug("get() result : {}", result); m_computeNB.decCountRequests(); synchronized (m_config) { m_config.setResult(m_SU, result); } m_futureHttpResponse = null; } catch (ExecutionException e) { if (e.getCause() != null) { if (e.getCause() instanceof ConnectException || e.getCause() instanceof ConnectionClosedException || e.getCause() instanceof IllegalStateException || e.getCause() instanceof SocketException || e.getCause() instanceof NoHttpResponseException) { log.debug("get() e.getCause() : {}", e.getCause().toString()); log.debug("get() Exception : {}", e.toString()); // computeNB is faulty only in the case of Network Exception/ConnectException m_computeNB.setFaulty(true); result = DMJson.error(DMUtil.clientErrMsg(e)); // m_isError is set only in the case of network exception // only in this case retry has to be attempted if maxRetry > 0 is set by User m_isError = true; m_computeNB.decCountRequests(); synchronized (m_config) { m_config.appendResult(m_SU, result); } m_futureHttpResponse = null; } else { log.debug("get() ExecutionException : {}", e.toString()); // m_computeNB is faulty only in the case of ClientProtocolException/NetworkException which // is already handled above // // // m_computeNB.setFaulty(true); log.debug("run() m_SU : {}", m_SU); String errorJson = DMJson.error(DMUtil.clientErrMsg(e)); m_computeNB.decCountRequests(); synchronized (m_config) { m_config.appendResult(m_SU, errorJson); } m_futureHttpResponse = null; } // End if } else { log.debug("get() ExecutionException : {}", e.toString()); // m_computeNB is faulty only in the case of ClientProtocolException/NetworkException which // is already handled above // // // m_computeNB.setFaulty(true); log.debug("run() m_SU : {}", m_SU); String errorJson = DMJson.error(DMUtil.clientErrMsg(e)); m_computeNB.decCountRequests(); synchronized (m_config) { m_config.appendResult(m_SU, errorJson); } m_futureHttpResponse = null; } // End if } catch (InterruptedException | TimeoutException | ParseException | IOException e) { //e.printStackTrace(); log.debug("get() Exception : {}", e.toString()); // m_computeNB is faulty only in the case of ClientProtocolException/NetworkException which // is already handled above // // // m_computeNB.setFaulty(true); log.debug("run() m_SU : {}", m_SU); result = DMJson.error(DMUtil.clientErrMsg(e)); m_computeNB.decCountRequests(); synchronized (m_config) { m_config.appendResult(m_SU, result); } m_futureHttpResponse = null; } // try-catch } else { //log.debug("get() Inside else block (null == futureHttpResponse)"); result = DMJson.error( "DComputeAsyncRun:get() Client Side Issue : get() crun futureHttpResponse is null. Split no. : " + m_SU); m_computeNB.decCountRequests(); synchronized (m_config) { //if (false == config.isResultSet(crun.getSU())) m_config.appendResult(m_SU, result); } // if futureHttpResponse is null, exception should have been caught in crun.run() above // TODO check if setError() on crun here is needed to enable retry for this crun } // End if m_isDone = true; m_isRetrySubmitted = false; if (false == m_isRunOnce) { m_isRunOnce = true; } }
From source file:at.itbh.bev.rest.client.BevRestClient.java
/** * Query the ReST endpoint using the command line arguments * /*w ww . jav a 2 s .c o m*/ * @param args * the command line arguments */ public void query(String[] args) { BevQueryExecutor executor = null; ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); int threadPoolSize = 1; if (line.hasOption("t")) { threadPoolSize = Integer.parseInt(line.getOptionValue("t")); } String postalCode = null; String place = null; String addressLine = null; String houseId = null; String radius = null; String longitude = null; String latitude = null; String separator = ";"; boolean enforceUnique = false; if (line.hasOption("z")) { postalCode = line.getOptionValue("z"); } if (line.hasOption("p")) { place = line.getOptionValue("p"); } if (line.hasOption("a")) { addressLine = line.getOptionValue("a"); } if (line.hasOption("i")) { houseId = line.getOptionValue("i"); } if (line.hasOption("radius")) { radius = line.getOptionValue("radius"); } if (line.hasOption("longitude")) { longitude = line.getOptionValue("longitude"); } if (line.hasOption("latitude")) { latitude = line.getOptionValue("latitude"); } if (line.hasOption("s")) { separator = line.getOptionValue("s"); } if (line.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar BevRestClient.jar", options, true); System.exit(0); } if (line.hasOption("u")) { enforceUnique = true; } if (line.hasOption("disable-certificate-validation")) { clientBuilder.disableTrustManager(); } if (!line.hasOption("proxy-port") && line.hasOption("proxy-host")) { throw new ParseException( "The option --proxy-host is only allowed in combination with the option --proxy-port."); } if (line.hasOption("proxy-port") && !line.hasOption("proxy-host")) { throw new ParseException( "The option --proxy-port is only allowed in combination with the option --proxy-host."); } if (line.hasOption("proxy-host") && line.hasOption("proxy-port")) { clientBuilder.defaultProxy(line.getOptionValue("proxy-host"), Integer.parseInt(line.getOptionValue("proxy-port"))); } OutputStreamWriter output; if (line.hasOption("o")) { output = new OutputStreamWriter(new FileOutputStream(line.getOptionValue("o"))); } else { output = new OutputStreamWriter(System.out); } // avoid concurrent access exceptions in the Apache http client clientBuilder.connectionPoolSize(threadPoolSize); executor = new BevQueryExecutor(clientBuilder.build(), line.getOptionValue("r"), threadPoolSize); CsvPreference csvPreference = new CsvPreference.Builder('"', Objects.toString(line.getOptionValue("s"), ";").toCharArray()[0], System.getProperty("line.separator")).build(); csvWriter = new CsvMapWriter(output, csvPreference, true); if (line.hasOption("b")) { ICsvMapReader mapReader = null; try { FileReader fileReader = new FileReader(line.getOptionValue("b")); mapReader = new CsvMapReader(fileReader, csvPreference); // calculate the output header (field names) final String[] header = mapReader.getHeader(true); ArrayList<String> tempFields = new ArrayList<>(Arrays.asList(defaultFieldNames)); for (int i = 0; i < header.length; i++) { if (!tempFields.contains(header[i])) { tempFields.add(header[i]); } } fieldNames = tempFields.toArray(new String[] {}); Map<String, String> inputData; List<Future<List<BevQueryResult>>> queryResults = new ArrayList<>(); while ((inputData = mapReader.read(header)) != null) { queryResults .add(executor.query(inputData.get(INPUT_POSTAL_CODE), inputData.get(INPUT_PLACE), inputData.get(INPUT_ADDRESS_LINE), inputData.get(INPUT_HOUSE_ID), inputData.get(INPUT_LONGITUDE), inputData.get(INPUT_LATITUDE), inputData.get(INPUT_RADIUS), inputData.get(INPUT_ENFORCE_UNIQUE) == null ? false : Boolean.parseBoolean(inputData.get(INPUT_ENFORCE_UNIQUE)), inputData)); } csvWriter.writeHeader(fieldNames); for (Future<List<BevQueryResult>> queryResult : queryResults) { List<BevQueryResult> results = queryResult.get(); outputResults(separator, results); } } finally { if (mapReader != null) { mapReader.close(); } } } else { fieldNames = defaultFieldNames; Map<String, String> inputData = new HashMap<String, String>(); Future<List<BevQueryResult>> queryResult = executor.query(postalCode, place, addressLine, houseId, longitude, latitude, radius, enforceUnique, inputData); try { List<BevQueryResult> results = queryResult.get(); if (enforceUnique && results.size() == 1) { if (!results.get(0).getFoundMatch()) throw new Exception("No unique result found."); } outputResults(separator, results); } catch (ExecutionException e) { throw e.getCause(); } } } catch (ParseException exp) { System.out.println(exp.getMessage()); System.out.println(); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar BevRestClient.jar", options, true); System.exit(-2); } catch (BevRestException e) { System.err.println(e.toString()); System.exit(e.getErrorCode()); } catch (JsonProcessingException e) { System.err.println(e.toString()); System.exit(-3); } catch (IOException e) { System.err.println(e.toString()); System.exit(-4); } catch (Throwable t) { System.err.println(t.toString()); t.printStackTrace(); System.exit(-1); } finally { if (csvWriter != null) { try { csvWriter.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } if (executor != null) { executor.dispose(); } } }
From source file:com.cloudant.sync.replication.PullStrategy.java
/** * Handle exceptions in separate run() method to allow replicate() to * just return when cancel is set to true rather than having to keep * track of whether we terminated via an error in replicate(). *//*from www . ja va 2s . c o m*/ @Override public void run() { if (this.state != null && this.state.cancel) { // we were already cancelled, don't run, but still post completion this.state.documentCounter = 0; this.state.batchCounter = 0; runComplete(null); return; } // reset internal state this.state = new State(); ErrorInfo errorInfo = null; try { this.useBulkGet = sourceDb.isBulkSupported(); replicate(); } catch (ExecutionException ex) { logger.log(Level.SEVERE, String.format("Batch %s ended with error:", this.state.batchCounter), ex); errorInfo = new ErrorInfo(ex.getCause()); } catch (Throwable e) { logger.log(Level.SEVERE, String.format("Batch %s ended with error:", this.state.batchCounter), e); errorInfo = new ErrorInfo(e); } runComplete(errorInfo); }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void responseReceiver_handleDelivery_onEncodingException_exception() throws EncodingException, IOException, InterruptedException, ExecutionException, TimeoutException { ResponseReceiverImpl receiver = new ResponseReceiverImpl(serializer, new Validator() { }, 1, TimeUnit.MINUTES);// ww w .j a v a2 s . c om String correlationId = "987654321"; CompletableFuture<Res> answer = receiver.put(correlationId, Res.class); assertFalse(answer.isDone()); assertFalse(answer.isCompletedExceptionally()); receiver.handleDelivery(correlationId, new byte[] {}); assertTrue(answer.isDone()); assertTrue(answer.isCompletedExceptionally()); exception.expect(ExecutionException.class); try { answer.get(); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof EncodingException); assertEquals("failed to decode JSON", ex.getCause().getMessage()); throw ex; } }
From source file:org.apache.axis2.jaxws.client.async.AsyncResponse.java
protected void onComplete(MessageContext mc) { if (log.isDebugEnabled()) { log.debug("AsyncResponse received a MessageContext."); }//from w ww .ja va2 s . co m // A new message context invalidates the cached object retrieved // during the last get() if (response != mc) { cachedObject = null; cacheValid = false; } response = mc; response.setEndpointDescription(endpointDescription); // Check for cached attachment file(s) if attachments exist. if (response.getAxisMessageContext().getAttachmentMap() != null) { AttachmentUtils.findCachedAttachment(response.getAxisMessageContext().getAttachmentMap()); } // Process the response as soon as it is available. This means making sure that // no content is left unread in the response stream. Leaving content there could // result in an error if the runtime is greedy about cleaning up. try { responseObject = processResponse(); } catch (ExecutionException e) { savedException = e; if (log.isDebugEnabled()) { log.debug("An error occurred while processing the response: " + e.getCause()); } latch.countDown(); } // Countdown so that the Future object will know that procesing is complete. latch.countDown(); if (log.isDebugEnabled()) { log.debug("New latch count = [" + latch.getCount() + "]"); } }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void responseReceiver_put_createsFuture_andCleansUpExpires() throws InterruptedException, ExecutionException, TimeoutException { ResponseReceiver receiver = new ResponseReceiverImpl(serializer, new Validator() { }, 100, TimeUnit.MILLISECONDS); CompletableFuture<Res> actual = receiver.put("987654321", Res.class); assertFalse(actual.isDone());//from www . j a v a 2 s. c o m assertFalse(actual.isCompletedExceptionally()); // wait for expiry timeout Thread.sleep(150); // trigger cache operations (to evict the record) for (int i = 0; i < 1000; i++) { receiver.put(UUID.randomUUID().toString(), Res.class); } exception.expect(ExecutionException.class); try { actual.get(); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof TimeoutException); assertEquals( "Request io.ventu.rpc.amqp.AmqpInvokerimplTest$Res with correlationId 987654321 has expired.", ex.getCause().getMessage()); throw ex; } }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void responseReceiver_handleDelivery_onEncodingException_withErrorField_APIException() throws EncodingException, IOException, InterruptedException, ExecutionException, TimeoutException { ResponseReceiverImpl receiver = new ResponseReceiverImpl(serializer, new Validator() { }, 1, TimeUnit.MINUTES);/* w ww . j a v a2 s . c o m*/ String correlationId = "987654321"; CompletableFuture<Res> answer = receiver.put(correlationId, Res.class); assertFalse(answer.isDone()); assertFalse(answer.isCompletedExceptionally()); Map<String, Object> res = Maps.newHashMap(); res.put("error", Integer.valueOf(371)); receiver.handleDelivery(correlationId, serializer.encode(res)); assertTrue(answer.isDone()); assertTrue(answer.isCompletedExceptionally()); exception.expect(ExecutionException.class); try { answer.get(); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof ApiException); assertEquals("371", ex.getCause().getMessage()); throw ex; } }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void responseReceiver_handleDelivery_onEncodingException_MapWithNoError_exception() throws EncodingException, IOException, InterruptedException, ExecutionException, TimeoutException { ResponseReceiverImpl receiver = new ResponseReceiverImpl(serializer, new Validator() { }, 1, TimeUnit.MINUTES);/*from w w w .ja va 2s .c o m*/ String correlationId = "987654321"; CompletableFuture<Res> answer = receiver.put(correlationId, Res.class); assertFalse(answer.isDone()); assertFalse(answer.isCompletedExceptionally()); Map<String, Object> res = Maps.newHashMap(); res.put("value", "notAnInt"); receiver.handleDelivery(correlationId, serializer.encode(res)); assertTrue(answer.isDone()); assertTrue(answer.isCompletedExceptionally()); exception.expect(ExecutionException.class); try { answer.get(); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof EncodingException); assertEquals("failed to decode JSON", ex.getCause().getMessage()); throw ex; } }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void closingInvoker_onIOException_exception() throws IOException, TimeoutException, ExecutionException, InterruptedException { String instanceId = "123456789"; Channel channel = mock(Channel.class); doThrow(new IOException("boom")).when(channel).close(); ResponseReceiver receiver = mock(ResponseReceiver.class); ChannelProvider channelProvider = mock(ChannelProvider.class); doReturn(channel).when(channelProvider).provide(instanceId, receiver); RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver); CompletableFuture<Void> actual = invoker.close(); verify(channel).close();//from w w w. j a va2s. c om verifyNoMoreInteractions(channel); assertTrue(actual.isDone()); assertTrue(actual.isCompletedExceptionally()); exception.expect(ExecutionException.class); try { actual.get(); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof IOException); throw ex; } }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void responseReceiver_handleDelivery_onAPIException_exception() throws EncodingException, IOException, InterruptedException, ExecutionException { Validator validator = new Validator() { @Override/*from w w w . j a v a 2s.c om*/ public <T> void validate(T value) throws ApiException, IllegalArgumentException { throw new ApiException("boom"); } }; ResponseReceiverImpl receiver = new ResponseReceiverImpl(serializer, validator, 1, TimeUnit.MINUTES); String correlationId = "987654321"; CompletableFuture<Res> answer = receiver.put(correlationId, Res.class); assertFalse(answer.isDone()); assertFalse(answer.isCompletedExceptionally()); receiver.handleDelivery(correlationId, serializer.encode(Maps.newHashMap())); assertTrue(answer.isDone()); assertTrue(answer.isCompletedExceptionally()); exception.expect(ExecutionException.class); try { answer.get(); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof ApiException); assertEquals("boom", ex.getCause().getMessage()); throw ex; } }