List of usage examples for java.util.concurrent CompletableFuture completeExceptionally
public boolean completeExceptionally(Throwable ex)
From source file:org.jaqpot.core.service.client.jpdi.JPDIClientImpl.java
@Override public Future<Model> train(Dataset dataset, Algorithm algorithm, Map<String, Object> parameters, String predictionFeature, MetaInfo modelMeta, String taskId) { CompletableFuture<Model> futureModel = new CompletableFuture<>(); TrainingRequest trainingRequest = new TrainingRequest(); trainingRequest.setDataset(dataset); trainingRequest.setParameters(parameters); trainingRequest.setPredictionFeature(predictionFeature); // String trainingRequestString = serializer.write(trainingRequest); final HttpPost request = new HttpPost(algorithm.getTrainingService()); PipedOutputStream out = new PipedOutputStream(); PipedInputStream in;/* w w w.j a v a 2 s . c o m*/ try { in = new PipedInputStream(out); } catch (IOException ex) { futureModel.completeExceptionally(ex); return futureModel; } InputStreamEntity entity = new InputStreamEntity(in, ContentType.APPLICATION_JSON); entity.setChunked(true); request.setEntity(entity); request.addHeader("Accept", "application/json"); Future futureResponse = client.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { futureMap.remove(taskId); int status = response.getStatusLine().getStatusCode(); try { InputStream responseStream = response.getEntity().getContent(); switch (status) { case 200: case 201: TrainingResponse trainingResponse = serializer.parse(responseStream, TrainingResponse.class); Model model = new Model(); model.setId(randomStringGenerator.nextString(20)); model.setActualModel(trainingResponse.getRawModel()); model.setPmmlModel(trainingResponse.getPmmlModel()); model.setAdditionalInfo(trainingResponse.getAdditionalInfo()); model.setAlgorithm(algorithm); model.setParameters(parameters); model.setDatasetUri(dataset != null ? dataset.getDatasetURI() : null); //Check if independedFeatures of model exist in dataset List<String> filteredIndependedFeatures = new ArrayList<String>(); if (dataset != null && dataset.getFeatures() != null && trainingResponse.getIndependentFeatures() != null) for (String feature : trainingResponse.getIndependentFeatures()) { for (FeatureInfo featureInfo : dataset.getFeatures()) { if (feature.equals(featureInfo.getURI())) filteredIndependedFeatures.add(feature); } } model.setIndependentFeatures(filteredIndependedFeatures); model.setDependentFeatures(Arrays.asList(predictionFeature)); model.setMeta(modelMeta); List<String> predictedFeatures = new ArrayList<>(); for (String featureTitle : trainingResponse.getPredictedFeatures()) { Feature predictionFeatureResource = featureHandler.findByTitleAndSource(featureTitle, "algorithm/" + algorithm.getId()); if (predictionFeatureResource == null) { // Create the prediction features (POST /feature) String predFeatID = randomStringGenerator.nextString(12); predictionFeatureResource = new Feature(); predictionFeatureResource.setId(predFeatID); predictionFeatureResource.setPredictorFor(predictionFeature); predictionFeatureResource.setMeta(MetaInfoBuilder.builder() .addSources( /*messageBody.get("base_uri") + */"algorithm/" + algorithm.getId()) .addComments("Feature created to hold predictions by algorithm with ID " + algorithm.getId()) .addTitles(featureTitle).addSeeAlso(predictionFeature) .addCreators(algorithm.getMeta().getCreators()).build()); /* Create feature */ featureHandler.create(predictionFeatureResource); } predictedFeatures.add(baseURI + "feature/" + predictionFeatureResource.getId()); } model.setPredictedFeatures(predictedFeatures); futureModel.complete(model); break; case 400: String message = new BufferedReader(new InputStreamReader(responseStream)).lines() .collect(Collectors.joining("\n")); futureModel.completeExceptionally(new BadRequestException(message)); break; case 500: message = new BufferedReader(new InputStreamReader(responseStream)).lines() .collect(Collectors.joining("\n")); futureModel.completeExceptionally(new InternalServerErrorException(message)); break; default: message = new BufferedReader(new InputStreamReader(responseStream)).lines() .collect(Collectors.joining("\n")); futureModel.completeExceptionally(new InternalServerErrorException(message)); } } catch (IOException | UnsupportedOperationException ex) { futureModel.completeExceptionally(ex); } } @Override public void failed(final Exception ex) { futureMap.remove(taskId); futureModel.completeExceptionally(ex); } @Override public void cancelled() { futureMap.remove(taskId); futureModel.cancel(true); } }); serializer.write(trainingRequest, out); try { out.close(); } catch (IOException ex) { futureModel.completeExceptionally(ex); } futureMap.put(taskId, futureResponse); return futureModel; }
From source file:com.yahoo.pulsar.broker.namespace.NamespaceService.java
/** * Main internal method to lookup and setup ownership of service unit to a broker * * @param bundle//w ww .j a v a2s.c om * @param authoritative * @param readOnly * @return * @throws PulsarServerException */ private CompletableFuture<LookupResult> findBrokerServiceUrl(NamespaceBundle bundle, boolean authoritative, boolean readOnly) { if (LOG.isDebugEnabled()) { LOG.debug("findBrokerServiceUrl: {} - read-only: {}", bundle, readOnly); } CompletableFuture<LookupResult> future = new CompletableFuture<>(); // First check if we or someone else already owns the bundle ownershipCache.getOwnerAsync(bundle).thenAccept(nsData -> { if (!nsData.isPresent()) { // No one owns this bundle if (readOnly) { // Do not attempt to acquire ownership future.completeExceptionally(new IllegalStateException( String.format("Can't find owner of ServiceUnit: %s", bundle))); } else { // Now, no one owns the namespace yet. Hence, we will try to dynamically assign it pulsar.getExecutor().execute(() -> { searchForCandidateBroker(bundle, future, authoritative); }); } } else if (nsData.get().isDisabled()) { future.completeExceptionally( new IllegalStateException(String.format("Namespace bundle %s is being unloaded", bundle))); } else { if (LOG.isDebugEnabled()) { LOG.debug("Namespace bundle {} already owned by {} ", bundle, nsData); } future.complete(new LookupResult(nsData.get())); } }).exceptionally(exception -> { LOG.warn("Failed to check owner for bundle {}: {}", bundle, exception.getMessage(), exception); future.completeExceptionally(exception); return null; }); return future; }
From source file:com.ikanow.aleph2.analytics.storm.utils.StormControllerUtil.java
/** * Checks the jar cache to see if an entry already exists for this list of jars, * returns the path of that entry if it does exist, otherwise creates the jar, adds * the path to the cache and returns it. * //from w ww. ja va 2 s. co m * @param jars_to_merge * @return * @throws Exception */ public static synchronized CompletableFuture<String> buildOrReturnCachedStormTopologyJar( final Collection<String> jars_to_merge, final String cached_jar_dir) { CompletableFuture<String> future = new CompletableFuture<String>(); final String hashed_jar_name = JarBuilderUtil.getHashedJarName(jars_to_merge, cached_jar_dir); //1. Check cache for this jar via hash of jar names if (storm_topology_jars_cache.containsKey(hashed_jar_name)) { //if exists: //2. validate jars has not been updated Date most_recent_update = JarBuilderUtil.getMostRecentlyUpdatedFile(jars_to_merge); //if the cache is more recent than any of the files, we assume nothing has been updated if (storm_topology_jars_cache.get(hashed_jar_name).getTime() > most_recent_update.getTime()) { //RETURN return cached jar file path _logger.debug("Returning a cached copy of the jar"); //update the cache copy to set its modified time to now so we don't clean it up JarBuilderUtil.updateJarModifiedTime(hashed_jar_name); future.complete(hashed_jar_name); return future; } else { //delete cache copy _logger.debug("Removing an expired cached copy of the jar"); removeCachedJar(hashed_jar_name); } } //if we fall through //3. create jar _logger.debug("Fell through or cache copy is old, have to create a new version"); if (buildStormTopologyJar(jars_to_merge, hashed_jar_name)) { //4. add jar to cache w/ current/newest file timestamp storm_topology_jars_cache.put(hashed_jar_name, new Date()); //RETURN return new jar file path future.complete(hashed_jar_name); } else { //had an error creating jar, throw an exception? future.completeExceptionally(new Exception("Error trying to create storm jar, see logs")); } return future; }
From source file:com.yahoo.pulsar.broker.service.ServerCnx.java
@Override protected void handleCloseConsumer(CommandCloseConsumer closeConsumer) { checkArgument(state == State.Connected); log.info("[{}] Closing consumer: {}", remoteAddress, closeConsumer.getConsumerId()); long requestId = closeConsumer.getRequestId(); long consumerId = closeConsumer.getConsumerId(); CompletableFuture<Consumer> consumerFuture = consumers.get(consumerId); if (consumerFuture == null) { log.warn("[{}] Consumer was not registered on the connection: {}", consumerId, remoteAddress); ctx.writeAndFlush(Commands.newError(requestId, ServerError.MetadataError, "Consumer not found")); return;//from w w w .j a va 2s . c o m } if (!consumerFuture.isDone() && consumerFuture .completeExceptionally(new IllegalStateException("Closed consumer before creation was complete"))) { // We have received a request to close the consumer before it was actually completed, we have marked the // consumer future as failed and we can tell the client the close operation was successful. When the actual // create operation will complete, the new consumer will be discarded. log.info("[{}] Closed consumer {} before its creation was completed", remoteAddress, consumerId); ctx.writeAndFlush(Commands.newSuccess(requestId)); return; } if (consumerFuture.isCompletedExceptionally()) { log.info("[{}] Closed consumer {} that already failed to be created", remoteAddress, consumerId); ctx.writeAndFlush(Commands.newSuccess(requestId)); return; } // Proceed with normal consumer close Consumer consumer = consumerFuture.getNow(null); try { consumer.close(); consumers.remove(consumerId, consumerFuture); ctx.writeAndFlush(Commands.newSuccess(requestId)); log.info("[{}] Closed consumer {}", remoteAddress, consumer); } catch (BrokerServiceException e) { log.warn("[{]] Error closing consumer: ", remoteAddress, consumer, e); ctx.writeAndFlush( Commands.newError(requestId, BrokerServiceException.getClientErrorCode(e), e.getMessage())); } }
From source file:io.pravega.segmentstore.server.reading.StorageReaderTests.java
/** * Tests the ability to queue dependent reads (subsequent reads that only want to read a part of a previous read). * Test this both with successful and failed reads. *///w ww. ja va 2s . co m @Test public void testDependents() { final Duration waitTimeout = Duration.ofSeconds(5); TestStorage storage = new TestStorage(); CompletableFuture<Integer> signal = new CompletableFuture<>(); AtomicBoolean wasReadInvoked = new AtomicBoolean(); storage.readImplementation = () -> { if (wasReadInvoked.getAndSet(true)) { Assert.fail( "Read was invoked multiple times, which is a likely indicator that the requests were not chained."); } return signal; }; @Cleanup StorageReader reader = new StorageReader(SEGMENT_METADATA, storage, executorService()); // Create some reads. CompletableFuture<StorageReader.Result> c1 = new CompletableFuture<>(); CompletableFuture<StorageReader.Result> c2 = new CompletableFuture<>(); reader.execute(new StorageReader.Request(0, 100, c1::complete, c1::completeExceptionally, TIMEOUT)); reader.execute(new StorageReader.Request(50, 100, c2::complete, c2::completeExceptionally, TIMEOUT)); Assert.assertFalse("One or more of the reads has completed prematurely.", c1.isDone() || c2.isDone()); signal.completeExceptionally(new IntentionalException()); AssertExtensions.assertThrows("The first read was not failed with the correct exception.", () -> c1.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS), ex -> ex instanceof IntentionalException); AssertExtensions.assertThrows("The second read was not failed with the correct exception.", () -> c2.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS), ex -> ex instanceof IntentionalException); }
From source file:com.heliosdecompiler.helios.gui.view.editors.DisassemblerView.java
@Override public CompletableFuture<byte[]> save(Node node) { if (!(node instanceof CodeArea)) { return CompletableFuture.completedFuture(new byte[0]); }// ww w . j a v a 2 s .c om String assembledCode = ((CodeArea) node).getText(); CompletableFuture<byte[]> future = new CompletableFuture<>(); backgroundTaskHelper.submit(new BackgroundTask( Message.TASK_ASSEMBLE_FILE.format(node.getProperties().get("path").toString()), true, () -> { if (controller instanceof KrakatauDisassemblerController) { KrakatauAssemblerSettings settings = new KrakatauAssemblerSettings(); settings.setPythonExecutable(new File(configuration.getString(Settings.PYTHON2_KEY))); settings.setProcessCreator(processController::launchProcess); try { TransformationResult<byte[]> result = StandardTransformers.Assemblers.KRAKATAU .assemble(assembledCode, settings); if (result.getTransformationData().size() == 1) { future.complete(result.getTransformationData().values().iterator().next()); } else { future.completeExceptionally(new KrakatauException(KrakatauException.Reason.UNKNOWN, result.getStdout(), result.getStderr())); } } catch (TransformationException e) { future.completeExceptionally(e); } } else { future.complete(new byte[0]); } })); return future; }
From source file:com.yahoo.pulsar.broker.service.ServerCnx.java
@Override protected void handleCloseProducer(CommandCloseProducer closeProducer) { checkArgument(state == State.Connected); final long producerId = closeProducer.getProducerId(); final long requestId = closeProducer.getRequestId(); CompletableFuture<Producer> producerFuture = producers.get(producerId); if (producerFuture == null) { log.warn("[{}] Producer {} was not registered on the connection", remoteAddress, producerId); ctx.writeAndFlush(Commands.newError(requestId, ServerError.UnknownError, "Producer was not registered on the connection")); return;// w w w. j ava 2 s . c om } if (!producerFuture.isDone() && producerFuture .completeExceptionally(new IllegalStateException("Closed producer before creation was complete"))) { // We have received a request to close the producer before it was actually completed, we have marked the // producer future as failed and we can tell the client the close operation was successful. When the actual // create operation will complete, the new producer will be discarded. log.info("[{}] Closed producer {} before its creation was completed", remoteAddress, producerId); ctx.writeAndFlush(Commands.newSuccess(requestId)); return; } else if (producerFuture.isCompletedExceptionally()) { log.info("[{}] Closed producer {} that already failed to be created", remoteAddress, producerId); ctx.writeAndFlush(Commands.newSuccess(requestId)); return; } // Proceed with normal close, the producer Producer producer = producerFuture.getNow(null); log.info("[{}][{}] Closing producer on cnx {}", producer.getTopic(), producer.getProducerName(), remoteAddress); producer.close().thenAccept(v -> { log.info("[{}][{}] Closed producer on cnx {}", producer.getTopic(), producer.getProducerName(), remoteAddress); ctx.writeAndFlush(Commands.newSuccess(requestId)); producers.remove(producerId, producerFuture); }); }
From source file:com.vmware.loginsightapi.LogInsightClient.java
/** * Ingest messages to loginsight/* w w w.java2 s .co m*/ * * @param messages * IngestionRequest object with list of messages * @return IngestionResponse CompletableFuture object * @see IngestionRequest * @see IngestionResponse */ public CompletableFuture<IngestionResponse> ingest(IngestionRequest messages) { HttpPost httpPost = null; CompletableFuture<IngestionResponse> completableFuture = new CompletableFuture<IngestionResponse>(); try { httpPost = getIngestionHttpRequest(messages); logger.info("Sending : " + messages.toJson()); asyncHttpClient.execute(httpPost, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse httpResponse) { try { String responseString = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); logger.warn("Response: " + responseString); completableFuture.complete(IngestionResponse.fromJsonString(responseString)); } catch (IOException e) { e.printStackTrace(); completableFuture.completeExceptionally( new LogInsightApiException("Unable to process the query response", e)); } } @Override public void failed(Exception ex) { completableFuture.completeExceptionally(new LogInsightApiException("Ingestion failed", ex)); } @Override public void cancelled() { completableFuture.completeExceptionally(new LogInsightApiException("Ingestion cancelled")); } }); } catch (Exception e) { completableFuture.completeExceptionally(new LogInsightApiException("Ingestion failed", e)); } return completableFuture; }
From source file:com.vmware.loginsightapi.LogInsightClient.java
/** * Performs aggregate query. Accepts callback * //from w w w . java 2 s .c o m * @param apiUrl * relative url of the API * @return AggregateResponse CompletableFuture * */ public CompletableFuture<AggregateResponse> aggregateQuery(String apiUrl) { HttpGet request = null; CompletableFuture<AggregateResponse> completableFuture = new CompletableFuture<AggregateResponse>(); try { request = getHttpRequest(apiUrl, true); logger.debug("Querying " + aggregateQueryUrl() + apiUrl); asyncHttpClient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse httpResponse) { try { String responseString = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); logger.warn("Response: " + responseString); completableFuture.complete(AggregateResponse.fromJsonString(responseString)); } catch (IOException e) { e.printStackTrace(); completableFuture.completeExceptionally( new LogInsightApiException("Unable to process the query response", e)); } } @Override public void failed(Exception ex) { completableFuture.completeExceptionally(new LogInsightApiException("Failed message Query", ex)); } @Override public void cancelled() { completableFuture.completeExceptionally(new LogInsightApiException("Cancelled message Query")); } }); } catch (Exception ie) { completableFuture.completeExceptionally(new LogInsightApiException("Message query failed", ie)); } return completableFuture; }
From source file:com.vmware.loginsightapi.LogInsightClient.java
/** * Performs message query. Returns a CompletableFuture for * MessageQueryResponse/*from w w w.jav a 2s.c o m*/ * * @param apiUrl * relative url of the API * @return MessageQueryResponse CompletableFuture object * @throws LogInsightApiException * Exception */ public CompletableFuture<MessageQueryResponse> messageQuery(String apiUrl) { HttpGet request = null; CompletableFuture<MessageQueryResponse> completableFuture = new CompletableFuture<MessageQueryResponse>(); try { request = getHttpRequest(apiUrl, false); asyncHttpClient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse httpResponse) { try { InputStream responseBody = httpResponse.getEntity().getContent(); String responseString = IOUtils.toString(responseBody, "UTF-8"); logger.warn("Response: " + responseString); completableFuture.complete(MessageQueryResponse.fromJsonString(responseString)); } catch (IOException e) { e.printStackTrace(); completableFuture.completeExceptionally(e); } } @Override public void failed(Exception ex) { completableFuture.completeExceptionally(new LogInsightApiException("Failed message Query", ex)); } @Override public void cancelled() { completableFuture.completeExceptionally(new LogInsightApiException("Cancelled message Query")); } }); } catch (Exception ie) { completableFuture.completeExceptionally(new LogInsightApiException("Message query failed", ie)); } return completableFuture; }