Example usage for java.util.concurrent CompletableFuture completeExceptionally

List of usage examples for java.util.concurrent CompletableFuture completeExceptionally

Introduction

In this page you can find the example usage for java.util.concurrent CompletableFuture completeExceptionally.

Prototype

public boolean completeExceptionally(Throwable ex) 

Source Link

Document

If not already completed, causes invocations of #get() and related methods to throw the given exception.

Usage

From source file:io.pravega.segmentstore.server.reading.StorageReadManagerTests.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  v  a  2  s.  com
@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
    StorageReadManager reader = new StorageReadManager(SEGMENT_METADATA, storage, executorService());

    // Create some reads.
    CompletableFuture<StorageReadManager.Result> c1 = new CompletableFuture<>();
    CompletableFuture<StorageReadManager.Result> c2 = new CompletableFuture<>();
    reader.execute(new StorageReadManager.Request(0, 100, c1::complete, c1::completeExceptionally, TIMEOUT));
    reader.execute(new StorageReadManager.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.yahoo.pulsar.client.impl.PulsarClientImpl.java

public CompletableFuture<Producer> createProducerAsync(final String topic, final ProducerConfiguration conf,
        String producerName) {/*from  ww w.  ja v a  2  s . co  m*/
    if (state.get() != State.Open) {
        return FutureUtil
                .failedFuture(new PulsarClientException.AlreadyClosedException("Client already closed"));
    }

    if (!DestinationName.isValid(topic)) {
        return FutureUtil
                .failedFuture(new PulsarClientException.InvalidTopicNameException("Invalid topic name"));
    }
    if (conf == null) {
        return FutureUtil.failedFuture(
                new PulsarClientException.InvalidConfigurationException("Producer configuration undefined"));
    }

    CompletableFuture<Producer> producerCreatedFuture = new CompletableFuture<>();

    getPartitionedTopicMetadata(topic).thenAccept(metadata -> {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Received topic metadata. partitions: {}", topic, metadata.partitions);
        }

        ProducerBase producer;
        if (metadata.partitions > 1) {
            producer = new PartitionedProducerImpl(PulsarClientImpl.this, topic, conf, metadata.partitions,
                    producerCreatedFuture);
        } else {
            producer = new ProducerImpl(PulsarClientImpl.this, topic, producerName, conf, producerCreatedFuture,
                    -1);
        }

        synchronized (producers) {
            producers.put(producer, Boolean.TRUE);
        }
    }).exceptionally(ex -> {
        log.warn("[{}] Failed to get partitioned topic metadata: {}", topic, ex.getMessage());
        producerCreatedFuture.completeExceptionally(ex);
        return null;
    });

    return producerCreatedFuture;
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

private CompletableFuture<Channel> openChannel(Address address) {
    Bootstrap bootstrap = bootstrapClient(address);
    CompletableFuture<Channel> retFuture = new CompletableFuture<>();
    ChannelFuture f = bootstrap.connect();

    f.addListener(future -> {//from w ww .  j ava  2s  .c om
        if (future.isSuccess()) {
            retFuture.complete(f.channel());
        } else {
            retFuture.completeExceptionally(future.cause());
        }
    });
    log.debug("Established a new connection to {}", address);
    return retFuture;
}

From source file:com.yahoo.pulsar.client.impl.PulsarClientImpl.java

@Override
public CompletableFuture<Void> closeAsync() {
    log.info("Client closing. URL: {}", lookup.getServiceUrl());
    if (!state.compareAndSet(State.Open, State.Closing)) {
        return FutureUtil
                .failedFuture(new PulsarClientException.AlreadyClosedException("Client already closed"));
    }//  w w w . j a v a  2 s .c o m

    final CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    List<CompletableFuture<Void>> futures = Lists.newArrayList();

    synchronized (producers) {
        // Copy to a new list, because the closing will trigger a removal from the map
        // and invalidate the iterator
        List<ProducerBase> producersToClose = Lists.newArrayList(producers.keySet());
        producersToClose.forEach(p -> futures.add(p.closeAsync()));
    }

    synchronized (consumers) {
        List<ConsumerBase> consumersToClose = Lists.newArrayList(consumers.keySet());
        consumersToClose.forEach(c -> futures.add(c.closeAsync()));
    }

    FutureUtil.waitForAll(futures).thenRun(() -> {
        // All producers & consumers are now closed, we can stop the client safely
        try {
            shutdown();
            closeFuture.complete(null);
            state.set(State.Closed);
        } catch (PulsarClientException e) {
            closeFuture.completeExceptionally(e);
        }
    }).exceptionally(exception -> {
        closeFuture.completeExceptionally(exception);
        return null;
    });

    return closeFuture;
}

From source file:com.yahoo.pulsar.broker.service.BrokerService.java

/**
 * Unload all the topic served by the broker service under the given service unit
 *
 * @param serviceUnit/*from w  ww .ja  va  2s  .  co m*/
 * @return
 */
public CompletableFuture<Integer> unloadServiceUnit(NamespaceBundle serviceUnit) {
    CompletableFuture<Integer> result = new CompletableFuture<Integer>();
    List<CompletableFuture<Void>> closeFutures = Lists.newArrayList();
    topics.forEach((name, topicFuture) -> {
        DestinationName topicName = DestinationName.get(name);
        if (serviceUnit.includes(topicName)) {
            // Topic needs to be unloaded
            log.info("[{}] Unloading topic", topicName);
            closeFutures.add(topicFuture.thenCompose(Topic::close));
        }
    });
    CompletableFuture<Void> aggregator = FutureUtil.waitForAll(closeFutures);
    aggregator.thenAccept(res -> result.complete(closeFutures.size())).exceptionally(ex -> {
        result.completeExceptionally(ex);
        return null;
    });
    return result;
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

private <T> void executeOnPooledConnection(Address address, String type,
        Function<ClientConnection, CompletableFuture<T>> callback, Executor executor,
        CompletableFuture<T> future) {
    if (address.equals(localAddress)) {
        callback.apply(localClientConnection).whenComplete((result, error) -> {
            if (error == null) {
                executor.execute(() -> future.complete(result));
            } else {
                executor.execute(() -> future.completeExceptionally(error));
            }//from ww  w. j av a 2s .  c  o m
        });
        return;
    }

    getChannel(address, type).whenComplete((channel, channelError) -> {
        if (channelError == null) {
            final ClientConnection connection = getOrCreateRemoteClientConnection(channel);
            callback.apply(connection).whenComplete((result, sendError) -> {
                if (sendError == null) {
                    executor.execute(() -> future.complete(result));
                } else {
                    final Throwable cause = Throwables.getRootCause(sendError);
                    if (!(cause instanceof TimeoutException) && !(cause instanceof MessagingException)) {
                        channel.close().addListener(f -> {
                            connection.close();
                            clientConnections.remove(channel);
                        });
                    }
                    executor.execute(() -> future.completeExceptionally(sendError));
                }
            });
        } else {
            executor.execute(() -> future.completeExceptionally(channelError));
        }
    });
}

From source file:com.movilizer.mds.webservice.services.UploadFileService.java

private CompletableFuture<UploadResponse> upload(HttpEntity entity, Integer connectionTimeoutInMillis) {
    CompletableFuture<UploadResponse> future = new CompletableFuture<>();
    try {// w  w  w .  j a  v a  2  s  .c om

        Async.newInstance().execute(
                Request.Post(documentUploadAddress.toURI())
                        .addHeader(USER_AGENT_HEADER_KEY, DefaultValues.USER_AGENT)
                        .connectTimeout(connectionTimeoutInMillis).body(entity),
                new ResponseHandlerAdapter<UploadResponse>(future) {
                    @Override
                    public UploadResponse convertHttpResponse(HttpResponse httpResponse) {
                        logger.info(Messages.UPLOAD_COMPLETE);
                        int statusCode = httpResponse.getStatusLine().getStatusCode();
                        String errorMessage = httpResponse.getStatusLine().getReasonPhrase();
                        if (statusCode == POSSIBLE_BAD_CREDENTIALS) {
                            errorMessage = errorMessage + Messages.FAILED_FILE_UPLOAD_CREDENTIALS;
                        }
                        return new UploadResponse(statusCode, errorMessage);
                    }
                });
    } catch (URISyntaxException e) {
        if (logger.isErrorEnabled()) {
            logger.error(String.format(Messages.UPLOAD_ERROR, e.getMessage()));
        }
        future.completeExceptionally(new MovilizerWebServiceException(e));
    }
    return future;
}

From source file:com.yahoo.pulsar.client.impl.PulsarClientImpl.java

@Override
public CompletableFuture<Consumer> subscribeAsync(final String topic, final String subscription,
        final ConsumerConfiguration conf) {
    if (state.get() != State.Open) {
        return FutureUtil
                .failedFuture(new PulsarClientException.AlreadyClosedException("Client already closed"));
    }//from w  ww . ja v  a  2s.  c o  m
    if (!DestinationName.isValid(topic)) {
        return FutureUtil
                .failedFuture(new PulsarClientException.InvalidTopicNameException("Invalid topic name"));
    }
    if (subscription == null) {
        return FutureUtil.failedFuture(
                new PulsarClientException.InvalidConfigurationException("Invalid subscription name"));
    }
    if (conf == null) {
        return FutureUtil.failedFuture(
                new PulsarClientException.InvalidConfigurationException("Consumer configuration undefined"));
    }

    CompletableFuture<Consumer> consumerSubscribedFuture = new CompletableFuture<>();

    getPartitionedTopicMetadata(topic).thenAccept(metadata -> {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Received topic metadata. partitions: {}", topic, metadata.partitions);
        }

        ConsumerBase consumer;
        // gets the next single threaded executor from the list of executors
        ExecutorService listenerThread = externalExecutorProvider.getExecutor();
        if (metadata.partitions > 1) {
            consumer = new PartitionedConsumerImpl(PulsarClientImpl.this, topic, subscription, conf,
                    metadata.partitions, listenerThread, consumerSubscribedFuture);
        } else {
            consumer = new ConsumerImpl(PulsarClientImpl.this, topic, subscription, conf, listenerThread,
                    consumerSubscribedFuture);
        }

        synchronized (consumers) {
            consumers.put(consumer, Boolean.TRUE);
        }
    }).exceptionally(ex -> {
        log.warn("[{}] Failed to get partitioned topic metadata", topic, ex);
        consumerSubscribedFuture.completeExceptionally(ex);
        return null;
    });

    return consumerSubscribedFuture;
}

From source file:org.jaqpot.core.service.client.jpdi.JPDIClientImpl.java

@Override
public Future<Dataset> predict(Dataset inputDataset, Model model, MetaInfo datasetMeta, String taskId) {

    CompletableFuture<Dataset> futureDataset = new CompletableFuture<>();

    Dataset dataset = DatasetFactory.copy(inputDataset);
    Dataset tempWithDependentFeatures = DatasetFactory.copy(dataset,
            new HashSet<>(model.getDependentFeatures()));

    dataset.getDataEntry().parallelStream().forEach(dataEntry -> {
        dataEntry.getValues().keySet().retainAll(model.getIndependentFeatures());
    });//from  ww  w .j  ava2s. com
    PredictionRequest predictionRequest = new PredictionRequest();
    predictionRequest.setDataset(dataset);
    predictionRequest.setRawModel(model.getActualModel());
    predictionRequest.setAdditionalInfo(model.getAdditionalInfo());

    final HttpPost request = new HttpPost(model.getAlgorithm().getPredictionService());
    request.addHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");

    PipedOutputStream out = new PipedOutputStream();
    PipedInputStream in;
    try {
        in = new PipedInputStream(out);
    } catch (IOException ex) {
        futureDataset.completeExceptionally(ex);
        return futureDataset;
    }
    request.setEntity(new InputStreamEntity(in, ContentType.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:
                    try {
                        PredictionResponse predictionResponse = serializer.parse(responseStream,
                                PredictionResponse.class);

                        List<LinkedHashMap<String, Object>> predictions = predictionResponse.getPredictions();
                        if (dataset.getDataEntry().isEmpty()) {
                            DatasetFactory.addEmptyRows(dataset, predictions.size());
                        }
                        List<Feature> features = featureHandler
                                .findBySource("algorithm/" + model.getAlgorithm().getId());
                        IntStream.range(0, dataset.getDataEntry().size())
                                // .parallel()
                                .forEach(i -> {
                                    Map<String, Object> row = predictions.get(i);
                                    DataEntry dataEntry = dataset.getDataEntry().get(i);
                                    if (model.getAlgorithm().getOntologicalClasses().contains("ot:Scaling")
                                            || model.getAlgorithm().getOntologicalClasses()
                                                    .contains("ot:Transformation")) {
                                        dataEntry.getValues().clear();
                                        dataset.getFeatures().clear();
                                    }
                                    row.entrySet().stream().forEach(entry -> {
                                        //                                                    Feature feature = featureHandler.findByTitleAndSource(entry.getKey(), "algorithm/" + model.getAlgorithm().getId());
                                        Feature feature = features.stream()
                                                .filter(f -> f.getMeta().getTitles().contains(entry.getKey()))
                                                .findFirst().orElse(null);
                                        if (feature == null) {
                                            return;
                                        }
                                        dataEntry.getValues().put(baseURI + "feature/" + feature.getId(),
                                                entry.getValue());
                                        FeatureInfo featInfo = new FeatureInfo(
                                                baseURI + "feature/" + feature.getId(),
                                                feature.getMeta().getTitles().stream().findFirst().get());
                                        featInfo.setCategory(Dataset.DescriptorCategory.PREDICTED);
                                        dataset.getFeatures().add(featInfo);
                                    });
                                });
                        dataset.setId(randomStringGenerator.nextString(20));
                        dataset.setTotalRows(dataset.getDataEntry().size());
                        dataset.setMeta(datasetMeta);
                        futureDataset.complete(DatasetFactory.mergeColumns(dataset, tempWithDependentFeatures));
                    } catch (Exception ex) {
                        futureDataset.completeExceptionally(ex);
                    }
                    break;
                case 400:
                    String message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new BadRequestException(message));
                    break;
                case 404:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new NotFoundException(message));
                    break;
                case 500:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new InternalServerErrorException(message));
                    break;
                default:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new InternalServerErrorException(message));
                }
            } catch (IOException | UnsupportedOperationException ex) {
                futureDataset.completeExceptionally(ex);
            }
        }

        @Override
        public void failed(final Exception ex) {
            futureMap.remove(taskId);
            futureDataset.completeExceptionally(new InternalServerErrorException(ex));
        }

        @Override
        public void cancelled() {
            futureMap.remove(taskId);
            futureDataset.cancel(true);
        }
    });
    serializer.write(predictionRequest, out);
    try {
        out.close();
    } catch (IOException ex) {
        futureDataset.completeExceptionally(ex);
    }
    futureMap.put(taskId, futureResponse);
    return futureDataset;
}

From source file:com.yahoo.pulsar.broker.namespace.NamespaceService.java

private CompletableFuture<LookupResult> createLookupResult(String candidateBroker) throws Exception {

    CompletableFuture<LookupResult> lookupFuture = new CompletableFuture<>();
    try {/*  w ww  .java  2s  .  c  o m*/
        checkArgument(StringUtils.isNotBlank(candidateBroker),
                "Lookup broker can't be null " + candidateBroker);
        URI uri = new URI(candidateBroker);
        String path = String.format("%s/%s:%s", SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT, uri.getHost(),
                uri.getPort());
        pulsar.getLocalZkCache().getDataAsync(path, loadReportDeserializer).thenAccept(reportData -> {
            if (reportData.isPresent()) {
                LoadReport report = reportData.get();
                lookupFuture.complete(new LookupResult(report.getWebServiceUrl(), report.getWebServiceUrlTls(),
                        report.getPulsarServiceUrl(), report.getPulsarServieUrlTls()));
            } else {
                lookupFuture.completeExceptionally(new KeeperException.NoNodeException(path));
            }
        }).exceptionally(ex -> {
            lookupFuture.completeExceptionally(ex);
            return null;
        });
    } catch (Exception e) {
        lookupFuture.completeExceptionally(e);
    }
    return lookupFuture;
}