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:org.jnode.net.NServerSocket.java

private CompletableFuture<ServerSocketChannel> createServerChannel(int port) {
    CompletableFuture cf = new CompletableFuture<>();
    try {/*  ww w  . ja  v  a2 s.  com*/
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.socket().bind(new InetSocketAddress(port));
        cf.complete(ssc);
    } catch (Exception e) {
        cf.completeExceptionally(e);
    }
    return cf;
}

From source file:org.mule.service.oauth.internal.DefaultClientCredentialsOAuthDancer.java

@Override
public CompletableFuture<Void> refreshToken() {
    final Map<String, String> formData = new HashMap<>();

    formData.put(GRANT_TYPE_PARAMETER, GRANT_TYPE_CLIENT_CREDENTIALS);
    if (scopes != null) {
        formData.put(SCOPE_PARAMETER, scopes);
    }/* ww  w.  ja va 2  s  . c o  m*/
    String authorization = null;
    if (encodeClientCredentialsInBody) {
        formData.put(CLIENT_ID_PARAMETER, clientId);
        formData.put(CLIENT_SECRET_PARAMETER, clientSecret);
    } else {
        authorization = "Basic " + encodeBase64String(format("%s:%s", clientId, clientSecret).getBytes());
    }

    try {
        TokenResponse tokenResponse = invokeTokenUrl(tokenUrl, formData, authorization, false, encoding);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Retrieved access token, refresh token and expires from token url are: %s, %s, %s",
                    tokenResponse.getAccessToken(), tokenResponse.getRefreshToken(),
                    tokenResponse.getExpiresIn());
        }

        final DefaultResourceOwnerOAuthContext defaultUserState = (DefaultResourceOwnerOAuthContext) getContext();
        defaultUserState.setAccessToken(tokenResponse.getAccessToken());
        defaultUserState.setExpiresIn(tokenResponse.getExpiresIn());
        for (Entry<String, Object> customResponseParameterEntry : tokenResponse.getCustomResponseParameters()
                .entrySet()) {
            defaultUserState.getTokenResponseParameters().put(customResponseParameterEntry.getKey(),
                    customResponseParameterEntry.getValue());
        }

        updateResourceOwnerOAuthContext(defaultUserState);
        return completedFuture(null);
    } catch (TokenUrlResponseException | TokenNotFoundException e) {
        final CompletableFuture<Void> exceptionFuture = new CompletableFuture<>();
        exceptionFuture.completeExceptionally(e);
        return exceptionFuture;
    }
}

From source file:org.onlab.netty.NettyMessaging.java

protected CompletableFuture<Void> sendAsync(Endpoint ep, InternalMessage message) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    try {/*from  w  w  w .  j a  va 2  s .c  o m*/
        if (ep.equals(localEp)) {
            dispatchLocally(message);
            future.complete(null);
        } else {
            Channel channel = null;
            try {
                channel = channels.borrowObject(ep);
                channel.writeAndFlush(message).addListener(channelFuture -> {
                    if (!channelFuture.isSuccess()) {
                        future.completeExceptionally(channelFuture.cause());
                    } else {
                        future.complete(null);
                    }
                });
            } finally {
                channels.returnObject(ep, channel);
            }
        }
    } catch (Exception e) {
        future.completeExceptionally(e);
    }
    return future;
}

From source file:org.onlab.netty.NettyMessaging.java

@Override
public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
    CompletableFuture<byte[]> response = new CompletableFuture<>();
    Long messageId = messageIdGenerator.incrementAndGet();
    responseFutures.put(messageId, response);
    InternalMessage message = new InternalMessage(messageId, localEp, type, payload);
    try {/*from  w w w  . j  av  a2  s.com*/
        sendAsync(ep, message);
    } catch (Exception e) {
        responseFutures.invalidate(messageId);
        response.completeExceptionally(e);
    }
    return response;
}

From source file:org.onlab.nio.service.IOLoopMessaging.java

protected CompletableFuture<Void> sendAsync(Endpoint ep, DefaultMessage message) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    if (ep.equals(localEp)) {
        dispatchLocally(message);/*www . jav a  2  s.  c  o  m*/
        future.complete(null);
        return future;
    }

    DefaultMessageStream stream = null;
    try {
        stream = streams.borrowObject(ep);
        stream.write(message);
        future.complete(null);
    } catch (Exception e) {
        future.completeExceptionally(e);
    } finally {
        try {
            streams.returnObject(ep, stream);
        } catch (Exception e) {
            log.warn("Failed to return stream to pool");
        }
    }
    return future;
}

From source file:org.onlab.nio.service.IOLoopMessaging.java

@Override
public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
    CompletableFuture<byte[]> response = new CompletableFuture<>();
    Long messageId = messageIdGenerator.incrementAndGet();
    responseFutures.put(messageId, response);
    DefaultMessage message = new DefaultMessage(messageId, localEp, type, payload);
    try {/*from   w  ww. j av a 2 s  .  c o m*/
        sendAsync(ep, message);
    } catch (Exception e) {
        responseFutures.invalidate(messageId);
        response.completeExceptionally(e);
    }
    return response;
}

From source file:org.onosproject.incubator.store.meter.impl.DistributedMeterStore.java

@Override
public CompletableFuture<MeterStoreResult> storeMeter(Meter meter) {
    // Init steps
    CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
    MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
    // Store the future related to the operation
    futures.put(key, future);/*  ww w.j  a va 2 s  . com*/
    // Store the meter data
    MeterData data = new MeterData(meter, null, local);
    try {
        meters.put(key, data);
    } catch (StorageException e) {
        futures.remove(key);
        future.completeExceptionally(e);
    }
    // Done, return the future
    return future;
}

From source file:org.onosproject.incubator.store.meter.impl.DistributedMeterStore.java

@Override
public CompletableFuture<MeterStoreResult> deleteMeter(Meter meter) {
    // Init steps
    CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
    MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
    // Store the future related to the operation
    futures.put(key, future);//from  w ww.java2s .  c o  m
    // Create the meter data
    MeterData data = new MeterData(meter, null, local);
    // Update the state of the meter. It will be pruned by observing
    // that it has been removed from the dataplane.
    try {
        // If it does not exist in the system
        if (meters.computeIfPresent(key, (k, v) -> data) == null) {
            // Complete immediately
            future.complete(MeterStoreResult.success());
        }
    } catch (StorageException e) {
        futures.remove(key);
        future.completeExceptionally(e);
    }
    // Done, return the future
    return future;
}

From source file:org.onosproject.incubator.store.meter.impl.DistributedMeterStore.java

@Override
public CompletableFuture<MeterStoreResult> updateMeter(Meter meter) {
    CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
    MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
    futures.put(key, future);/*from  w  ww .  j ava  2  s .co  m*/

    MeterData data = new MeterData(meter, null, local);
    try {
        if (meters.computeIfPresent(key, (k, v) -> data) == null) {
            future.complete(MeterStoreResult.fail(MeterFailReason.INVALID_METER));
        }
    } catch (StorageException e) {
        futures.remove(key);
        future.completeExceptionally(e);
    }
    return future;
}

From source file:org.onosproject.store.cluster.messaging.impl.NettyMessagingManager.java

protected CompletableFuture<Void> sendAsync(Endpoint ep, InternalMessage message) {
    checkPermission(CLUSTER_WRITE);//  www  .j  a va 2 s .  co  m
    if (ep.equals(localEp)) {
        try {
            dispatchLocally(message);
        } catch (IOException e) {
            return Tools.exceptionalFuture(e);
        }
        return CompletableFuture.completedFuture(null);
    }

    CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        Connection connection = null;
        try {
            connection = channels.borrowObject(ep);
            connection.send(message, future);
        } finally {
            if (connection != null) {
                channels.returnObject(ep, connection);
            }
        }
    } catch (Exception e) {
        future.completeExceptionally(e);
    }
    return future;
}