Example usage for io.vertx.core Future setHandler

List of usage examples for io.vertx.core Future setHandler

Introduction

In this page you can find the example usage for io.vertx.core Future setHandler.

Prototype

@Fluent
default Future<T> setHandler(Handler<AsyncResult<T>> handler) 

Source Link

Document

Like #onComplete(Handler) .

Usage

From source file:io.flowly.engine.verticles.Engine.java

License:Open Source License

private void saveInstance(FlowInstance instance, String status, boolean saveMetaData,
        Handler<AsyncResult<Boolean>> resultHandler) {
    Future<Boolean> future = Future.future();
    future.setHandler(resultHandler);

    FlowInstanceWrapper wrapper = new FlowInstanceWrapper(instance, false, saveMetaData, status, null);
    eventBus.send(EngineAddresses.REPO_FLOW_SAVE_INSTANCE, wrapper, reply -> {
        future.complete((Boolean) reply.result().body());
    });//  w w w .  jav a2s  . c om
}

From source file:io.flowly.engine.verticles.Engine.java

License:Open Source License

private void getInstance(Long flowObjectInstanceId, Handler<AsyncResult<FlowInstance>> resultHandler) {
    Future<FlowInstance> future = Future.future();
    future.setHandler(resultHandler);

    if (flowObjectInstanceId != null) {
        eventBus.send(EngineAddresses.GET_FLOW_INSTANCE_TASK, flowObjectInstanceId, reply -> {
            future.complete((FlowInstance) reply.result().body());
        });/*  w  w w. j av a 2 s .  c om*/
    } else {
        future.complete(null);
    }
}

From source file:io.nitor.api.backend.msgraph.GraphQueryHandler.java

License:Apache License

@Override
public void handle(RoutingContext ctx) {
    HttpServerRequest sreq = ctx.request();
    String path = sreq.path();/* w w  w  .  ja v a2s  .  com*/
    path = path.substring(routeLength);
    if (!path.startsWith("/")) {
        path = '/' + path;
    }
    path = baseUrl + path + paramsOf(ctx.request().absoluteURI());

    Map<String, String> data = sessionHandler.getSessionData(ctx);
    String refreshToken = data.get(GRAPH_ACCESS_TOKEN_KEY);
    Future<TokenData> tokenFuture = tokenCache.getAccessToken(refreshToken);

    HttpServerResponse sres = ctx.response();
    String finalPath = path;
    tokenFuture.setHandler(tokenResult -> {
        if (tokenResult.failed()) {
            sessionHandler.removeCookie(ctx);
            String err = tokenResult.cause().toString();
            logger.error(err);
            sres.setStatusCode(INTERNAL_SERVER_ERROR.code()).end(err);
            return;
        }
        TokenData token = tokenResult.result();
        if (!refreshToken.equals(token.refreshToken)) {
            Map<String, String> newData = new HashMap<>(data);
            newData.put(GRAPH_ACCESS_TOKEN_KEY, token.refreshToken);
            sessionHandler.setSessionData(ctx, newData);
        }
        String clientRequestId = UUID.randomUUID().toString();
        logger.info("Querying " + sreq.method() + " " + finalPath + " [" + clientRequestId + "]");
        HttpClientRequest creq = httpClient.requestAbs(sreq.method(), finalPath)
                .putHeader(AUTHORIZATION, "Bearer " + token.accessToken).putHeader(ACCEPT, APPLICATION_JSON)
                .putHeader("client-request-id", clientRequestId).setTimeout(SECONDS.toMillis(20))
                .exceptionHandler(err -> {
                    logger.error("Graph query failed [" + clientRequestId + "]", err);
                    if (!sres.ended()) {
                        sres.setStatusCode(INTERNAL_SERVER_ERROR.code()).write("Graph query failed: " + err)
                                .end();
                    }
                });

        for (String header : allowedRequestHeaders) {
            ofNullable(sreq.getHeader(header)).ifPresent(value -> creq.putHeader(header, value));
        }
        if (sres.headers().getAll("transfer-encoding").stream().anyMatch(v -> v.equals("chunked"))) {
            creq.setChunked(true);
        }

        sres.closeHandler(close -> creq.connection().close());
        creq.handler(cres -> mapResponse(cres, sres, clientRequestId));

        if (sreq.isEnded()) {
            creq.end();
        } else {
            sreq.endHandler(v -> {
                try {
                    creq.end();
                } catch (IllegalStateException ex) {
                    // ignore - nothing can be done - the request is already complete/closed - TODO log?
                }
            });
            Pump resPump = Pump.pump(sreq, creq);
            resPump.start();
        }
    });
}

From source file:io.nonobot.core.adapter.impl.BotAdapterImpl.java

License:Apache License

private synchronized void connect(long reconnectPeriod, String name) {
    if (closed) {
        throw new IllegalStateException("Closed");
    }/*from w w  w . j ava2s  .  co  m*/
    if (client != null) {
        throw new IllegalStateException("Already connected");
    }
    client = new BotClientImpl(vertx, vertx.getOrCreateContext(), new ClientOptions().setName(name), ar1 -> {
        if (ar1.succeeded()) {
            Future<Void> completionFuture = Future.future();
            completionFuture.setHandler(ar2 -> {
                if (ar2.failed()) {
                    client = null;
                    System.out.println("Connection failure");
                    ar2.cause().printStackTrace();
                    reconnect(reconnectPeriod, name);
                } else {
                    connected = true;
                }
            });
            connectHandler.handle(new ConnectionRequestImpl(this, client, completionFuture));
        } else {
            client = null;
            ar1.cause().printStackTrace();
            reconnect(reconnectPeriod, name);
        }
    }) {
        @Override
        public void close() {
            super.close();
            client = null;
            connected = false;
            reconnect(reconnectPeriod, name);
        }
    };
}

From source file:io.nonobot.core.client.impl.BotClientImpl.java

License:Apache License

@Override
public void receiveMessage(ReceiveOptions options, String message, Handler<AsyncResult<String>> replyHandler) {
    String replyAddress = UUID.randomUUID().toString();
    Future<String> reply = Future.future();
    reply.setHandler(replyHandler);
    MessageConsumer<String> consumer = vertx.eventBus().consumer(replyAddress);
    consumer.handler(msg -> {/*w  w  w .ja v a2 s. c  om*/
        String content = msg.body();
        if (content != null && !reply.isComplete()) {
            if (msg.replyAddress() != null) {
                msg.reply(null);
            }
            reply.complete(content);
            consumer.unregister();
        } else {
            if (msg.replyAddress() != null) {
                msg.fail(0, "Already replied");
            }
        }
    });
    consumer.completionHandler(ar -> {
        if (ar.succeeded()) {
            Matcher botMatcher = botPattern.matcher(message);
            JsonObject msg = new JsonObject().put("replyAddress", replyAddress);
            msg.put("chatId", options.getChatId());
            if (botMatcher.find()) {
                msg.put("respond", true);
                msg.put("content", botMatcher.group(1));
            } else {
                msg.put("respond", false);
                msg.put("content", message);
            }
            vertx.eventBus().publish(inboundAddress, msg);
            vertx.setTimer(options.getTimeout(), timerID -> {
                if (!reply.isComplete()) {
                    consumer.unregister();
                    reply.fail(new Exception("timeout"));
                }
            });
        } else {
            replyHandler.handle(Future.failedFuture(ar.cause()));
        }
    });
}

From source file:io.reactiverse.pgclient.impl.SocketConnection.java

License:Apache License

void upgradeToSSLConnection(Handler<AsyncResult<Void>> completionHandler) {
    ChannelPipeline pipeline = socket.channelHandlerContext().pipeline();
    Future<Void> upgradeFuture = Future.future();
    upgradeFuture.setHandler(ar -> {
        if (ar.succeeded()) {
            completionHandler.handle(Future.succeededFuture());
        } else {//from   www  . j a  va 2s.  co m
            Throwable cause = ar.cause();
            if (cause instanceof DecoderException) {
                DecoderException err = (DecoderException) cause;
                cause = err.getCause();
            }
            completionHandler.handle(Future.failedFuture(cause));
        }
    });
    pipeline.addBefore("handler", "initiate-ssl-handler", new InitiateSslHandler(this, upgradeFuture));
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

License:Open Source License

@Override
public final void doStop(final Future<Void> stopFuture) {

    try {//from   w  ww  .  j a  va 2  s .  com
        preShutdown();
    } catch (Exception e) {
        LOG.error("error in preShutdown", e);
    }

    Future<Void> shutdownTracker = Future.future();
    shutdownTracker.setHandler(done -> {
        if (done.succeeded()) {
            LOG.info("HTTP adapter has been shut down successfully");
            stopFuture.complete();
        } else {
            LOG.info("error while shutting down adapter", done.cause());
            stopFuture.fail(done.cause());
        }
    });

    Future<Void> serverStopTracker = Future.future();
    if (server != null) {
        server.close(serverStopTracker.completer());
    } else {
        serverStopTracker.complete();
    }

    Future<Void> insecureServerStopTracker = Future.future();
    if (insecureServer != null) {
        insecureServer.close(insecureServerStopTracker.completer());
    } else {
        insecureServerStopTracker.complete();
    }

    CompositeFuture.all(serverStopTracker, insecureServerStopTracker).compose(v -> {
        Future<Void> honoClientStopTracker = Future.future();
        closeClients(honoClientStopTracker.completer());
        return honoClientStopTracker;
    }).compose(v -> postShutdown()).compose(s -> shutdownTracker.complete(), shutdownTracker);
}

From source file:org.eclipse.hono.adapter.mqtt.VertxBasedMqttProtocolAdapter.java

License:Open Source License

private Future<MqttServer> bindSecureMqttServer() {

    if (isSecurePortEnabled()) {
        MqttServerOptions options = new MqttServerOptions();
        options.setHost(getConfig().getBindAddress()).setPort(determineSecurePort())
                .setMaxMessageSize(getConfig().getMaxPayloadSize());
        addTlsKeyCertOptions(options);//from   w  ww  .j  a va 2s . c  om
        addTlsTrustOptions(options);

        Future<MqttServer> result = Future.future();
        result.setHandler(mqttServerAsyncResult -> {
            server = mqttServerAsyncResult.result();
        });
        bindMqttServer(options, server, result);
        return result;
    } else {
        return Future.succeededFuture();
    }
}

From source file:org.eclipse.hono.adapter.mqtt.VertxBasedMqttProtocolAdapter.java

License:Open Source License

private Future<MqttServer> bindInsecureMqttServer() {

    if (isInsecurePortEnabled()) {
        MqttServerOptions options = new MqttServerOptions();
        options.setHost(getConfig().getInsecurePortBindAddress()).setPort(determineInsecurePort())
                .setMaxMessageSize(getConfig().getMaxPayloadSize());

        Future<MqttServer> result = Future.future();
        result.setHandler(mqttServerAsyncResult -> {
            insecureServer = mqttServerAsyncResult.result();
        });/* w w w.  j a  v a2 s  .  c o m*/
        bindMqttServer(options, insecureServer, result);
        return result;
    } else {
        return Future.succeededFuture();
    }
}

From source file:org.eclipse.hono.adapter.mqtt.VertxBasedMqttProtocolAdapter.java

License:Open Source License

@Override
public void doStop(final Future<Void> stopFuture) {

    Future<Void> shutdownTracker = Future.future();
    shutdownTracker.setHandler(done -> {
        if (done.succeeded()) {
            LOG.info("MQTT adapter has been shut down successfully");
            stopFuture.complete();//  w  w w . ja  va 2s.co m
        } else {
            LOG.info("error while shutting down MQTT adapter", done.cause());
            stopFuture.fail(done.cause());
        }
    });

    Future<Void> serverTracker = Future.future();
    if (this.server != null) {
        this.server.close(serverTracker.completer());
    } else {
        serverTracker.complete();
    }

    Future<Void> insecureServerTracker = Future.future();
    if (this.insecureServer != null) {
        this.insecureServer.close(insecureServerTracker.completer());
    } else {
        insecureServerTracker.complete();
    }

    CompositeFuture.all(serverTracker, insecureServerTracker).compose(d -> {
        closeClients(shutdownTracker.completer());
    }, shutdownTracker);
}