Example usage for io.vertx.core Future future

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

Introduction

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

Prototype

future

Source Link

Usage

From source file:io.github.pflima92.plyshare.gateway.manager.GatewayManagerImpl.java

License:Apache License

@Override
public Future<Gateway> setup() {

    Future<Gateway> future = Future.future();
    return persistance.findGateway(gatewayOptionsHolder.getOptions().getProfile()).compose(oGateway -> {

        if (oGateway.isPresent()) {

            currentGateway = oGateway.get();
            future.complete(currentGateway);
        } else {//  ww  w.j  av a2s .  com

            install(future);
        }
    }, future);
}

From source file:io.github.resilience4j.circuitbreaker.VertxCircuitBreaker.java

License:Apache License

/**
 * Returns a Future which is decorated by a CircuitBreaker.
 *
 * @param circuitBreaker the CircuitBreaker
 * @param supplier the Future supplier//w w w  .j  a v  a  2  s  .  c  o  m
 * @param <T> the type of the returned Future's result
 * @return a future which is decorated by a CircuitBreaker.
 */
static <T> Supplier<Future<T>> decorateFuture(CircuitBreaker circuitBreaker, Supplier<Future<T>> supplier) {
    return () -> {
        final Future<T> future = Future.future();

        if (!circuitBreaker.isCallPermitted()) {
            future.fail(new CircuitBreakerOpenException(
                    String.format("CircuitBreaker '%s' is open", circuitBreaker.getName())));

        } else {
            long start = System.nanoTime();
            try {
                supplier.get().setHandler(result -> {
                    long durationInNanos = System.nanoTime() - start;
                    if (result.failed()) {
                        circuitBreaker.onError(durationInNanos, result.cause());
                        future.fail(result.cause());
                    } else {
                        circuitBreaker.onSuccess(durationInNanos);
                        future.complete(result.result());
                    }
                });
            } catch (Throwable throwable) {
                long durationInNanos = System.nanoTime() - start;
                circuitBreaker.onError(durationInNanos, throwable);
                future.fail(throwable);
            }
        }
        return future;
    };
}

From source file:io.gravitee.fetcher.http.vertx.VertxCompletableFuture.java

License:Apache License

/**
 * Creates a Vert.x {@link Future} from the given {@link CompletableFuture} (that can be a
 * {@link VertxCompletableFuture}).//from w  w w .  ja va 2s.c  o  m
 *
 * @param future the future
 * @param <T>    the type of the result
 * @return the Vert.x future completed or failed when the given {@link CompletableFuture} completes or fails.
 */
public static <T> Future<T> toFuture(CompletableFuture<T> future) {
    Future<T> fut = Future.future();
    Objects.requireNonNull(future).whenComplete((res, err) -> {
        if (err != null) {
            fut.fail(err);
        } else {
            fut.complete(res);
        }
    });
    return fut;
}

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

License:Apache License

public Future<TokenData> getAccessToken(String refreshToken) {
    if (refreshToken == null) {
        return failedFuture("refresh_token missing from session");
    }// www . j  a  v  a2  s. c  o  m
    TokenData d = cache.getOrDefault(refreshToken, missingToken);
    if (d.expires > currentTimeMillis()) {
        return succeededFuture(d);
    }
    Buffer form = Buffer.buffer(baseForm + "&refresh_token=" + urlEncode(refreshToken));
    final Future<TokenData> ret = Future.future();
    httpClient.getAbs(tokenUrl).putHeader(ACCEPT, APPLICATION_JSON)
            .putHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
            .putHeader(CONTENT_LENGTH, String.valueOf(form.length())).setTimeout(SECONDS.toMillis(10))
            .exceptionHandler(err -> {
                logger.error("Failed to refresh graph access token", err);
                ret.fail(err);
            }).handler(resp -> handleRefreshResponse(resp, ret, d.refreshToken)).end(form);
    return ret;
}

From source file:io.nonobot.core.adapter.BotAdapter.java

License:Apache License

/**
 * Like {@link #connect(BotClient,Future)}.
 */
@Fluent
default BotAdapter connect(BotClient client) {
    return connect(client, Future.future());
}

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 a v  a  2 s . com*/
    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);/*from   w w  w  .j  a  v a2  s . c  o m*/
    MessageConsumer<String> consumer = vertx.eventBus().consumer(replyAddress);
    consumer.handler(msg -> {
        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 -> {/*from  w w  w . jav a 2 s  .co  m*/
        if (ar.succeeded()) {
            completionHandler.handle(Future.succeededFuture());
        } else {
            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.dfr.dfr.Main.java

@Override
public void start(Future<Void> start) {
    HttpServer server = vertx.createHttpServer();
    Future<String> dm1 = Future.future();
    vertx.deployVerticle("org.dfr.dfr.worker.MemberWorker", new DeploymentOptions().setWorkerPoolSize(10),
            dm1.completer());/* ww  w .ja v  a 2s . c  o  m*/
    Future<HttpServer> depoyServerOK = Future.future();
    Router router = Router.router(vertx);
    StaticHandler staticH = StaticHandler.create();
    staticH.setWebRoot("templates");
    router.get("/*").handler(staticH);

    /**
     * Async block
     */
    router.post("/member/register").handler(h -> {
        h.request().bodyHandler(bH -> {
            vertx.eventBus().send("MemberWorker#Register", bH.toString(),
                    new DeliveryOptions().setSendTimeout(3000), evt -> {
                        if (evt.failed()) {
                            h.response().setStatusCode(408).end();
                        } else {
                            h.response().end(evt.result().body().toString());
                        }
                    });
        });
    });

    /**
     * Async block
     */
    router.post("/member/profileupdate").handler(h -> {
        h.request().bodyHandler(bH -> {
            vertx.eventBus().send("MemberWorker#ProfileUpdate", bH.toString(),
                    new DeliveryOptions().setSendTimeout(3000), evt -> {
                        if (evt.failed()) {
                            h.response().setStatusCode(408).end();
                        } else {
                            h.response().end(evt.result().body().toString());
                        }
                    });
        });
    });

    /**
     * Async block
     */
    router.post("/member/getprofile").handler(h -> {
        h.request().bodyHandler(bH -> {
            vertx.eventBus().send("MemberWorker#GetProfile", bH.toString(),
                    new DeliveryOptions().setSendTimeout(3000), evt -> {
                        if (evt.failed()) {
                            h.response().setStatusCode(408).end();
                        } else {
                            h.response().end(evt.result().body().toString());
                        }
                    });
        });
    });

    /**
     * Async block
     */
    router.post("/member/changepassword").handler(h -> {
        h.request().bodyHandler(bH -> {
            vertx.eventBus().send("MemberWorker#ChangePassword", bH.toString(),
                    new DeliveryOptions().setSendTimeout(3000), evt -> {
                        if (evt.failed()) {
                            h.response().setStatusCode(408).end();
                        } else {
                            h.response().end(evt.result().body().toString());
                        }
                    });
        });
    });

    /**
     * Async block
     */
    router.post("/member/asset/addasset").handler(h -> {
        h.request().bodyHandler(bH -> {
            vertx.eventBus().send("MembrWorker#AddAsset", bH.toString(),
                    new DeliveryOptions().setSendTimeout(3000), evt -> {
                        if (evt.failed()) {
                            h.response().setStatusCode(408).end();
                        } else {
                            h.response().end(evt.result().body().toString());
                        }
                    });
        });
    });

    router.post("/member/asset/getasset").handler(h -> {
        h.request().bodyHandler(bH -> {
            vertx.eventBus().send("AssetWorker#GetAsset", bH.toString(),
                    new DeliveryOptions().setSendTimeout(3000), evt -> {
                        if (evt.failed()) {
                            h.response().setStatusCode(408).end();
                        } else {
                            h.response().end(evt.result().body().toString());
                        }
                    });
        });
    });

    router.post("/member/asset/updateasset").handler(h -> {
        h.request().bodyHandler(bH -> {
            vertx.eventBus().send("AssetWorker#UpdateAsset", bH.toString(),
                    new DeliveryOptions().setSendTimeout(3000), evt -> {
                        if (evt.failed()) {
                            h.response().setStatusCode(408).end();
                        } else {
                            h.response().end(evt.result().body().toString());
                        }
                    });
        });
    });

    server.requestHandler(router::accept);
    Integer port = Integer.getInteger("http.port");
    String host = System.getProperty("http.address");

    log.info("port " + port);
    log.info("host " + host);

    if (port == null) {
        port = 8090;
    }
    if (host == null) {
        host = "127.0.0.1";
    }

    server.listen(port, host, depoyServerOK.completer());
    CompositeFuture.all(Arrays.asList(depoyServerOK, dm1)).setHandler(h -> {
        if (h.succeeded()) {
            start.complete();
            log.info("server start ok");
        } else {
            start.fail(h.cause());
            log.info("fail to deploy : " + h.cause().getMessage());
        }
    });
}

From source file:org.dfr.dfr.worker.MemberWorker.java

@Override
public void start(Future<Void> fut) {
    JsonObject config = new JsonObject();
    config.put("url", "jdbc:mysql://localhost:3306/latihan");
    config.put("driver_class", "com.mysql.jdbc.Driver");
    config.put("user", "root");
    config.put("password", "admin");
    JDBCClient client = JDBCClient.createShared(vertx, config, "memberds");
    final Validator v = Validation.buildDefaultValidatorFactory().getValidator();
    SimpleDateFormat mysqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    vertx.eventBus().consumer("MemberWorker#Register").handler(h -> {
        MemberRegisterRequest req = null;
        try {/*from w  w  w.ja va 2s . c  o  m*/
            req = Json.decodeValue(h.body().toString(), MemberRegisterRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        Set<ConstraintViolation<MemberRegisterRequest>> vr = v.validate(req);
        if (!vr.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)
                    .setMessage(vr.iterator().next().getMessage())));
            return;
        }
        final MemberRegisterRequest r = req;
        final HashMap<String, Object> smap = new HashMap();

        client.getConnection(ch -> {
            if (ch.succeeded()) {
                SQLConnection c = ch.result();
                Future<Void> f1 = Future.future();
                c.setAutoCommit(false, f1.completer());
                f1.compose(o -> {
                    Future<ResultSet> f2 = Future.future();
                    c.queryWithParams("select username from member where username=?",
                            new JsonArray().add(r.getUsername()), f2.completer());
                    return f2;
                }).compose(res -> {
                    Future<ResultSet> f2 = Future.future();
                    if (res.getNumRows() != 0) {
                        f2.fail(ErrorCode.USER_EXIST);
                    } else {
                        c.queryWithParams("select email from member where email=?",
                                new JsonArray().add(r.getEmail()), f2.completer());
                    }
                    return f2;
                }).compose(res -> {
                    if (res.getNumRows() > 0) {
                        return Future.failedFuture(ErrorCode.EMAIL_EXIST);
                    } else {
                        try {
                            r.setPassword(hash(r.getPassword()));
                        } catch (Exception e) {
                            return Future.failedFuture(ErrorCode.SERVER_ERROR);
                        }
                        Future<UpdateResult> f2 = Future.future();
                        c.updateWithParams("insert into member(username,password,email) values (?,?,?)",
                                new JsonArray().add(r.getUsername()).add(r.getPassword()).add(r.getEmail()),
                                f2.completer());
                        return f2;
                    }
                }).compose(res -> {
                    Future<UpdateResult> f2 = Future.future();
                    c.updateWithParams("insert into profile(member_id) values(?)",
                            new JsonArray().add(res.getKeys().getLong(0)), f2.completer());
                    return f2;
                }).compose(res -> {
                    Future<Void> cfut = Future.future();
                    c.commit(cfut.completer());
                    return cfut;
                }).setHandler(ch1 -> {
                    if (ch1.succeeded()) {
                        c.close(close -> {
                            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)));
                        });
                    } else {
                        c.rollback(rr -> {
                            c.close(close -> {
                                h.reply(Json.encode(new GeneralResponse().setCode(ch1.cause().getMessage())
                                        .setMessage(ErrorCode.getMessage(ch1.cause().getMessage()))));
                            });
                        });
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR))));
            }
        });
    });

    vertx.eventBus().consumer("MemberWorker#ProfileUpdate").handler(h -> {
        ProfileUpdateRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), ProfileUpdateRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        Set<ConstraintViolation<ProfileUpdateRequest>> vr = v.validate(req);
        if (!vr.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)
                    .setMessage(vr.iterator().next().getMessage())));
            return;
        }

        ProfileUpdateRequest rq = req;

        client.getConnection(connection -> {
            if (connection.succeeded()) {
                HashMap<String, Object> sm = new HashMap<String, Object>();
                SQLConnection con = connection.result();
                Future<Void> ac = Future.future();
                con.setAutoCommit(false, ac.completer());
                ac.compose(rv -> {
                    Future<ResultSet> lock = Future.future();
                    con.queryWithParams(
                            "select p.* from profile p inner join member m on p.member_id=m.member_id where m.username=? and m.password=? for update",
                            new JsonArray().add(rq.getUsername()).add(rq.getPassword()), lock.completer());
                    return lock;
                }).compose(r -> {
                    if (r.getNumRows() == 0) {
                        return Future.failedFuture(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    }
                    long member_id = r.getRows().iterator().next().getLong("member_id");
                    Future<UpdateResult> up = Future.future();
                    con.updateWithParams(
                            "update profile set name=?, phone=?, address=?, company_name=?, company_address=? where member_id=?",
                            new JsonArray().add(rq.getName()).add(rq.getPhone()).add(rq.getAddress())
                                    .add(rq.getCompanyName()).add(rq.getCompanyAddress()).add(member_id),
                            up.completer());
                    return up;
                }).compose(ok -> {
                    Future<Void> commitFu = Future.future();
                    con.commit(commitFu.completer());
                    return commitFu;
                }).setHandler(th -> {
                    if (th.succeeded()) {
                        con.close(cr -> {
                            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)));
                        });
                    } else {
                        con.rollback(rh -> {
                            con.close(cl -> {
                                h.reply(Json.encode(new GeneralResponse().setCode(th.cause().getMessage())
                                        .setMessage(ErrorCode.getMessage(th.cause().getMessage()))));
                            });
                        });
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR))));
            }
        });
    });

    vertx.eventBus().consumer("MemberWorker#GetProfile").handler(h -> {
        ProfileRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), ProfileRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }

        Set<ConstraintViolation<ProfileRequest>> rV = v.validate(req);

        if (!rV.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }

        final ProfileRequest r = req;

        client.getConnection(cH -> {
            if (cH.succeeded()) {
                SQLConnection c = cH.result();
                Future<Void> f = Future.future();
                c.setAutoCommit(true, f.completer());
                f.compose(res -> {
                    Future<ResultSet> f0 = Future.future();
                    c.queryWithParams("select member_id from member m where m.username=? and m.password=?",
                            new JsonArray().add(r.getUsername()).add(r.getPassword()), f0.completer());
                    return f0;
                }).compose(res -> {
                    Future<ResultSet> f0 = Future.future();
                    if (res.getNumRows() <= 0) {
                        f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    } else {
                        c.queryWithParams("select * from profile where member_id=?",
                                new JsonArray().add(res.getRows().iterator().next().getLong("member_id")),
                                f0.completer());
                    }
                    return f0;
                }).setHandler(rh -> {
                    c.close();
                    if (rh.succeeded()) {
                        h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)
                                .setData(rh.result().getRows().get(0))));
                    } else {
                        h.reply(Json.encode(new GeneralResponse().setCode(rh.cause().getMessage())
                                .setMessage(ErrorCode.getMessage(rh.cause().getMessage()))));
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR))));
            }
        });
    });

    vertx.eventBus().consumer("MemberWorker#ChangePassword").handler(h -> {
        ChangePasswordRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), ChangePasswordRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        Set<ConstraintViolation<ChangePasswordRequest>> rV = v.validate(req);
        if (!rV.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        final ChangePasswordRequest r = req;

        client.getConnection(connection -> {
            if (connection.succeeded()) {
                SQLConnection c = connection.result();
                Future<Void> f1 = Future.future();
                c.setAutoCommit(false, f1.completer());
                f1.compose(vo -> {
                    Future<ResultSet> f = Future.future();
                    c.queryWithParams("select member_id from member where username=? and password=? for update",
                            new JsonArray().add(r.getUsername()).add(r.getPassword()), f.completer());
                    return f;
                }).compose(res -> {
                    Future<UpdateResult> f0 = Future.future();
                    if (res.getNumRows() <= 0) {
                        f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    } else {
                        long member_id = res.getRows().iterator().next().getLong("member_id");
                        String hash = null;
                        try {
                            hash = hash(r.getNewPassword());
                        } catch (Exception e) {
                            return Future.failedFuture(ErrorCode.SERVER_ERROR);
                        }
                        c.updateWithParams("update member set password=? where member_id=?",
                                new JsonArray().add(hash).add(member_id), f0.completer());
                    }
                    return f0;
                }).compose(res -> {
                    Future<Void> cf = Future.future();
                    c.commit(cf.completer());
                    return cf;
                }).setHandler(ch -> {
                    if (ch.succeeded()) {
                        c.close();
                        h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)));
                    } else {
                        ch.cause().printStackTrace();
                        c.rollback(rh -> {
                            c.close();
                            h.reply(Json.encode(new GeneralResponse().setCode(ch.cause().getMessage())
                                    .setMessage(ErrorCode.getMessage(ch.cause().getMessage()))));
                        });
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR))));
            }
        });
    });

    vertx.eventBus().consumer("MembrWorker#AddAsset").handler(h -> {
        AddAssetRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), AddAssetRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        Set<ConstraintViolation<AddAssetRequest>> res = v.validate(req);
        if (!res.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)
                    .setMessage(res.iterator().next().getMessage())));
            return;
        }

        AddAssetRequest r = req;

        client.getConnection(connection -> {
            if (connection.succeeded()) {
                SQLConnection con = connection.result();
                Future<Void> f = Future.future();
                con.setAutoCommit(false, f.completer());
                f.compose(vo -> {
                    Future<ResultSet> f1 = Future.future();
                    con.queryWithParams("select * from member where username=? and password=?",
                            new JsonArray().add(r.getUsername()).add(r.getPassword()), f1.completer());
                    return f1;
                }).compose(re -> {
                    Future<UpdateResult> f1 = Future.future();
                    if (re.getNumRows() <= 0) {
                        System.out.println(Json.encode(re));
                        System.out.println(Json.encode(r));
                        f1.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    } else {
                        long member_id = re.getRows().iterator().next().getLong("member_id");
                        con.updateWithParams(
                                "insert into assets (member_id,debit_credit,asset_name,asset_value,date_time,description) values(?,?,?,?,?,?)",
                                new JsonArray().add(member_id).add(r.getDebitCredit()).add(r.getAssetName())
                                        .add(r.getAssetValue()).add(mysqlFormat.format(new Date()))
                                        .add(r.getDescription()),
                                f1.completer());
                    }
                    return f1;
                }).compose(re -> {
                    Future<Void> end = Future.future();
                    con.commit(end.completer());
                    return end;
                }).setHandler(ch -> {
                    if (ch.succeeded()) {
                        con.close();
                        h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)));
                    } else {
                        con.rollback(rh -> {
                            con.close();
                            h.reply(Json.encode(new GeneralResponse().setCode(ch.cause().getMessage())
                                    .setMessage(ErrorCode.getMessage(ch.cause().getMessage()))));
                        });
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR))));
            }
        });
    });

    vertx.eventBus().consumer("AssetWorker#GetAsset").handler(h -> {

        GetAssetRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), GetAssetRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        Set<ConstraintViolation<GetAssetRequest>> res = v.validate(req);
        if (!res.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)
                    .setMessage(res.iterator().next().getMessage())));
            return;
        }

        GetAssetRequest r = req;

        client.getConnection(connection -> {
            if (connection.succeeded()) {
                SQLConnection c = connection.result();
                Future<Void> vo = Future.future();
                c.setAutoCommit(true, vo.completer());
                vo.compose(re -> {
                    Future<ResultSet> f0 = Future.future();
                    c.queryWithParams("select member_id from member where username=? and password=?",
                            new JsonArray().add(r.getUsername()).add(r.getPassword()), f0.completer());
                    return f0;
                }).compose(re -> {
                    Future<ResultSet> f0 = Future.future();
                    if (re.getNumRows() <= 0) {
                        f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    } else {
                        long member_id = re.getRows().iterator().next().getLong("member_id");
                        c.queryWithParams("select * from assets where member_id=?",
                                new JsonArray().add(member_id), f0.completer());
                    }
                    return f0;
                }).setHandler(resp -> {
                    if (resp.succeeded()) {
                        h.reply(Json.encodePrettily(new GeneralResponse().setCode(ErrorCode.COMPLETE)
                                .setData(resp.result().getRows())));
                    } else {
                        h.reply(Json.encode(new GeneralResponse().setCode(resp.cause().getMessage())
                                .setMessage(ErrorCode.getMessage(resp.cause().getMessage()))));
                    }
                    c.close();
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(connection.cause().getMessage())));
            }
        });
    });

    vertx.eventBus().consumer("AssetWorker#UpdateAsset").handler(h -> {

        UpdateAssetRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), UpdateAssetRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }

        Set<ConstraintViolation<UpdateAssetRequest>> res = v.validate(req);

        if (!res.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)
                    .setMessage(res.iterator().next().getMessage())));
            return;
        }

        final UpdateAssetRequest r = req;

        client.getConnection(connection -> {
            if (connection.succeeded()) {
                SQLConnection con = connection.result();
                Future<Void> f = Future.future();
                con.setAutoCommit(false, f.completer());
                f.compose(vo -> {
                    Future<ResultSet> f0 = Future.future();
                    con.queryWithParams("select member_id from member where username=? and password=?",
                            new JsonArray().add(r.getUsername()).add(r.getPassword()), f0.completer());
                    return f0;
                }).compose(rs -> {
                    Future<ResultSet> f0 = Future.future();
                    if (rs.getNumRows() <= 0) {
                        f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    } else {
                        long member_id = rs.getRows().iterator().next().getLong("member_id");
                        con.queryWithParams("select * from assets where asset_id=? and member_id=? for update",
                                new JsonArray().add(r.getAssetId()).add(member_id), f0.completer());
                    }
                    return f0;
                }).compose(rs -> {
                    Future<UpdateResult> f0 = Future.future();
                    con.updateWithParams(
                            "update assets set debit_credit=?,asset_name=?,asset_value=?,date_time=?,description=? where asset_id=?",
                            new JsonArray().add(r.getDebitCredit()).add(r.getAssetName()).add(r.getAssetValue())
                                    .add(mysqlFormat.format(new Date())).add(r.getDescription())
                                    .add(r.getAssetId()),
                            f0.completer());
                    return f0;
                }).compose(rs -> {
                    Future<Void> cf = Future.future();
                    con.commit(cf.completer());
                    return cf;
                }).setHandler(sh -> {
                    if (sh.succeeded()) {
                        con.close();
                        h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)));
                    } else {
                        con.rollback(rh -> {
                            con.close();
                            h.reply(Json.encode(new GeneralResponse().setCode(sh.cause().getMessage())
                                    .setMessage(ErrorCode.getMessage(sh.cause().getMessage()))));
                        });
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)));
            }
        });
    });

    fut.complete();
}