Refine search
@Test public void testChangesNotVisibleObject2() { final JsonObject obj = new JsonObject(); eb.<JsonObject>consumer("foo").handler((Message<JsonObject> msg) -> { msg.body().put("b", "uqwduihwqd"); }); eb.send("foo", obj); vertx.setTimer(1000, id -> { assertFalse(obj.containsKey("b")); testComplete(); }); await(); }
@Test public void testPublishSameHandlerRegisteredTwice() { String str = TestUtils.randomUnicodeString(1000); AtomicInteger count = new AtomicInteger(); Handler<Message<String>> handler = (Message<String> msg) -> { assertEquals(str, msg.body()); if (count.incrementAndGet() == 2) { testComplete(); } }; eb.<String>consumer(ADDRESS1).handler(handler); eb.<String>consumer(ADDRESS1).handler(handler); eb.publish(ADDRESS1, str); await(); }
@Test public void testDefaultCodecReplyExceptionSubclass() throws Exception { startNodes(2); MyReplyException myReplyException = new MyReplyException(23, "my exception"); MyReplyExceptionMessageCodec codec = new MyReplyExceptionMessageCodec(); vertices[0].eventBus().registerDefaultCodec(MyReplyException.class, codec); vertices[1].eventBus().registerDefaultCodec(MyReplyException.class, codec); MessageConsumer<ReplyException> reg = vertices[0].eventBus().<ReplyException>consumer(ADDRESS1, msg -> { assertTrue(msg.body() instanceof MyReplyException); testComplete(); }); reg.completionHandler(ar -> { vertices[1].eventBus().send(ADDRESS1, myReplyException); }); await(); }
@Test public void testUnregisterDefaultDecoder() throws Exception { MessageCodec codec = new MyPOJOEncoder1(); vertx.eventBus().registerDefaultCodec(MyPOJO.class, codec); vertx.eventBus().unregisterDefaultCodec(MyPOJO.class); assertIllegalArgumentException(() -> vertx.eventBus().send(ADDRESS1, new MyPOJO("foo"))); }
@GET @Path("/products") @Produces({MediaType.APPLICATION_JSON}) public void list( // Suspend the request @Suspended final AsyncResponse asyncResponse, // Inject the Vertx instance @Context Vertx vertx) { // Send a list message to the backend vertx.eventBus().<JsonArray>send("backend", new JsonObject().put("op", "list"), msg -> { // When we get the response we resume the Jax-RS async response if (msg.succeeded()) { JsonArray json = msg.result().body(); if (json != null) { asyncResponse.resume(json.encode()); } else { asyncResponse.resume(Response.status(Response.Status.NOT_FOUND).build()); } } else { asyncResponse.resume(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build()); } }); } }
@Test public void testRegisterRemote1() { startNodes(2); String str = TestUtils.randomUnicodeString(100); vertices[0].eventBus().<String>consumer(ADDRESS1).handler((Message<String> msg) -> { assertEquals(str, msg.body()); testComplete(); }).completionHandler(ar -> { assertTrue(ar.succeeded()); vertices[1].eventBus().send(ADDRESS1, str); }); await(); }
private void handleRoot(RoutingContext routingContext) { JsonObject result = new JsonObject(); result.put("welcome", "欢迎使用古诗词·一言"); result.put("api-document", "下面为本API可用的所有类型,使用时,在链接最后面加上 .svg / .txt / .json / .png 可以获得不同格式的输出"); result.put("help", "具体安装方法请访问项目首页 " + config().getString("index.url", "http://localhost/")); vertx.eventBus().<JsonArray>send(Key.GET_HELP_FROM_REDIS, null, res -> { if (res.succeeded()) { result.put("list", res.result().body()); returnJsonWithCache(routingContext, result); } else { routingContext.fail(res.cause()); } }); }
@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() .addOutboundPermitted(new PermittedOptions().setAddress("feed")); // Create the event bus bridge and add it to the router. SockJSHandler ebHandler = SockJSHandler.create(vertx).bridge(opts); router.route("/eventbus/*").handler(ebHandler); // Start the web server and tell it to use the router to handle requests. vertx.createHttpServer().requestHandler(router).listen(8080); EventBus eb = vertx.eventBus(); vertx.setPeriodic(1000l, t -> { // Create a timestamp string String timestamp = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(Date.from(Instant.now())); eb.send("feed", new JsonObject().put("now", timestamp)); }); } }
private void sendMessage() { JsonObject jsonMessage = new JsonObject().put("message_from_sender_verticle", "hello consumer"); eventBus.send("Consumer", jsonMessage, messageAsyncResult -> { if(messageAsyncResult.succeeded()) { JsonObject jsonReply = (JsonObject) messageAsyncResult.result().body(); System.out.println("received reply: " + jsonReply.getValue("reply")); } }); } }
@Override public void start(Future<Void> startFuture) throws Exception { HttpServerOptions options = new HttpServerOptions().setPort(config().getInteger("port")); vertx.createHttpServer(options).requestHandler(request -> { String name = request.getParam("name"); if (name == null) { request.response().setStatusCode(400).end("Missing name"); } else { vertx.eventBus().<String>send("hello", name, ar -> { if (ar.succeeded()) { request.response().end(ar.result().body()); } else { request.response().setStatusCode(500).end(ar.cause().getMessage()); } }); } }).listen(ar -> { if (ar.succeeded()) { startFuture.complete(); } else { startFuture.fail(ar.cause()); } }); } }
private void testIsolationGroup(String group1, String group2, int count1, int count2, List<String> isolatedClasses, String verticleID) throws Exception { Map<String, Integer> countMap = new ConcurrentHashMap<>(); vertx.eventBus().<JsonObject>consumer("testcounts").handler((Message<JsonObject> msg) -> { countMap.put(msg.body().getString("deploymentID"), msg.body().getInteger("count")); }); CountDownLatch latch = new CountDownLatch(1); boolean expectedSuccess = Thread.currentThread().getContextClassLoader() instanceof URLClassLoader; try { vertx.deployVerticle(verticleID, new DeploymentOptions(). setIsolationGroup(group1).setIsolatedClasses(isolatedClasses), ar -> { assertTrue(ar.succeeded()); deploymentID1.set(ar.result()); assertEquals(0, TestVerticle.instanceCount.get()); vertx.deployVerticle(verticleID, new DeploymentOptions().setIsolationGroup(group2).setIsolatedClasses(isolatedClasses), ar2 -> { assertTrue(ar2.succeeded()); deploymentID2.set(ar2.result()); assertEquals(0, TestVerticle.instanceCount.get());
HttpServer httpServer = vertx.createHttpServer(); httpServer.requestHandler(router).listen(8080, ar -> { if (ar.succeeded()) { System.out.println("Http server started"); } else { ar.cause().printStackTrace(); JsonObject dashboard = new JsonObject(); vertx.setPeriodic(1000, timerID -> { vertx.eventBus().publish("dashboard", dashboard); }); KafkaReadStream<String, JsonObject> consumer = KafkaReadStream.create(vertx, config.getMap(), String.class, JsonObject.class); dashboard.mergeIn(obj); });
@Test public void testSendWithTimeoutNoTimeoutAfterReply() { String str = TestUtils.randomUnicodeString(1000); long timeout = 1000; eb.<String>consumer(ADDRESS1).handler((Message<String> msg) -> { assertEquals(str, msg.body()); msg.reply("a reply"); }); AtomicBoolean received = new AtomicBoolean(); eb.send(ADDRESS1, str, new DeliveryOptions().setSendTimeout(timeout), (AsyncResult<Message<Integer>> ar) -> { assertFalse(received.get()); assertTrue(ar.succeeded()); received.set(true); // Now wait longer than timeout and make sure we don't receive any other reply vertx.setTimer(timeout * 2, tid -> { testComplete(); }); }); await(); }
mongo = MongoClient.createShared(vertx, new JsonObject().put("db_name", "demo")); vertx.eventBus().consumer("vtoons.listAlbums", this::listAlbums); vertx.eventBus().consumer("vtoons.placeOrder", this::placeOrder); AuthProvider authProvider = ShiroAuth.create(vertx, ShiroAuthRealmType.PROPERTIES, new JsonObject()); if (login.failed()) { ctx.setUser(login.result()); ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json").end("{}"); }); vertx.createHttpServer().requestHandler(router).listen(8080);
@Test public void testSendWithTimeoutNoTimeoutReply() { String str = TestUtils.randomUnicodeString(1000); eb.<String>consumer(ADDRESS1).handler((Message<String> msg) -> { assertEquals(str, msg.body()); msg.reply(23); }); long timeout = 1000; eb.send(ADDRESS1, str, new DeliveryOptions().setSendTimeout(timeout), (AsyncResult<Message<Integer>> ar) -> { assertTrue(ar.succeeded()); assertEquals(23, (int) ar.result().body()); testComplete(); }); await(); }
private void registerHandler() { MessageConsumer<JsonObject> messageConsumer = eventBus.consumer(verticleAddress); messageConsumer.handler(message -> { JsonObject jsonMessage = message.body(); System.out.println(jsonMessage.getValue("message_from_sender_verticle")); JsonObject jsonReply = new JsonObject().put("reply", "how interesting!"); message.reply(jsonReply); }); } }
@Override public void start() throws Exception { // A simple backend vertx.eventBus().<JsonObject>consumer("backend", msg -> { JsonObject json = msg.body(); switch (json.getString("op", "")) { case "get": { String productID = json.getString("id"); msg.reply(products.get(productID)); break; } case "add": { String productID = json.getString("id"); JsonObject product = json.getJsonObject("product"); product.put("id", productID); msg.reply(addProduct(product)); break; } case "list": { JsonArray arr = new JsonArray(); products.forEach((k, v) -> arr.add(v)); msg.reply(arr); break; } default: { msg.fail(0, "operation not permitted"); } } }); }
@Test public void testRegisterLocal1() { String str = TestUtils.randomUnicodeString(100); eb.<String>localConsumer(ADDRESS1).handler((Message<String> msg) -> { assertEquals(str, msg.body()); testComplete(); }).completionHandler(ar -> { assertTrue(ar.succeeded()); eb.send(ADDRESS1, str); }); await(); }
@Test public void testSendWithTimeoutNoReply() { String str = TestUtils.randomUnicodeString(1000); eb.<String>consumer(ADDRESS1).handler((Message<String> msg) -> { assertEquals(str, msg.body()); }); long timeout = 1000; long start = System.currentTimeMillis(); eb.send(ADDRESS1, str, new DeliveryOptions().setSendTimeout(timeout), (AsyncResult<Message<Integer>> ar) -> { long now = System.currentTimeMillis(); assertFalse(ar.succeeded()); Throwable cause = ar.cause(); assertTrue(cause instanceof ReplyException); ReplyException re = (ReplyException) cause; assertEquals(-1, re.failureCode()); assertEquals(ReplyFailure.TIMEOUT, re.failureType()); assertTrue(now - start >= timeout); testComplete(); }); await(); }