Example usage for io.vertx.core.eventbus EventBus consumer

List of usage examples for io.vertx.core.eventbus EventBus consumer

Introduction

In this page you can find the example usage for io.vertx.core.eventbus EventBus consumer.

Prototype

<T> MessageConsumer<T> consumer(String address);

Source Link

Document

Create a message consumer against the specified address.

Usage

From source file:co.runrightfast.vertx.core.RunRightFastVerticle.java

License:Apache License

/**
 *
 * @param <REQ>//from  ww  w .  j a v  a 2  s .c o  m
 * @param <RESP>
 * @param config
 * @return MessageConsumer
 */
protected <REQ extends Message, RESP extends Message> MessageConsumerRegistration<REQ, RESP> registerMessageConsumer(
        @NonNull final MessageConsumerConfig<REQ, RESP> config) {
    Preconditions.checkState(
            !messageConsumerRegistrations.containsKey(config.getAddressMessageMapping().getAddress()));
    final EventBus eventBus = vertx.eventBus();
    registerMessageCodecs(config);

    final String address = config.getAddressMessageMapping().getAddress();
    final MessageConsumer<REQ> consumer = config.isLocal() ? eventBus.localConsumer(address)
            : eventBus.consumer(address);
    consumer.completionHandler(config.getCompletionHandler()
            .map(handler -> messageConsumerCompletionHandler(address, Optional.of(handler), config))
            .orElseGet(() -> messageConsumerCompletionHandler(address, Optional.empty(), config)));
    consumer.endHandler(config.getEndHandler()
            .map(handler -> messageConsumerEndHandler(address, Optional.of(handler), config))
            .orElseGet(() -> messageConsumerEndHandler(address, Optional.empty(), config)));
    config.getExceptionHandler().ifPresent(consumer::exceptionHandler);
    consumer.handler(messageConsumerHandler(config));

    final String processSpecificAddress = config.getAddressMessageMapping().getProcessSpecificAddress();
    final MessageConsumer<REQ> processSpecificConsumer = config.isLocal()
            ? eventBus.localConsumer(processSpecificAddress)
            : eventBus.consumer(processSpecificAddress);
    processSpecificConsumer.completionHandler(config.getCompletionHandler().map(
            handler -> messageConsumerCompletionHandler(processSpecificAddress, Optional.of(handler), config))
            .orElseGet(
                    () -> messageConsumerCompletionHandler(processSpecificAddress, Optional.empty(), config)));
    processSpecificConsumer.endHandler(config.getEndHandler()
            .map(handler -> messageConsumerEndHandler(processSpecificAddress, Optional.of(handler), config))
            .orElseGet(() -> messageConsumerEndHandler(processSpecificAddress, Optional.empty(), config)));
    config.getExceptionHandler().ifPresent(processSpecificConsumer::exceptionHandler);
    processSpecificConsumer.handler(messageConsumerHandler(config));

    final MessageConsumerRegistration<REQ, RESP> messageConsumerRegistration = MessageConsumerRegistration
            .<REQ, RESP>builder().messageConsumer(consumer)
            .processSpecificMessageConsumer(processSpecificConsumer).config(config).build();
    messageConsumerRegistrations = ImmutableMap.<String, MessageConsumerRegistration<?, ?>>builder()
            .putAll(messageConsumerRegistrations).put(config.address(), messageConsumerRegistration).build();
    return messageConsumerRegistration;
}

From source file:com.mycompany.sharedwhiteboard.Server.java

@Override
public void start() throws Exception {

    Router router = Router.router(vertx);

    // Allow events for the designated addresses in/out of the event bus bridge
    BridgeOptions opts = new BridgeOptions()
            .addInboundPermitted(new PermittedOptions().setAddress("chat.to.server"))
            .addOutboundPermitted(new PermittedOptions().setAddress("chat.to.client"));

    // Create the event bus bridge and add it to the router.
    SockJSHandler ebHandler = SockJSHandler.create(vertx).bridge(opts);
    router.route("/eventbus/*").handler(ebHandler);

    // Create a router endpoint for the static content.
    router.route().handler(StaticHandler.create());

    // Start the web server and tell it to use the router to handle requests.
    vertx.createHttpServer().requestHandler(router::accept).listen(8080);

    EventBus eb = vertx.eventBus();

    // Register to listen for messages coming IN to the server
    eb.consumer("chat.to.server").handler(message -> {
        // Send the message back out to all clients with the timestamp prepended.
        eb.publish("chat.to.client", message.body());
    });//www.ja v a 2  s . c o m

}

From source file:com.nasa.ESWorkerVerticle.java

@Override
public void start() throws Exception {

    EventBus eb = vertx.eventBus();

    eb.consumer("bus.symptoms").handler(message -> {

        String text = ((JsonObject) message.body()).getString("text");

        JsonObject result = null;/*from   w  w  w  . ja va2  s .  c o  m*/

        try {
            if (text != null) {
                result = es.getSymptoms(text);
            }
        } catch (Exception ex) {
            result = new JsonObject();
            result.put("symptoms", new JsonArray());
        }

        message.reply(result);
    });

    eb.consumer("bus.conditions").handler(message -> {

        String text = ((JsonObject) message.body()).getString("text");

        JsonObject result = null;

        try {
            if (text != null) {
                result = es.getConditions(text);
            }
        } catch (Exception ex) {
            result = new JsonObject();
            result.put("conditions", new JsonArray());
        }

        message.reply(result);
    });

    eb.consumer("bus.map.weather").handler(message -> {

        String lat = ((JsonObject) message.body()).getString("lat");
        String lon = ((JsonObject) message.body()).getString("lon");
        String zoom = ((JsonObject) message.body()).getString("zoom");
        String count = ((JsonObject) message.body()).getString("count");

        JsonObject result = null;

        try {
            if (lat != null && lon != null && zoom != null) {
                result = Transformer.weatherToMap(es.getMap(lat, lon, zoom, count));
            } else {
                throw new IllegalArgumentException("incorrect weather params: " + message.body().toString());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            result = new JsonObject();
            result.put("type", "FeatureCollection");
            result.put("features", new JsonArray());
        }

        message.reply(result);
    });

    eb.consumer("bus.map.pollution").handler(message -> {

        String lat = ((JsonObject) message.body()).getString("lat");
        String lon = ((JsonObject) message.body()).getString("lon");
        String zoom = ((JsonObject) message.body()).getString("zoom");
        String count = ((JsonObject) message.body()).getString("count");

        System.out.println("Worker: " + message.body());

        JsonObject result = null;

        try {
            if (lat != null && lon != null && zoom != null) {
                result = Transformer.pollutionToMap(es.getMap(lat, lon, zoom, count));
            } else {
                throw new IllegalArgumentException("incorrect pollution params: " + message.body().toString());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            result = new JsonObject();
            result.put("type", "FeatureCollection");
            result.put("features", new JsonArray());
        }

        message.reply(result);
    });

    eb.consumer("bus.map.condition").handler(message -> {

        String lat = ((JsonObject) message.body()).getString("lat");
        String lon = ((JsonObject) message.body()).getString("lon");
        String zoom = ((JsonObject) message.body()).getString("zoom");
        String count = ((JsonObject) message.body()).getString("count");

        JsonObject result = null;

        try {
            if (lat != null && lon != null && zoom != null) {
                result = Transformer.conditionToMap(es.getMap(lat, lon, zoom, count));
            } else {
                throw new IllegalArgumentException("incorrect condition params: " + message.body().toString());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            result = new JsonObject();
            result.put("type", "FeatureCollection");
            result.put("features", new JsonArray());
        }

        message.reply(result);
    });

    eb.consumer("bus.check").handler(message -> {

        Float lat = Float.parseFloat(((JsonObject) message.body()).getString("lat"));
        Float lon = Float.parseFloat(((JsonObject) message.body()).getString("lon"));

        JsonObject result = new JsonObject();

        Gson gson = new Gson();

        try {
            JsonArray matchesArr = new JsonArray();

            if (lat != null && lon != null) {
                matchesArr = es.getCheck(lat, lon);
                result.put("conditions", matchesArr);
            }

            OtherOmwClient owm = new OtherOmwClient();
            BreezoMeterClient bm = new BreezoMeterClient();

            JsonObject weatherJ = owm.currentWeather(lat, lon);
            JsonObject pollutionJ = bm.currentAirQualityAtPoint(lat, lon);

            Weather weather = owm.toWeather(weatherJ);
            if (weather != null) {
                result.put("weather", new JsonObject(gson.toJson(weather)));
            }

            Pollution pollution = bm.toPollution(pollutionJ);
            if (pollution != null) {
                result.put("pollution", new JsonObject(gson.toJson(pollution)));
            }

        } catch (Exception ex) {
            result = new JsonObject();
            result.put("conditions", new JsonArray());
            result.put("weather", new JsonObject());
            result.put("pollution", new JsonObject());
        }

        message.reply(result);
    });

    eb.consumer("bus.feedback").handler(message -> {

        JsonObject userFeedback = (JsonObject) message.body();

        JsonObject result = new JsonObject();

        try {
            Gson gson = new Gson();
            Feedback feedback = gson.fromJson(userFeedback.toString(), Feedback.class);

            float lat = feedback.getLocation().getLat();
            float lon = feedback.getLocation().getLon();

            OtherOmwClient owm = new OtherOmwClient();
            JsonObject owmData = owm.currentWeather(lat, lon);
            feedback.setWeather(owm.toWeather(owmData));

            BreezoMeterClient bm = new BreezoMeterClient();
            JsonObject bmData = bm.currentAirQualityAtPoint(lat, lon);
            feedback.setPollution(bm.toPollution(bmData));

            result = es.postFeedback(new JsonObject(gson.toJson(feedback)));
        } catch (Exception ex) {
            ex.printStackTrace();
            result.put("success", false);
        }

        message.reply(result);
    });
}

From source file:com.zanclus.distributed.chat.service.Main.java

License:Apache License

@Override
public void start() throws Exception {

    Router router = Router.router(vertx);

    final EventBus eb = vertx.eventBus();

    eb.consumer("chat.to.server").handler(message -> {
        String timestamp = getDateTimeInstance(SHORT, MEDIUM).format(Date.from(now()));
        eb.publish("chat.to.client", timestamp + ": " + message.body());
    });//from ww w  .j a  v a  2s  . c  o  m

    BridgeOptions opts = new BridgeOptions()
            .addInboundPermitted(new PermittedOptions().setAddress("chat.to.server"))
            .addOutboundPermitted(new PermittedOptions().setAddress("chat.to.client"));

    SockJSHandler ebHandler = SockJSHandler.create(vertx).bridge(opts);
    router.route("/eventbus/*").handler(ebHandler);

    router.route().handler(StaticHandler.create("webroot/").setIndexPage("chat.html"));

    vertx.createHttpServer().requestHandler(router::accept).listen(8000);
}

From source file:de.qreator.matheserver.Start.java

public static void main(String[] s) {
    int port = 8080;
    if (s.length == 1) {
        port = Integer.parseInt(s[0]); // port festlegen: 

    }//from  ww w.  j a  v  a  2 s.  c o m

    Vertx vertx = Vertx.vertx();

    io.vertx.core.http.HttpServer server = vertx.createHttpServer();

    Router router = Router.router(vertx);
    SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
    PermittedOptions[] inboundPermitted = new PermittedOptions[3];
    inboundPermitted[0] = new PermittedOptions().setAddress("matheserver");
    inboundPermitted[1] = new PermittedOptions().setAddress("matheserver.spielfeld");
    inboundPermitted[2] = new PermittedOptions().setAddressRegex("matheserver.spieler\\..+");

    BridgeOptions options = new BridgeOptions();
    for (int i = 0; i < 3; i++) {
        options.addInboundPermitted(inboundPermitted[i]);
        options.addOutboundPermitted(inboundPermitted[i]);
    }

    sockJSHandler.bridge(options);

    router.route("/bridge/*").handler(sockJSHandler);
    router.route("/*").handler(StaticHandler.create()); // webroot unter src/main/resources/webroot
    server.requestHandler(router::accept).listen(port);

    EventBus eb = vertx.eventBus();

    MessageConsumer<JsonObject> consumer = eb.consumer("matheserver");
    consumer.handler(message -> {
        String typ = (message.body()).getString("typ");
        if (typ.equals("einaus")) {
            try {
                Runtime.getRuntime().exec("sudo init 6");
                System.out.println("System wird neu gestartet ...");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    try {
        System.out.println("Spieler bitte mit Browser anmelden unter \nhttp://"
                + InetAddress.getLocalHost().getHostAddress() + ":" + port + "/spieler.html");

    } catch (Exception e) {
        e.printStackTrace();

    }
}

From source file:examples.EventBusExamples.java

License:Open Source License

public void example2(Vertx vertx) {
    EventBus eb = vertx.eventBus();

    MessageConsumer<String> consumer = eb.consumer("news.uk.sport");
    consumer.handler(message -> {/*w  w w  . j  a  va 2  s.c  om*/
        System.out.println("I have received a message: " + message.body());
    });
}

From source file:examples.EventBusExamples.java

License:Open Source License

public void example8(EventBus eventBus) {
    MessageConsumer<String> consumer = eventBus.consumer("news.uk.sport");
    consumer.handler(message -> {/*from ww w.  ja  v a2 s.  c  om*/
        System.out.println("I have received a message: " + message.body());
        message.reply("how interesting!");
    });
}

From source file:org.apache.tamaya.vertx.TamayaConfigurationProducer.java

License:Apache License

/**
 * Registers a handler for accessing single configuration keys (input: String, reply type: String). If no
 * config createValue is present the consumer will reply with a NOT_FOUND failure.
 * @param address the event bus address to register.
 * @param eventBus the event bus./*from  ww w .j av a2s  .c  o  m*/
 * @return the consumer registered.
 */
public static MessageConsumer<String> registerSingleConfigEntryProvider(String address, EventBus eventBus) {
    MessageConsumer<String> consumer = eventBus.consumer(address);
    consumer.handler(h -> {
        String key = (String) h.body();
        if (key == null) {
            h.fail(HttpResponseStatus.BAD_REQUEST.code(), "Missing config key.");
        } else {
            String value = Configuration.current().getOrDefault(key, null);
            if (value != null) {
                h.reply(value);
            } else {
                h.fail(HttpResponseStatus.NOT_FOUND.code(), "Config key not found: " + key);
            }
        }
    });
    return consumer;
}

From source file:org.apache.tamaya.vertx.TamayaConfigurationProducer.java

License:Apache License

/**
 * Registers a handler for accessing multiple configuration keys (input: String[] (Json),
 * reply type: {@code Map<String,String>} (Json).
 * @param address the event bus address to register.
 * @param eventBus the event bus.//from www  . j a  v a  2  s.co  m
 * @return the consumer registered.
 */
public static MessageConsumer<String> registerMultiConfigEntryProvider(String address, EventBus eventBus) {
    MessageConsumer<String> consumer = eventBus.consumer(address);
    consumer.handler(h -> {
        String val = h.body();
        Configuration config = Configuration.current();
        Map<String, String> entries = new TreeMap<>();
        if (val != null) {
            String[] sections = Json.decodeValue(val, String[].class);
            for (String section : sections) {
                if (section != null) {
                    entries.putAll(config.map(ConfigurationFunctions.section(section)).getProperties());
                }
            }
        } else {
            entries.putAll(config.getProperties());
        }
        h.reply(Json.encode(entries));
    });
    return consumer;
}

From source file:org.apache.tamaya.vertx.TamayaConfigurationProducer.java

License:Apache License

/**
 * Registers a handler for configuring any objects sent via the message bus using Tamaya's injection API.
 * @param address the event bus address to register.
 * @param eventBus the event bus./*w  ww  . java 2s  . c o  m*/
 * @return the consumer registered.
 */
public static MessageConsumer<Object> registerConfigurationInjector(String address, EventBus eventBus) {
    MessageConsumer<Object> consumer = eventBus.consumer(address);
    consumer.handler(h -> {
        Object o = h.body();
        if (o == null) {
            h.fail(HttpResponseStatus.BAD_REQUEST.code(), "Required createObject to configure is missing.");
        } else {
            ConfigurationInjector.getInstance().configure(o);
            h.reply("OK");
        }
    });
    return consumer;
}