Example usage for java.util.concurrent CompletableFuture getNow

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public T getNow(T valueIfAbsent) 

Source Link

Document

Returns the result value (or throws any encountered exception) if completed, else returns the given valueIfAbsent.

Usage

From source file:io.pravega.controller.store.stream.PersistentStreamBase.java

@Override
public CompletableFuture<Map<Integer, List<Integer>>> getSuccessorsWithPredecessors(final int number) {
    val legal = verifyLegalState();
    val indexTableFuture = getIndexTable();
    val historyTableFuture = getHistoryTable();
    CompletableFuture<List<Segment>> segments = getSuccessorsForSegment(number);

    CompletableFuture<Void> all = CompletableFuture.allOf(legal, segments, indexTableFuture,
            historyTableFuture);//from w w  w  .j a v a  2s .  co m

    return all.thenCompose(v -> {
        List<CompletableFuture<Map.Entry<Segment, List<Integer>>>> resultFutures = new ArrayList<>();
        List<Segment> successors = segments.getNow(null);
        for (Segment successor : successors) {
            List<Integer> candidates = TableHelper.findSegmentPredecessorCandidates(successor,
                    indexTableFuture.getNow(null).getData(), historyTableFuture.getNow(null).getData());
            resultFutures.add(findOverlapping(successor, candidates)
                    .thenApply(list -> new SimpleImmutableEntry<>(successor,
                            list.stream().map(Segment::getNumber).collect(Collectors.toList()))));
        }
        return FutureHelpers.allOfWithResults(resultFutures);
    }).thenApply(
            list -> list.stream().collect(Collectors.toMap(e -> e.getKey().getNumber(), e -> e.getValue())));
}

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  .  ja  v  a 2 s .com
    }

    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: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;/*from   w  w  w.ja  va2  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:io.liveoak.container.BasicServerTest.java

@Test
public void testServer() throws Exception {

    CompletableFuture<StompMessage> peopleCreationNotification = new CompletableFuture<>();
    CompletableFuture<StompMessage> bobCreationNotification = new CompletableFuture<>();

    StompClient stompClient = new StompClient();

    CountDownLatch subscriptionLatch = new CountDownLatch(1);

    stompClient.connect("localhost", 8080, (client) -> {
        stompClient.subscribe("/testApp/memory/people/*", (subscription) -> {
            subscription.onMessage((msg) -> {
                System.err.println("******* MESSAGE: " + msg);
                if (msg.headers().get("location").equals("/testApp/memory/people")) {
                    peopleCreationNotification.complete(msg);
                } else {
                    bobCreationNotification.complete(msg);
                }/*  w ww .j a  v  a  2  s.c  om*/
            });
            subscription.onReceipt(() -> {
                subscriptionLatch.countDown();
            });
        });
    });

    subscriptionLatch.await();

    Header header = new BasicHeader("Accept", "application/json");

    HttpGet getRequest = null;
    HttpPost postRequest = null;
    HttpPut putRequest = null;
    CloseableHttpResponse response = null;

    System.err.println("TEST #1");
    // Root object should exist.
    getRequest = new HttpGet("http://localhost:8080/testApp/memory");
    getRequest.addHeader(header);

    response = this.httpClient.execute(getRequest);

    //  {
    //    "id" : "memory",
    //    "self" : {
    //      "href" : "/memory"
    //    },
    //   "content" : [ ]
    // }

    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    ResourceState state = decode(response);
    assertThat(state).isNotNull();
    assertThat(state.members().size()).isEqualTo(0);

    response.close();

    System.err.println("TEST #2");
    // people collection should not exist.

    getRequest = new HttpGet("http://localhost:8080/testApp/memory/people");

    response = this.httpClient.execute(getRequest);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(404);

    response.close();

    System.err.println("TEST #3");
    // create people collection with direct PUT

    putRequest = new HttpPut("http://localhost:8080/testApp/memory/people");
    putRequest.setEntity(new StringEntity("{ \"type\": \"collection\" }"));
    putRequest.setHeader("Content-Type", "application/json");
    response = this.httpClient.execute(putRequest);
    System.err.println("response: " + response);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201);

    response.close();

    System.err.println("TEST #4");
    // people collection should exist now.

    getRequest = new HttpGet("http://localhost:8080/testApp/memory/people");

    response = this.httpClient.execute(getRequest);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    response.close();

    assertThat(peopleCreationNotification.getNow(null)).isNull();

    System.err.println("TEST #5");
    // people collection should be enumerable from the root

    getRequest = new HttpGet("http://localhost:8080/testApp/memory?expand=members");
    getRequest.addHeader(header);

    response = this.httpClient.execute(getRequest);

    //        {
    //          "id" : "memory",
    //          "self" : {
    //            "href" : "/memory"
    //          },
    //          "content" : [ {
    //            "id" : "people",
    //            "self" : {
    //                "href" : "/memory/people"
    //            },
    //            "content" : [ ]
    //          } ]
    //        }

    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    state = decode(response);
    assertThat(state).isNotNull();
    assertThat(state.members().size()).isEqualTo(1);

    ResourceState memoryCollection = state.members().get(0);
    assertThat(memoryCollection.id()).isEqualTo("people");

    assertThat(memoryCollection.uri().toString()).isEqualTo("/testApp/memory/people");

    System.err.println("TEST #6");
    // Post a person

    postRequest = new HttpPost("http://localhost:8080/testApp/memory/people");
    postRequest.setEntity(new StringEntity("{ \"name\": \"bob\" }"));
    postRequest.setHeader("Content-Type", "application/json");

    response = httpClient.execute(postRequest);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201);

    state = decode(response);
    assertThat(state).isNotNull();
    assertThat(state).isInstanceOf(ResourceState.class);

    assertThat(state.id()).isNotNull();
    assertThat(state.getProperty("name")).isEqualTo("bob");

    // check STOMP
    System.err.println("TEST #STOMP");
    StompMessage obj = bobCreationNotification.get(30000, TimeUnit.SECONDS);
    assertThat(obj).isNotNull();

    ResourceState bobObjState = decode(obj.content());
    assertThat(bobObjState.getProperty("name")).isEqualTo("bob");

    assertThat(state.getProperty(LiveOak.ID)).isEqualTo(bobObjState.getProperty(LiveOak.ID));
    response.close();
}