Java Code Examples for io.vertx.core.eventbus.MessageConsumer#handler()
The following examples show how to use
io.vertx.core.eventbus.MessageConsumer#handler() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpServer.java From vertx-in-action with MIT License | 5 votes |
private void sse(HttpServerRequest request) { HttpServerResponse response = request.response(); response .putHeader("Content-Type", "text/event-stream") .putHeader("Cache-Control", "no-cache") .setChunked(true); MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer("sensor.updates"); consumer.handler(msg -> { response.write("event: update\n"); response.write("data: " + msg.body().encode() + "\n\n"); }); TimeoutStream ticks = vertx.periodicStream(1000); ticks.handler(id -> { vertx.eventBus().<JsonObject>request("sensor.average", "", reply -> { if (reply.succeeded()) { response.write("event: average\n"); response.write("data: " + reply.result().body().encode() + "\n\n"); } }); }); response.endHandler(v -> { consumer.unregister(); ticks.cancel(); }); }
Example 2
Source File: VertxEventBusMetricsTest.java From vertx-micrometer-metrics with Apache License 2.0 | 5 votes |
@Test public void shouldDiscardMessages(TestContext context) { vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(new MicrometerMetricsOptions() .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true)) .setEnabled(true))) .exceptionHandler(t -> context.exceptionHandler().handle(t)); int num = 10; EventBus eb = vertx.eventBus(); MessageConsumer<Object> consumer = eb.consumer("foo"); consumer.setMaxBufferedMessages(num); consumer.pause(); consumer.handler(msg -> fail("should not be called")); for (int i = 0; i < num; i++) { eb.send("foo", "the_message-" + i); } eb.send("foo", "last"); waitForValue(vertx, context, "vertx.eventbus.discarded[side=local]$COUNT", value -> value.intValue() == 1); List<RegistryInspector.Datapoint> datapoints = listDatapoints(startsWith("vertx.eventbus")); assertThat(datapoints).contains(dp("vertx.eventbus.pending[side=local]$VALUE", 10)); // Unregister => discard all remaining consumer.unregister(); waitForValue(vertx, context, "vertx.eventbus.discarded[side=local]$COUNT", value -> value.intValue() == 11); datapoints = listDatapoints(startsWith("vertx.eventbus")); assertThat(datapoints).contains(dp("vertx.eventbus.pending[side=local]$VALUE", 0)); }
Example 3
Source File: CallbackTraderVerticle.java From vertx-kubernetes-workshop with Apache License 2.0 | 5 votes |
private void initialize(Future<Void> done, String company, int numberOfShares, Future<PortfolioService> retrieveThePortfolioService, Future<MessageConsumer<JsonObject>> retrieveTheMarket, AsyncResult<CompositeFuture> ar) { if (ar.failed()) { done.fail(ar.cause()); } else { PortfolioService portfolio = retrieveThePortfolioService.result(); MessageConsumer<JsonObject> consumer = retrieveTheMarket.result(); consumer.handler(message -> TraderUtils.dumbTradingLogic(company, numberOfShares, portfolio, message.body())); done.complete(); } }
Example 4
Source File: CallbackTraderVerticle.java From vertx-kubernetes-workshop with Apache License 2.0 | 5 votes |
private void initialize(Future<Void> done, String company, int numberOfShares, Future<PortfolioService> retrieveThePortfolioService, Future<MessageConsumer<JsonObject>> retrieveTheMarket, AsyncResult<CompositeFuture> ar) { if (ar.failed()) { done.fail(ar.cause()); } else { PortfolioService portfolio = retrieveThePortfolioService.result(); MessageConsumer<JsonObject> consumer = retrieveTheMarket.result(); consumer.handler(message -> TraderUtils.dumbTradingLogic(company, numberOfShares, portfolio, message.body())); done.complete(); } }
Example 5
Source File: ApplicationLauncher.java From excelastic with MIT License | 5 votes |
/** * Waits until there is a connection to the ElasticSearch server and then * attempts to open the browser if one is available to the import website. */ private void waitForElasticServerAvailability() { MessageConsumer<?> consumer = vertx.eventBus().consumer(ES_STATUS); consumer.handler(message -> { logger.openingBrowser(message.body().toString()); try { Desktop.getDesktop().browse(new URI(Configuration.getWebsiteURL())); } catch (Exception e) { logger.displayNotAvailable(e); } consumer.pause(); }); }
Example 6
Source File: MessageSourceTest.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
@Test public void test() throws InterruptedException { Random random = new Random(); vertx.setPeriodic(10, l -> { vertx.eventBus().publish("data", random.nextDouble()); }); Record record = MessageSource.createRecord("Hello", "data"); discovery.publish(record, (r) -> { }); await().until(() -> record.getRegistration() != null); AtomicReference<Record> found = new AtomicReference<>(); discovery.getRecord(new JsonObject().put("name", "Hello"), ar -> { found.set(ar.result()); }); await().until(() -> found.get() != null); ServiceReference service = discovery.getReference(found.get()); MessageConsumer<Double> consumer = service.get(); List<Double> data = new ArrayList<>(); consumer.handler(message -> { data.add(message.body()); }); await().until(() -> !data.isEmpty()); service.release(); int size = data.size(); Thread.sleep(500); assertThat(data.size()).isEqualTo(size); // Just there to be sure we can call it twice service.release(); }
Example 7
Source File: ReportingTest.java From vertx-unit with Apache License 2.0 | 5 votes |
@org.junit.Test public void testReportToEventBus() { MessageConsumer<JsonObject> consumer = vertx.eventBus().<JsonObject>consumer("the_address"); consumer.handler(msg -> { if (msg.body().getString("type").equals(EventBusCollector.EVENT_TEST_SUITE_END)) { consumer.unregister(); testComplete(); } }); consumer.completionHandler(ar -> { assertTrue(ar.succeeded()); suite.run(vertx, new TestOptions().addReporter(new ReportOptions().setTo("bus:the_address"))); }); await(); }
Example 8
Source File: StoreVerticle.java From vertx-mqtt-broker with Apache License 2.0 | 5 votes |
@Override public void start() throws Exception { PassiveExpiringMap.ConstantTimeToLiveExpirationPolicy<String, Map<String, byte[]>> expirePeriod = new PassiveExpiringMap.ConstantTimeToLiveExpirationPolicy<>( 1, TimeUnit.DAYS); this.db = new PassiveExpiringMap<>( expirePeriod, new LinkedHashMap<>() ); this.topicsManager = new MQTTTopicsManagerOptimized(); MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer(ADDRESS); consumer.handler(message -> { JsonObject request = message.body(); MultiMap headers = message.headers(); if (headers == null || !headers.contains("command")) { message.reply(new JsonObject().put("error", "Invalid message: missing 'command' header")); } JsonObject response = new JsonObject(); String command = headers.get("command"); switch (command) { case "saveRetainMessage": response = saveRetainMessage(request); break; case "getRetainedMessagesByTopicFilter": response = getRetainedMessagesByTopicFilter(request); break; case "deleteRetainMessage": response = deleteRetainMessage(request); break; default: response = doDefault(request); break; } // System.out.println("instance => "+ this + "db.size => "+ db.size()); message.reply(response); }); }
Example 9
Source File: EventBusTest.java From vertx-unit with Apache License 2.0 | 4 votes |
@org.junit.Test public void testEventBusReporter() throws Exception { long now = System.currentTimeMillis(); String address = TestUtils.randomAlphaString(10); String testSuiteName = TestUtils.randomAlphaString(10); String testCaseName1 = TestUtils.randomAlphaString(10); String testCaseName2 = TestUtils.randomAlphaString(10); String testCaseName3 = TestUtils.randomAlphaString(10); AtomicInteger status = new AtomicInteger(); MessageConsumer<JsonObject> consumer = vertx.eventBus().localConsumer(address); consumer.handler(msg -> { JsonObject body = msg.body(); String type = body.getString("type"); switch (status.get()) { case 0: assertEquals(EventBusCollector.EVENT_TEST_SUITE_BEGIN, type); assertEquals(testSuiteName, body.getString("name")); break; case 1: assertEquals(EventBusCollector.EVENT_TEST_CASE_BEGIN, type); assertEquals(testCaseName1, body.getString("name")); break; case 2: assertEquals(EventBusCollector.EVENT_TEST_CASE_END, type); assertEquals(testCaseName1, body.getString("name")); assertTrue(body.getInteger("durationTime") >= 10); assertNull(testCaseName1, body.getJsonObject("failure")); break; case 3: assertEquals(EventBusCollector.EVENT_TEST_CASE_BEGIN, type); assertEquals(testCaseName2, body.getString("name")); break; case 4: assertEquals(EventBusCollector.EVENT_TEST_CASE_END, type); assertEquals(testCaseName2, body.getString("name")); assertTrue(body.getLong("beginTime") >= now); assertTrue(body.getLong("durationTime") >= 0); JsonObject failure = body.getJsonObject("failure"); assertNotNull(failure); assertEquals("the_" + testCaseName2 + "_failure", failure.getString("message")); assertNotNull(failure.getString("stackTrace")); assertNotNull(failure.getBinary("cause")); break; case 5: assertEquals(EventBusCollector.EVENT_TEST_CASE_BEGIN, type); assertEquals(testCaseName3, body.getString("name")); break; case 6: assertEquals(EventBusCollector.EVENT_TEST_CASE_END, type); assertEquals(testCaseName3, body.getString("name")); assertTrue(body.getLong("beginTime") >= now); assertTrue(body.getLong("durationTime") >= 0); JsonObject error = body.getJsonObject("failure"); assertNotNull(error); assertNull(error.getString("message")); assertNotNull(error.getString("stackTrace")); assertNotNull(error.getBinary("cause")); break; case 7: assertEquals(EventBusCollector.EVENT_TEST_SUITE_END, type); assertEquals(testSuiteName, body.getString("name")); consumer.unregister(); testComplete(); break; default: fail("Unexpected status " + status.get()); } status.incrementAndGet(); }); consumer.completionHandler(ar -> { assertTrue(ar.succeeded()); TestSuite.create(testSuiteName).test(testCaseName1, context -> { try { Thread.sleep(10); } catch (InterruptedException ignore) { } }).test(testCaseName2, context -> { context.fail("the_" + testCaseName2 + "_failure"); }).test(testCaseName3, context -> { throw new RuntimeException(); }).run(vertx, new TestOptions().addReporter(new ReportOptions().setTo("bus:" + address))); }); await(); }
Example 10
Source File: EventBusTest.java From vertx-unit with Apache License 2.0 | 4 votes |
@org.junit.Test public void testEventBusReporterTestSuiteFailure() throws Exception { String address = TestUtils.randomAlphaString(10); String testSuiteName = TestUtils.randomAlphaString(10); String testCaseName = TestUtils.randomAlphaString(10); AtomicInteger status = new AtomicInteger(); MessageConsumer<JsonObject> consumer = vertx.eventBus().localConsumer(address); consumer.handler(msg -> { JsonObject body = msg.body(); String type = body.getString("type"); switch (status.get()) { case 0: assertEquals(EventBusCollector.EVENT_TEST_SUITE_BEGIN, type); assertEquals(testSuiteName, body.getString("name")); break; case 1: assertEquals(EventBusCollector.EVENT_TEST_CASE_BEGIN, type); assertEquals(testCaseName, body.getString("name")); break; case 2: assertEquals(EventBusCollector.EVENT_TEST_CASE_END, type); assertEquals(testCaseName, body.getString("name")); assertNotNull(body.getLong("beginTime")); assertNotNull(body.getLong("durationTime")); assertNull(testCaseName, body.getJsonObject("failure")); break; case 3: assertEquals(EventBusCollector.EVENT_TEST_SUITE_ERROR, type); JsonObject failure = body.getJsonObject("failure"); assertNotNull(failure); assertEquals("the_after_failure", failure.getString("message")); assertNotNull(failure.getString("stackTrace")); assertNotNull(failure.getBinary("cause")); break; case 4: assertEquals(EventBusCollector.EVENT_TEST_SUITE_END, type); assertEquals(testSuiteName, body.getString("name")); assertNull(body.getLong("beginTime")); assertNull(body.getLong("durationTime")); consumer.unregister(); testComplete(); break; default: fail("Unexpected status " + status.get()); } status.incrementAndGet(); }); consumer.completionHandler(ar -> { assertTrue(ar.succeeded()); TestSuite.create(testSuiteName).test(testCaseName, context -> { // Ok }).after(context -> { throw new RuntimeException("the_after_failure"); }).run(vertx, new TestOptions().addReporter(new ReportOptions().setTo("bus:" + address))); }); await(); }
Example 11
Source File: EventBusTest.java From vertx-unit with Apache License 2.0 | 4 votes |
@org.junit.Test public void testEventBusReport() throws Exception { long now = System.currentTimeMillis(); String address = TestUtils.randomAlphaString(10); String testSuiteName = TestUtils.randomAlphaString(10); String testCaseName1 = TestUtils.randomAlphaString(10); String testCaseName2 = TestUtils.randomAlphaString(10); String testCaseName3 = TestUtils.randomAlphaString(10); MessageConsumer<JsonObject> consumer = vertx.eventBus().localConsumer(address); Handler<Message<JsonObject>> messageHandler = EventBusCollector.create(vertx, testSuite -> { Map<TestCaseReport, TestResult> results = new LinkedHashMap<>(); testSuite.handler(testCase -> { testCase.endHandler(result -> { results.put(testCase, result); }); }); testSuite.endHandler(done -> { assertEquals(testSuiteName, testSuite.name()); assertEquals(3, results.size()); Iterator<Map.Entry<TestCaseReport, TestResult>> it = results.entrySet().iterator(); Map.Entry<TestCaseReport, TestResult> entry1 = it.next(); assertEquals(entry1.getKey().name(), entry1.getValue().name()); assertEquals(testCaseName1, entry1.getValue().name()); assertTrue(entry1.getValue().succeeded()); assertTrue(entry1.getValue().beginTime() >= now); assertEquals(10, entry1.getValue().durationTime()); assertNull(entry1.getValue().failure()); Map.Entry<TestCaseReport, TestResult> entry2 = it.next(); assertEquals(entry2.getKey().name(), entry2.getValue().name()); assertEquals(testCaseName2, entry2.getValue().name()); assertFalse(entry2.getValue().succeeded()); assertTrue(entry2.getValue().beginTime() >= now); assertEquals(5, entry2.getValue().durationTime()); assertNotNull(entry2.getValue().failure()); assertEquals(false, entry2.getValue().failure().isError()); assertEquals("the_failure_message", entry2.getValue().failure().message()); assertEquals("the_failure_stackTrace", entry2.getValue().failure().stackTrace()); assertTrue(entry2.getValue().failure().cause() instanceof IOException); Map.Entry<TestCaseReport, TestResult> entry3 = it.next(); assertEquals(entry3.getKey().name(), entry3.getValue().name()); assertEquals(testCaseName3, entry3.getValue().name()); assertFalse(entry3.getValue().succeeded()); assertTrue(entry3.getValue().beginTime() >= now); assertEquals(7, entry3.getValue().durationTime()); assertNotNull(entry3.getValue().failure()); assertEquals(false, entry3.getValue().failure().isError()); assertEquals(null, entry3.getValue().failure().message()); assertEquals("the_failure_stackTrace", entry3.getValue().failure().stackTrace()); assertTrue(entry3.getValue().failure().cause() instanceof IOException); consumer.unregister(); testComplete(); }); }).asMessageHandler(); consumer.completionHandler(ar -> { assertTrue(ar.succeeded()); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_SUITE_BEGIN).put("name", testSuiteName)); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_BEGIN).put("name", testCaseName1)); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_END).put("name", testCaseName1).put("beginTime", System.currentTimeMillis()).put("durationTime", 10L)); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_BEGIN).put("name", testCaseName2)); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_END).put("name", testCaseName2).put("beginTime", System.currentTimeMillis()).put("durationTime", 5L). put("failure", new FailureImpl( false, "the_failure_message", "the_failure_stackTrace", new IOException()).toJson())); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_BEGIN).put("name", testCaseName3)); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_END).put("name", testCaseName3).put("beginTime", System.currentTimeMillis()).put("durationTime", 7L). put("failure", new FailureImpl( false, null, "the_failure_stackTrace", new IOException()).toJson())); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_SUITE_END)); }); consumer.handler(messageHandler); await(); }
Example 12
Source File: EventBusTest.java From vertx-unit with Apache License 2.0 | 4 votes |
@org.junit.Test public void testEventBusReportAfterFailure() throws Exception { String address = TestUtils.randomAlphaString(10); String testSuiteName = TestUtils.randomAlphaString(10); String testCaseName = TestUtils.randomAlphaString(10); MessageConsumer<JsonObject> consumer = vertx.eventBus().localConsumer(address); LinkedList<Throwable> suiteFailures = new LinkedList<>(); Handler<Message<JsonObject>> messageHandler = EventBusCollector.create(vertx, testSuite -> { Map<TestCaseReport, TestResult> results = new LinkedHashMap<>(); testSuite.handler(testCase -> { testCase.endHandler(result -> { assertEquals(Collections.emptyList(), suiteFailures); results.put(testCase, result); }); }); testSuite.exceptionHandler(suiteFailures::add); testSuite.endHandler(done -> { assertEquals(testSuiteName, testSuite.name()); assertEquals(1, results.size()); Iterator<Map.Entry<TestCaseReport, TestResult>> it = results.entrySet().iterator(); Map.Entry<TestCaseReport, TestResult> entry1 = it.next(); assertEquals(entry1.getKey().name(), entry1.getValue().name()); assertEquals(testCaseName, entry1.getValue().name()); assertTrue(entry1.getValue().succeeded()); assertNull(entry1.getValue().failure()); assertEquals(1, suiteFailures.size()); assertTrue(suiteFailures.get(0) instanceof IOException); consumer.unregister(); testComplete(); }); }).asMessageHandler(); consumer.completionHandler(ar -> { assertTrue(ar.succeeded()); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_SUITE_BEGIN).put("name", testSuiteName)); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_BEGIN).put("name", testCaseName)); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_END).put("name", testCaseName)); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_SUITE_ERROR). put("failure", new FailureImpl( false, "the_failure_message", "the_failure_stackTrace", new IOException()).toJson())); vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_SUITE_END)); }); consumer.handler(messageHandler); await(); }