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

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

Introduction

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

Prototype

@CacheReturn
T body();

Source Link

Document

The body of the message.

Usage

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

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {//from  ww  w  . j  a  v a  2 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 "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", "")));
    });/*  w  w w  .  ja  v  a 2  s.co  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.notizwerk.Consumer.java

License:Open Source License

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

    setUpFileSystem(v -> {/*ww  w.j  av  a2  s .co m*/
        vertx.eventBus().consumer("consumer", (Message<JsonObject> msg) -> {
            messagesInTick++;
            receivedMessages++;
            file.write(Buffer.buffer(msg.body().encode()));
            msg.reply("ok");
        });
        vertx.setPeriodic(REPORT_DELAY_IN_MSEC, (id) -> {
            long messageRate = Math.floorDiv(messagesInTick * 1000, REPORT_DELAY_IN_MSEC);
            messagesInTick = 0;
            JsonObject stats = new JsonObject().put("name", name).put("id", name)
                    .put("timestamp", AppStarter.TIME_FORMATTER.format(ZonedDateTime.now()))
                    .put("messageRate", messageRate).put("receivedMessages", receivedMessages);
            file.write(Buffer.buffer(stats.encode() + String.format("%n")));
            vertx.eventBus().publish("consumer.stats", stats);
        });
        startFuture.complete();
    });
}

From source file:de.notizwerk.Producer.java

License:Open Source License

@Override
public void start() throws Exception {

    setUpFileSystem(v -> {/*from   www.j  av  a2 s .com*/
        vertx.setPeriodic(REPORT_DELAY_IN_MSEC, this::report);
        vertx.setTimer(SEND_DELAY_IN_MSEC, this::generateAndSend);
        vertx.eventBus().consumer("producer.control", (Message<JsonObject> msg) -> {
            String action = msg.headers().get("action");
            switch (action) {
            case "startSending":
                this.sendingActive = true;
                break;
            case "stopSending":
                this.sendingActive = false;
                break;
            case "clearStats":
                this.sentMessages = 0;
                this.generatedMessages = 0;
                this.undeliveredMessages = 0;
                this.generatedMessagesInTick = 0;
                break;
            case "throttle":
                this.msgPerSec = msg.body().getLong("throttle", -1l);
                break;
            }
        });
    });

}

From source file:de.openflorian.alarm.AlarmContextVerticle.java

License:Open Source License

/**
 * Queue Handler: {@link EventBusAddresses.ALARM_INCURRED}
 * // ww  w. j a  v a  2 s . co m
 * @param msg
 */
private void handleAlarm(Message<Object> msg) {
    final Operation operationToAlarm = (Operation) msg.body();
    if (currentOperation != null && !currentOperation.equals(operationToAlarm)) {
        log.error("Recieved operation cannot be alarmed. Another operation is active: " + currentOperation);
        return;
    }
    currentOperation = operationToAlarm;
    if (currentOperation.getId() == 0) {
        try {
            currentOperation.setIncurredAt(new Date());
            currentOperation = new OperationDao().insert(currentOperation);
        } catch (final Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    log.info("Alarm incurred: " + currentOperation);
}

From source file:de.openflorian.alarm.AlarmContextVerticle.java

License:Open Source License

/**
 * Queue Handler: {@link EventBusAddresses.ALARM_INCURRED}
 * /*  ww w.  j ava  2  s .  c om*/
 * @param msg
 */
private void handleTakenOver(Message<Object> msg) {
    final Operation o = (Operation) msg.body();
    if (currentOperation.equals(o)) {
        try {
            currentOperation.setTakenOverAt(new Date());
            new OperationDao().update(currentOperation);

            log.info("Current operation successfuly resetted.");
        } catch (final Exception e) {
            log.error(e.getMessage(), e);
        }
    } else {
        if (currentOperation == null)
            log.error("Operation recieved does not match the currently alarmed operation");
        else
            log.error("No operation alarmed currently.");
    }
}

From source file:de.openflorian.alarm.AlarmContextVerticle.java

License:Open Source License

/**
 * Queue Handler: {@link EventBusAddresses.ALARM_INCURRED}
 * /*w  w  w.  jav a 2s  .com*/
 * @param msg
 */
private void handleDispatched(Message<Object> msg) {
    final Operation o = (Operation) msg.body();
    if (currentOperation.equals(o)) {
        try {
            currentOperation.setDispatchedAt(new Date());
            new OperationDao().update(currentOperation);

            this.currentOperation = null;
            log.info("Current operation successfuly resetted.");
        } catch (final Exception e) {
            log.error(e.getMessage(), e);
        }
    } else {
        if (currentOperation == null)
            log.error("Operation recieved does not match the currently alarmed operation");
        else
            log.error("No operation alarmed currently.");
    }
}

From source file:de.openflorian.alarm.alert.AbstractAlerter.java

License:Open Source License

/**
 * Alerting delegate for VertX messages.
 *
 * @param msg/* www.j av  a2 s.  c  o m*/
 */
public void alert(Message<Object> msg) {
    try {
        final Operation operation = (Operation) msg.body();
        alert(operation);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:de.openflorian.alarm.archive.AlarmFaxArchiver.java

License:Open Source License

/**
 * Takes given <code>event</code> and moves the parsed and transformed Alarm
 * Fax TIF and TXT files to the/*from   ww  w  .  j a va  2  s  .  co m*/
 * {@link AlarmFaxArchiver#CONFIG_ARCHIVATION_DIRECTORY}
 * 
 * @param event
 */
private void archive(Message<Object> msg) {
    final String toArchive = msg.body().toString();

    if (log.isDebugEnabled())
        log.debug("Archiving file: " + toArchive);

    final File toArchiveFile = new File(toArchive);

    if (toArchiveFile.exists()) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
        try {
            final String archiveTarget = String.format("%s%s%s_%s", faxArchivationDirectory, File.separator,
                    format.format(new Date()), toArchiveFile.getName());
            if (log.isDebugEnabled())
                log.debug("Archiving target: " + archiveTarget);

            FileUtils.moveFile(toArchiveFile, new File(archiveTarget));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    } else {
        log.error("File does not exist: " + toArchive);
    }
}

From source file:de.openflorian.alarm.parser.AlarmFaxParserVerticle.java

License:Open Source License

/**
 * Parses given file from <code>event</code> and extracts
 * /* ww  w .ja  va 2s.  c  o  m*/
 * @param msg
 * @throws FileNotFoundException
 * @returns {@link Operation}
 */
public void parse(Message<Object> msg) {
    final AlarmFaxEvent event = (AlarmFaxEvent) msg.body();

    if (firstParserResponsable == null)
        throw new IllegalStateException("No alarm fax parser responsable chain available.");

    final File inputFile = event.getResultFile();
    if (inputFile.exists() && inputFile.canRead()) {
        try {
            log.debug("Parsing file: " + inputFile.getAbsolutePath());
            final Operation op = new Operation();

            final byte[] encoded = Files.readAllBytes(event.getResultFile().toPath());
            final String fax = new String(encoded, "UTF-8");
            parseFax(fax, op);

            OpenflorianContext.vertx().eventBus().send(EventBusAddresses.ARCHIVE_FILE,
                    inputFile.getAbsolutePath());

            OpenflorianContext.vertx().eventBus().publish(EventBusAddresses.ALARM_INCURRED, op);
        } catch (final IOException e) {
            log.error(e.getMessage(), e);
        } catch (final Exception e) {
            log.error(e.getMessage(), e);
        }
    } else {
        log.error("Given file '" + inputFile.getAbsolutePath() + "' is not readable or does not exist!");
    }
}