Package org.vertx.java.core.eventbus

Examples of org.vertx.java.core.eventbus.EventBus


        obj.putString("address", addr);
        return new JsonArray(new Object[] {obj});
    }

    private void setupEventBusHandlers() {
        EventBus eventBus = vertx.eventBus();

        // register to receive messages sent by the browser to the "translator" address
        eventBus.registerHandler("translator",new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> message) {
                handleTranslationRequest(message);
            }
        });
View Full Code Here


        return (VertxEndpoint) super.getEndpoint();
    }

    @Override
    public boolean process(Exchange exchange, AsyncCallback callback) {
        EventBus eventBus = getEndpoint().getEventBus();
        String address = getEndpoint().getAddress();

        boolean reply = ExchangeHelper.isOutCapable(exchange);
        boolean pubSub = getEndpoint().isPubSub();

        Object body = getVertxBody(exchange);
        if (body != null) {
            if (reply) {
                LOG.debug("Sending to: {} with body: {}", address, body);
                eventBus.send(address, body, new CamelReplyHandler(exchange, callback));
                return false;
            } else {
                if (pubSub) {
                    LOG.debug("Publishing to: {} with body: {}", address, body);
                    eventBus.publish(address, body);
                } else {
                    LOG.debug("Sending to: {} with body: {}", address, body);
                    eventBus.send(address, body);
                }
                callback.done(true);
                return true;
            }
        }
View Full Code Here

    }

    @Override
    public void start() {

        final EventBus eb = vertx.eventBus();
        final String address = "bench.mongodb";

        JsonObject dbConfig = new JsonObject()
                .putString("address", address)
                .putString("db_name", "hello_world")
                .putString("host", "localhost");

        // deploy mongo module
        container.deployModule("io.vertx~mod-mongo-persistor~2.0.0-final", dbConfig);

        // create the yoke app
        new Yoke(this)
                // register the MVEL engine
                .engine("mvel", new MVELEngine("views"))

                // Test 1: JSON serialization
                .use("/json", new Middleware() {
                    @Override
                    public void handle(YokeRequest request, Handler<Object> next) {
                        // For each request, an object mapping the key message to Hello, World! must be instantiated.
                        request.response().end(new JsonObject().putString("message", "Hello, World!"));
                    }
                })
                // Test 2: db
                .use("/db", new Middleware() {
                    @Override
                    public void handle(final YokeRequest request, final Handler<Object> next) {

                        final Random random = ThreadLocalRandom.current();

                        eb.send(address, buildQuery("findone", "world", random.nextInt(10000) + 1), new Handler<Message<JsonObject>>() {
                            @Override
                            public void handle(Message<JsonObject> message) {
                                // get the body
                                final JsonObject body = message.body();

                                if ("ok".equals(body.getString("status"))) {
                                    // json -> string serialization
                                    request.response().end(body.getObject("result"));
                                    return;
                                }

                                next.handle(body.getString("message"));
                            }
                        });
                    }
                })
                // Test 3: queries
                .use("/queries", new Middleware() {
                    @Override
                    public void handle(final YokeRequest request, Handler<Object> next) {

                        final Random random = ThreadLocalRandom.current();

                        // Get the count of queries to run.
                        final int count = parseRequestParam(request, "queries");

                        final Handler<Message<JsonObject>> dbh = new Handler<Message<JsonObject>>() {
                            // how many messages have this handler received
                            int received = 0;
                            // keeps the received messages
                            JsonArray result = new JsonArray();

                            @Override
                            public void handle(Message<JsonObject> message) {
                                // increase the counter
                                received++;

                                // get the body
                                final JsonObject body = message.body();

                                if ("ok".equals(body.getString("status"))) {
                                    // json -> string serialization
                                    result.add(body.getObject("result"));
                                }

                                // end condition
                                if (received == count) {
                                    request.response().end(result);
                                }
                            }
                        };

                        for (int i = 0; i < count; i++) {
                            eb.send(address, buildQuery("findone", "world", random.nextInt(10000) + 1), dbh);
                        }
                    }
                })
                // Test 4: fortune
                .use("/fortunes", new Middleware() {
                    @Override
                    public void handle(final YokeRequest request, final Handler<Object> next) {

                        final List<JsonObject> results = new ArrayList<>();

                        eb.send(address, buildQuery("find", "fortune"), new Handler<Message<JsonObject>>() {
                            @Override
                            public void handle(Message<JsonObject> reply) {
                                String status = reply.body().getString("status");

                                if (status != null) {
                                    if ("ok".equalsIgnoreCase(status)) {
                                        JsonArray itResult = reply.body().getArray("results");
                                        for (Object o : itResult) {
                                            results.add((JsonObject) o);
                                        }
                                        // end condition
                                        results.add(new JsonObject().putNumber("id", 0).putString("message", "Additional fortune added at request time."));
                                        // sort ASC
                                        Collections.sort(results, new Comparator<JsonObject>() {
                                            @Override
                                            public int compare(JsonObject o1, JsonObject o2) {
                                                return o1.getNumber("id").intValue() - o2.getNumber("id").intValue();
                                            }
                                        });
                                        // render
                                        request.put("fortunes", results);
                                        request.response().render("fortunes.mvel", next);
                                        return;
                                    }
                                    if ("more-exist".equalsIgnoreCase(status)) {
                                        JsonArray itResult = reply.body().getArray("results");
                                        for (Object o : itResult) {
                                            results.add((JsonObject) o);
                                        }
                                        // reply asking for more
                                        reply.reply(this);
                                        return;
                                    }
                                }
                                next.handle("error");
                            }
                        });
                    }
                })
                // Test 5: updates
                .use("/updates", new Middleware() {
                    @Override
                    public void handle(final YokeRequest request, final Handler<Object> next) {

                        final Random random = ThreadLocalRandom.current();

                        // Get the count of queries to run.
                        final int count = parseRequestParam(request, "queries");

                        final Handler<Message<JsonObject>> dbh = new Handler<Message<JsonObject>>() {
                            // how many messages have this handler received
                            int received = 0;
                            // keeps the received messages
                            JsonArray worlds = new JsonArray();

                            @Override
                            public void handle(Message<JsonObject> message) {

                                // get the body
                                final JsonObject body = message.body();
                                JsonObject world;

                                if ("ok".equals(body.getString("status"))) {
                                    world = new JsonObject()
                                            .putNumber("id", received)
                                            .putNumber("randomNumber", body.getObject("result").getNumber("randomNumber"));
                                    worlds.add(world);

                                    world.putNumber("randomNumber", random.nextInt(10000) + 1);
                                    eb.send(address, buildUpdate("world", world.getInteger("id"), world.getInteger("randomNumber")));
                                }

                                // increase the counter
                                received++;

                                // end condition
                                if (received == count) {
                                    request.response().end(worlds);
                                }
                            }
                        };

                        for (int i = 0; i < count; i++) {
                            eb.send(address, buildQuery("findone", "world", random.nextInt(10000) + 1), dbh);
                        }
                    }
                })
                // Test 6: plain text
                .use("/plaintext", new Middleware() {
View Full Code Here

public class KitCMS extends Verticle {

    @Override
    public void start() {
        final Config config = new Config(container.config());
        final EventBus eb = vertx.eventBus();
        final FileSystem fileSystem = vertx.fileSystem();

        final RedisClient db = new RedisClient(eb, Config.REDIS_ADDRESS);

        db.deployModule(container, config.dbServer, config.dbPort);
View Full Code Here

        persistorCfg.putString("host", "localhost");
        persistorCfg.putNumber("port", 27017);
        persistorCfg.putString("address", "mongo.persons");
        persistorCfg.putString("db_name", "yoke");

        final EventBus eb = vertx.eventBus();

        // deploy mongo module
        container.deployModule("io.vertx~mod-mongo-persistor~2.0.0-final", persistorCfg);

        // db access
View Full Code Here

  @Inject private AnonymousUsers anonymousUsers;
  private String address;
  private Map<String, JsonObject> collaborators = new HashMap<String, JsonObject>();

  public void start(final CountingCompletionHandler<Void> countDownLatch) {
    final EventBus eb = vertx.eventBus();
    address = container.config().getObject("realtime_store", new JsonObject())
        .getString("address", Topic.STORE);
    final Pattern pattern = Pattern.compile(address + "((/[^/]+){2})" + Topic.WATCH);

    countDownLatch.incRequired();
    eb.registerHandler(address + Topic.PRESENCE, new Handler<Message<JsonObject>>() {
      @Override
      public void handle(Message<JsonObject> message) {
        JsonObject body = message.body();
        String id = body.getString(Key.ID);
        if (id == null) {
          message.fail(-1, "id must be specified");
          return;
        }
        Set<String> sessions = vertx.sharedData()
            .getSet(BridgeHook.getSessionsKey(address + "/" + id + Topic.WATCH));
        if (body.containsField(WebSocketBus.SESSION)) {
          sessions.add(body.getString(WebSocketBus.SESSION));
        }
        JsonArray collaborators = new JsonArray();
        for (String sessionId : sessions) {
          collaborators.addObject(getCollaborator(sessionId));
        }
        message.reply(collaborators);
      }
    }, new Handler<AsyncResult<Void>>() {
      @Override
      public void handle(AsyncResult<Void> ar) {
        if (ar.succeeded()) {
          countDownLatch.complete();
        } else {
          countDownLatch.failed(ar.cause());
        }
      }
    });

    countDownLatch.incRequired();
    eb.registerHandler(BridgeHook.SESSION_WATCH_ADDR, new Handler<Message<JsonObject>>() {
      @Override
      public void handle(Message<JsonObject> message) {
        JsonObject body = message.body();
        String topic = body.getString(BridgeHook.TOPIC);
        Matcher matcher = pattern.matcher(topic);
        if (!matcher.matches()) {
          return;
        }
        JsonObject collaborator = getCollaborator(body.getString(WebSocketBus.SESSION));
        collaborator.putBoolean(Key.IS_JOINED, body.getBoolean(Key.IS_JOINED));
        eb.publish(address + matcher.group(1) + Topic.PRESENCE + Topic.WATCH, collaborator);
      }
    }, new Handler<AsyncResult<Void>>() {
      @Override
      public void handle(AsyncResult<Void> ar) {
        if (ar.succeeded()) {
View Full Code Here

    // }}}

    // {{{ testFoo
    /** {@inheritDoc} */
    public void testFoo() {
        EventBus eb = getVertx().eventBus();

        String handlerId = "testAddress1";
        eb.registerHandler(handlerId, new Handler<Message<JsonObject>>() {
            // {{{ handle
            /** {@inheritDoc} */
            @Override
            public void handle(final Message<JsonObject> msg) {
                logger.fine("received msg: " + msg.body);

                logger.fine("reply address: " + msg.replyAddress);

                tu.azzert("raw_xbee_frames".equals(msg.body.getString("exchange")), "wrong exchange");

                String contentType = msg.body.getObject("properties").getString("contentType");

                Object body;

                if (
                    "application/json".equals(contentType) ||
                    "application/bson".equals(contentType)
                ) {
                    body = msg.body.getObject("body");
                } else {
                    body = msg.body.getBinary("body");
                }

                logger.fine("received body class: " + body.getClass());
                logger.fine("received body: " + body);
                tu.azzert(body != null, "no body in message");

                tu.testComplete();
            }
            // }}}
        });

        logger.fine("address for registered handler: " + handlerId);

        JsonObject createMsg = new JsonObject();
        createMsg.putString("exchange", "raw_xbee_frames");
        createMsg.putString("routingKey", "*.*");
        createMsg.putString("forward", handlerId);

        eb.send(AMQP_BRIDGE_ADDR + ".create-consumer", createMsg);
    }
View Full Code Here

     */
    public void testInvokeRpcWithSingleReply() {
        final JsonObject cannedJsonResponse =
            new JsonObject().putString("baz", "bap");

        EventBus eb = getVertx().eventBus();

        // build the endpoint for the module to deliver to
        Consumer cons = new DefaultConsumer(chan) {
            public void handleDelivery(final String consumerTag,
                                       final Envelope envelope,
                                       final AMQP.BasicProperties props,
                                       final byte[] body)
                throws IOException
            {
                logger.fine("in handleDelivery: " + new String(body));

                getChannel().basicAck(envelope.getDeliveryTag(), false);

                AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
                    .correlationId(props.getCorrelationId())
                    .build();

                getChannel().basicPublish(
                    "",
                    props.getReplyTo(),
                    replyProps,
                    cannedJsonResponse.encode().getBytes()
                );
            }
        };

        try {
            chan.basicConsume(amqpQueue, cons);
        } catch (IOException e) {
            String msg = "unable to consume";
            logger.log(Level.SEVERE, msg, e);
            tu.azzert(false, msg);
        }

        // setup is done; fire off the EventBus invocation
        logger.fine("calling .invoke_rpc");

        eb.send(
            AMQP_BRIDGE_ADDR + ".invoke_rpc",
            new JsonObject()
                .putString("routingKey", amqpQueue)
                .putObject("properties", new JsonObject().putString("contentType", "application/json"))
                .putObject("body", new JsonObject().putString("foo", "bar")),
View Full Code Here

    }
    // }}}

    // {{{ testInvokeRpcWithMultipleReplies
    public void testInvokeRpcWithMultipleReplies() {
        EventBus eb = getVertx().eventBus();

        final int replyCount = 3;
        final List<Message<JsonObject>> receivedMessages = new ArrayList<>();

        String handlerId = "testAddress2";
        // set up an anonymous EventBus handler for receiving our RPC responses
        eb.registerHandler(handlerId, new Handler<Message<JsonObject>>() {
            // {{{ handle
            /** {@inheritDoc} */
            @Override
            public void handle(final Message<JsonObject> msg) {
                receivedMessages.add(msg);

                logger.fine(msg.body.encode());

                // ensure correlation ID is passed back to us
                tu.azzert(
                    "thisIsMyCorrelationId".equals(msg.body.getObject("properties").getString("correlationId")),
                    "didn't get correlation id back"
                );

                if (receivedMessages.size() == replyCount) {
                    tu.testComplete();
                }
            }
            // }}}
        });

        // build the AMQP client endpoint for the module to deliver to
        Consumer cons = new DefaultConsumer(chan) {
            public void handleDelivery(final String consumerTag,
                                       final Envelope envelope,
                                       final AMQP.BasicProperties props,
                                       final byte[] body)
                throws IOException
            {
                logger.fine("in handleDelivery: " + new String(body));

                getChannel().basicAck(envelope.getDeliveryTag(), false);

                java.util.Map<String,Object> headers = new java.util.HashMap<>();
                headers.put("qwerty", "uiop");

                AMQP.BasicProperties replyProps =
                    new AMQP.BasicProperties.Builder()
                        .correlationId(props.getCorrelationId())
                        .headers(headers)
                        .type("Homer")
                        .build();

                for (int i = 1; i <= replyCount; i++) {
                    getChannel().basicPublish(
                        "",
                        props.getReplyTo(),
                        replyProps,
                        new JsonObject().putString(
                            "body",
                            String.format("reply %d of %d", i, replyCount)
                        ).encode().getBytes("UTF-8")
                    );
                }
            }
        };

        try {
            chan.basicConsume(amqpQueue, cons);
        } catch (IOException e) {
            String msg = "unable to consume";
            logger.log(Level.SEVERE, msg, e);
            tu.azzert(false, msg);
        }

        // setup is done; fire off the EventBus invocation
        logger.fine("calling .invoke_rpc");

        eb.send(
            AMQP_BRIDGE_ADDR + ".invoke_rpc",
            new JsonObject()
                .putString("routingKey", amqpQueue)
                .putString("replyTo", handlerId)
                .putObject(
View Full Code Here

     * advantage of some undocumented functionality in the JsonObject object.
     *
     * Sends a BSON object and gets back a string.  This is really painful…
     */
    public void testSendBsonToAMQP() {
        EventBus eb = getVertx().eventBus();



        // build the AMQP client endpoint for the module to deliver to
        Consumer cons = new DefaultConsumer(chan) {
            public void handleDelivery(final String consumerTag,
                                       final Envelope envelope,
                                       final AMQP.BasicProperties props,
                                       final byte[] body)
                throws IOException
            {
                getChannel().basicAck(envelope.getDeliveryTag(), false);

                tu.azzert(
                    "application/bson".equals(props.getContentType()),
                    "wrong content type"
                );

                Map bsonMap = bsonObjectMapper.readValue(
                    new ByteArrayInputStream(body),
                    Map.class
                );

                logger.finer("bsonMap: " + bsonMap);
                logger.finer("bsonMap[testKey], as string: " + new String((byte[]) bsonMap.get("testKey")));

                AMQP.BasicProperties replyProps =
                    new AMQP.BasicProperties.Builder()
                        .correlationId(props.getCorrelationId())
                        .contentType("text/plain")
                        .contentEncoding("UTF-8")
                        .build();

                getChannel().basicPublish(
                    "",
                    props.getReplyTo(),
                    replyProps,
                    (byte[]) bsonMap.get("testKey")
                );
            }
        };

        try {
            chan.basicConsume(amqpQueue, cons);
        } catch (IOException e) {
            String msg = "unable to consume";
            logger.log(Level.SEVERE, msg, e);
            tu.azzert(false, msg);
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            Map<String,Object> bsonReq = new HashMap<>();
            bsonReq.put("testKey", "testValue".getBytes("UTF-8"));

            bsonObjectMapper.writeValue(baos, bsonReq);
        } catch (IOException e) {
            throw new IllegalStateException("bad encoding UTF-8", e);
        }

        // setup is done; fire off the EventBus invocation
        logger.fine("calling .invoke_rpc");

        eb.send(
            AMQP_BRIDGE_ADDR + ".invoke_rpc",
            new JsonObject()
                .putString("routingKey", amqpQueue)
                .putObject("properties", new JsonObject().putString("contentType", "application/bson"))
                .putBinary("body", baos.toByteArray()),
View Full Code Here

TOP

Related Classes of org.vertx.java.core.eventbus.EventBus

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.