Example usage for io.vertx.core.eventbus Message reply

List of usage examples for io.vertx.core.eventbus Message reply

Introduction

In this page you can find the example usage for io.vertx.core.eventbus Message reply.

Prototype

default void reply(@Nullable Object message) 

Source Link

Document

Reply to this message.

Usage

From source file:com.groupon.vertx.redis.RedisCommandHandler.java

License:Apache License

private void setCommandResponseHandler(final List<RedisCommand> redisCommands,
        final Message<JsonObject> command, final boolean isMulti) {
    for (final RedisCommand redisCommand : redisCommands) {
        final Future<JsonObject> finalResult = Future.future();
        finalResult.setHandler(new Handler<AsyncResult<JsonObject>>() {
            public void handle(AsyncResult<JsonObject> commandResponse) {
                log.trace("handleCommand", "reply", new String[] { "command", "response", "isMulti" },
                        redisCommand.toString(), commandResponse, isMulti);
                if (commandResponse.succeeded()) {
                    command.reply(commandResponse.result());
                } else {
                    String cause = commandResponse.cause() != null ? commandResponse.cause().getMessage()
                            : "unknown";
                    command.reply(buildReply("error", null, cause));
                }//from   ww w .  j av a  2  s. c  o  m
            }
        });
        redisCommand.commandResponse(finalResult);
    }
}

From source file:com.jedlab.vertee.DatabaseServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {//from  w  w  w  .j  ava 2 s .co m
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {

        case "persist": {
            service.persist((io.vertx.core.json.JsonObject) json.getValue("document"), createHandler(msg));
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.reply(new ServiceException(500, t.getMessage()));
        throw t;
    }
}

From source file:com.pluralsight.dockerproductionaws.portfolio.PortfolioServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {// w  ww.  j a  v  a 2 s  . co m
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {
        case "getPortfolio": {
            service.getPortfolio(res -> {
                if (res.failed()) {
                    if (res.cause() instanceof ServiceException) {
                        msg.reply(res.cause());
                    } else {
                        msg.reply(new ServiceException(-1, res.cause().getMessage()));
                    }
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        case "buy": {
            service.buy(json.getValue("amount") == null ? null : (json.getLong("amount").intValue()),
                    (io.vertx.core.json.JsonObject) json.getValue("quote"), res -> {
                        if (res.failed()) {
                            if (res.cause() instanceof ServiceException) {
                                msg.reply(res.cause());
                            } else {
                                msg.reply(new ServiceException(-1, res.cause().getMessage()));
                            }
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        case "sell": {
            service.sell(json.getValue("amount") == null ? null : (json.getLong("amount").intValue()),
                    (io.vertx.core.json.JsonObject) json.getValue("quote"), res -> {
                        if (res.failed()) {
                            if (res.cause() instanceof ServiceException) {
                                msg.reply(res.cause());
                            } else {
                                msg.reply(new ServiceException(-1, res.cause().getMessage()));
                            }
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        case "evaluate": {
            service.evaluate(createHandler(msg));
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.reply(new ServiceException(500, t.getMessage()));
        throw t;
    }
}

From source file:com.reachauto.account.AccountServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {/* w  w  w  .j a v  a  2  s.  com*/
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {
        case "addAccount": {
            service.addAccount(
                    json.getJsonObject("account") == null ? null
                            : new com.reachauto.account.Account(json.getJsonObject("account")),
                    createHandler(msg));
            break;
        }
        case "deleteAccount": {
            service.deleteAccount(json.getValue("id") == null ? null : (json.getLong("id").intValue()),
                    createHandler(msg));
            break;
        }
        case "updateAccount": {
            service.updateAccount(json.getJsonObject("account") == null ? null
                    : new com.reachauto.account.Account(json.getJsonObject("account")), res -> {
                        if (res.failed()) {
                            if (res.cause() instanceof ServiceException) {
                                msg.reply(res.cause());
                            } else {
                                msg.reply(new ServiceException(-1, res.cause().getMessage()));
                            }
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        case "retrieveAccount": {
            service.retrieveAccount(json.getValue("id") == null ? null : (json.getLong("id").intValue()),
                    res -> {
                        if (res.failed()) {
                            if (res.cause() instanceof ServiceException) {
                                msg.reply(res.cause());
                            } else {
                                msg.reply(new ServiceException(-1, res.cause().getMessage()));
                            }
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.reply(new ServiceException(500, t.getMessage()));
        throw t;
    }
}

From source file:com.reachauto.device.DeviceServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {//  w w  w. j  a va 2  s  .  co  m
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {
        case "addDevice": {
            service.addDevice(
                    json.getJsonObject("device") == null ? null
                            : new com.reachauto.device.Device(json.getJsonObject("device")),
                    createHandler(msg));
            break;
        }
        case "deleteDevice": {
            service.deleteDevice((java.lang.String) json.getValue("id"), createHandler(msg));
            break;
        }
        case "updateDevice": {
            service.updateDevice(json.getJsonObject("device") == null ? null
                    : new com.reachauto.device.Device(json.getJsonObject("device")), res -> {
                        if (res.failed()) {
                            if (res.cause() instanceof ServiceException) {
                                msg.reply(res.cause());
                            } else {
                                msg.reply(new ServiceException(-1, res.cause().getMessage()));
                            }
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        case "retrieveDevice": {
            service.retrieveDevice((java.lang.String) json.getValue("id"), res -> {
                if (res.failed()) {
                    if (res.cause() instanceof ServiceException) {
                        msg.reply(res.cause());
                    } else {
                        msg.reply(new ServiceException(-1, res.cause().getMessage()));
                    }
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.reply(new ServiceException(500, t.getMessage()));
        throw t;
    }
}

From source file:com.reachauto.product.ProductServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {//from   w  ww .ja  v a2  s .c  o  m
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {
        case "addProduct": {
            service.addProduct(
                    json.getJsonObject("product") == null ? null
                            : new com.reachauto.product.Product(json.getJsonObject("product")),
                    createHandler(msg));
            break;
        }
        case "deleteProduct": {
            service.deleteProduct(json.getValue("id") == null ? null : (json.getLong("id").intValue()),
                    createHandler(msg));
            break;
        }
        case "updateProduct": {
            service.updateProduct(json.getJsonObject("product") == null ? null
                    : new com.reachauto.product.Product(json.getJsonObject("product")), res -> {
                        if (res.failed()) {
                            if (res.cause() instanceof ServiceException) {
                                msg.reply(res.cause());
                            } else {
                                msg.reply(new ServiceException(-1, res.cause().getMessage()));
                            }
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        case "retrieveProduct": {
            service.retrieveProduct(json.getValue("id") == null ? null : (json.getLong("id").intValue()),
                    res -> {
                        if (res.failed()) {
                            if (res.cause() instanceof ServiceException) {
                                msg.reply(res.cause());
                            } else {
                                msg.reply(new ServiceException(-1, res.cause().getMessage()));
                            }
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.reply(new ServiceException(500, t.getMessage()));
        throw t;
    }
}

From source file:com.sagalasan.swivel.service.CurrentTimeService.java

License:Apache License

private void sendTime(Message message) {
    message.reply(new Time().setTime(System.currentTimeMillis()));
}

From source file:com.test.mailer.MailerServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {//from  w  w w .j  ava2s . co m
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {

        case "sendAttachment": {
            service.sendAttachment((java.lang.String) json.getValue("To"),
                    json.getJsonObject("attachment") == null ? null
                            : new io.vertx.ext.mail.MailAttachment(json.getJsonObject("attachment")),
                    (java.lang.String) json.getValue("Title"), createHandler(msg));
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.reply(new ServiceException(500, t.getMessage()));
        throw t;
    }
}

From source file:de.elsibay.EbbTicketShowcase.java

License:Open Source License

@Override
public void start(Future<Void> startFuture) throws Exception {

    SessionStore sessionStore = LocalSessionStore.create(vertx);
    Router backendRouter = Router.router(vertx);
    backendRouter.route().handler(LoggerHandler.create(LoggerHandler.DEFAULT_FORMAT));
    CookieHandler cookieHandler = CookieHandler.create();
    SessionHandler sessionHandler = SessionHandler.create(sessionStore);
    // the CORS OPTION request must not set cookies
    backendRouter.get().handler(cookieHandler);
    backendRouter.get().handler(sessionHandler);
    backendRouter.post().handler(cookieHandler);
    backendRouter.post().handler(sessionHandler);

    // setup CORS
    CorsHandler corsHandler = CorsHandler.create("http(s)?://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT)
            .allowCredentials(true).allowedHeader(HttpHeaders.ACCEPT.toString())
            .allowedHeader(HttpHeaders.ORIGIN.toString()).allowedHeader(HttpHeaders.AUTHORIZATION.toString())
            .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()).allowedHeader(HttpHeaders.COOKIE.toString())
            .exposedHeader(HttpHeaders.SET_COOKIE.toString()).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.PUT).allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.DELETE);

    // setup event bus bridge
    TicketEventbusBridge sebb = new TicketEventbusBridge(sessionStore);
    backendRouter.mountSubRouter("/eventbus", sebb.route(vertx));

    // dummy eventbus services
    vertx.eventBus().consumer("ping", (Message<JsonObject> msg) -> {
        msg.reply(new JsonObject().put("answer", "pong " + msg.body().getString("text", "")));
    });//from  w  w  w. j a v  a2s  .c  o m

    vertx.setPeriodic(5000, id -> {
        vertx.eventBus().send("topic", new JsonObject().put("timestamp", new Date().getTime()));
    });

    // session manager for login
    backendRouter.route("/api/*").handler(corsHandler);
    backendRouter.route("/api/*").method(HttpMethod.POST).method(HttpMethod.PUT).handler(BodyHandler.create());

    backendRouter.route("/api/session").handler((RoutingContext rc) -> {
        JsonObject user = rc.getBodyAsJson();
        String sessionId = rc.session().id();
        rc.session().put("user", user);
        rc.response().end(user.copy().put("sessionId", sessionId).encodePrettily());
    });

    // dummy ping REST service
    backendRouter.route("/api/ping").handler((RoutingContext rc) -> {
        JsonObject replyMsg = new JsonObject();
        replyMsg.put("timestamp", new Date().getTime());
        Cookie sessionCookie = rc.getCookie(SessionHandler.DEFAULT_SESSION_COOKIE_NAME);
        if (sessionCookie != null) {
            replyMsg.put("sessionId", sessionCookie.getValue());
        }
        rc.response().end(replyMsg.encode());
    });

    // start backend on one port
    vertx.createHttpServer().requestHandler(backendRouter::accept).listen(BACKENDSERVER_PORT,
            BACKENDSERVER_HOST, (AsyncResult<HttpServer> async) -> {
                System.out
                        .println(async.succeeded() ? "Backend Server started" : "Backend Server start FAILED");
            });

    // static files on other port
    Router staticFilesRouter = Router.router(vertx);
    staticFilesRouter.route("/*").handler(StaticHandler.create("src/main/www").setCachingEnabled(false));
    vertx.createHttpServer().requestHandler(staticFilesRouter::accept).listen(WEBSERVER_PORT, WEBSERVER_HOST,
            (AsyncResult<HttpServer> async) -> {
                System.out.println(async.succeeded()
                        ? "Web Server started\ngoto http://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT + "/"
                        : "Web Server start FAILED");
            });
}

From source file:de.neofonie.deployer.DeployerVerticle.java

License:Open Source License

/**
 * Iterate and deploy verticles//from  ww  w.j av a 2  s . c  o m
 */
private void deployVerticle(final Message<JsonObject> event) {

    // iterate over all candidates to be deployed
    Set<String> candidates = this.workingCopy.fieldNames();

    // detach from underlying json
    Map<String, JsonObject> initiants = new HashMap<>();
    candidates.forEach(id -> {
        JsonObject info = this.workingCopy.getJsonObject(id);
        JsonArray dependsOn = info.getJsonArray("dependsOn");
        if (dependsOn != null && deployed.getList().containsAll(dependsOn.getList()) || dependsOn == null
                || dependsOn.isEmpty()) {
            initiants.put(id, info);
        }
    });

    // remove the initiants
    initiants.keySet().forEach(id -> this.workingCopy.remove(id));

    // setup latch for the reply
    CountDownLatch latch = new CountDownLatch(initiants.size());
    if (initiants.isEmpty()) {
        event.reply(Boolean.TRUE);
        return;
    }

    // run over all dependencies
    initiants.forEach((id, info) -> {

        // get the name of the verticle
        String name = info.getString("name");
        final JsonObject localConfig = new JsonObject();
        localConfig.mergeIn(globalConfig);
        localConfig.mergeIn(info.getJsonObject("config", new JsonObject()));

        Handler<AsyncResult<String>> handler = innerEvent -> {
            if (innerEvent.succeeded()) {
                // add service to deployed-list
                deployed.add(id);

                // re-emit
                vertx.eventBus().send(LOOPBACK, workingCopy, (AsyncResult<Message<Boolean>> recursiveReply) -> {
                    // always decrease latch
                    latch.countDown();

                    if (recursiveReply.succeeded() && recursiveReply.result().body()) {
                        if (latch.getCount() == 0) {
                            event.reply(recursiveReply.result().body() & Boolean.TRUE);
                        }
                    } else {
                        event.fail(500, this.getFailure(id, recursiveReply));
                    }
                });

            } else {
                event.fail(500, id + " >> " + innerEvent.cause().getMessage());
            }
        };

        LOG.log(Level.INFO, "Deploying: ''{0}''", new Object[] { id });
        DeploymentOptions deploymentOptions = new DeploymentOptions(info);
        vertx.deployVerticle(name, deploymentOptions.setConfig(localConfig), handler);
    });
}