Search in sources :

Example 1 with MessageConsumer

use of io.vertx.core.eventbus.MessageConsumer in project vert.x by eclipse.

the class MetricsContextTest method testMessageHandler.

private void testMessageHandler(BiConsumer<Vertx, Handler<Void>> runOnContext, BiConsumer<Thread, Context> checker) {
    AtomicReference<Thread> consumerThread = new AtomicReference<>();
    AtomicReference<Context> consumerContext = new AtomicReference<>();
    AtomicBoolean registeredCalled = new AtomicBoolean();
    AtomicBoolean unregisteredCalled = new AtomicBoolean();
    AtomicBoolean beginHandleCalled = new AtomicBoolean();
    AtomicBoolean endHandleCalled = new AtomicBoolean();
    VertxMetricsFactory factory = (vertx, options) -> new DummyVertxMetrics() {

        @Override
        public EventBusMetrics createMetrics(EventBus eventBus) {
            return new DummyEventBusMetrics() {

                @Override
                public boolean isEnabled() {
                    return true;
                }

                @Override
                public Void handlerRegistered(String address, String repliedAddress) {
                    registeredCalled.set(true);
                    return null;
                }

                @Override
                public void handlerUnregistered(Void handler) {
                    unregisteredCalled.set(true);
                }

                @Override
                public void beginHandleMessage(Void handler, boolean local) {
                    consumerThread.set(Thread.currentThread());
                    consumerContext.set(Vertx.currentContext());
                    beginHandleCalled.set(true);
                }

                @Override
                public void endHandleMessage(Void handler, Throwable failure) {
                    endHandleCalled.set(true);
                    checker.accept(consumerThread.get(), consumerContext.get());
                }
            };
        }
    };
    Vertx vertx = vertx(new VertxOptions().setMetricsOptions(new MetricsOptions().setEnabled(true).setFactory(factory)));
    EventBus eb = vertx.eventBus();
    runOnContext.accept(vertx, v -> {
        MessageConsumer<Object> consumer = eb.consumer("the_address");
        consumer.handler(msg -> {
            checker.accept(consumerThread.get(), consumerContext.get());
            executeInVanillaThread(() -> {
                vertx.getOrCreateContext().runOnContext(v2 -> {
                    consumer.unregister(onSuccess(v3 -> {
                        assertTrue(registeredCalled.get());
                        assertTrue(beginHandleCalled.get());
                        assertTrue(endHandleCalled.get());
                        waitUntil(() -> unregisteredCalled.get());
                        testComplete();
                    }));
                });
            });
        }).completionHandler(onSuccess(v2 -> {
            eb.send("the_address", "the_msg");
        }));
    });
    await();
}
Also used : io.vertx.core(io.vertx.core) DatagramSocket(io.vertx.core.datagram.DatagramSocket) VertxMetricsFactory(io.vertx.core.spi.VertxMetricsFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) DummyVertxMetrics(io.vertx.core.metrics.impl.DummyVertxMetrics) io.vertx.core.net(io.vertx.core.net) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) io.vertx.core.http(io.vertx.core.http) CountDownLatch(java.util.concurrent.CountDownLatch) EventBus(io.vertx.core.eventbus.EventBus) Buffer(io.vertx.core.buffer.Buffer) MetricsOptions(io.vertx.core.metrics.MetricsOptions) Ignore(org.junit.Ignore) BiConsumer(java.util.function.BiConsumer) io.vertx.core.spi.metrics(io.vertx.core.spi.metrics) DatagramSocketOptions(io.vertx.core.datagram.DatagramSocketOptions) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) MetricsOptions(io.vertx.core.metrics.MetricsOptions) AtomicReference(java.util.concurrent.atomic.AtomicReference) DummyVertxMetrics(io.vertx.core.metrics.impl.DummyVertxMetrics) EventBus(io.vertx.core.eventbus.EventBus) VertxMetricsFactory(io.vertx.core.spi.VertxMetricsFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 2 with MessageConsumer

use of io.vertx.core.eventbus.MessageConsumer in project vert.x by eclipse.

the class NetTest method setHandlers.

void setHandlers(NetSocket sock) {
    Handler<Message<Buffer>> resumeHandler = m -> sock.resume();
    MessageConsumer reg = vertx.eventBus().<Buffer>consumer("client_resume").handler(resumeHandler);
    sock.closeHandler(v -> reg.unregister());
}
Also used : java.util(java.util) io.vertx.core(io.vertx.core) io.vertx.core.impl(io.vertx.core.impl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cert(io.vertx.test.core.tls.Cert) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) AtomicReference(java.util.concurrent.atomic.AtomicReference) LoggerFactory(io.vertx.core.logging.LoggerFactory) InetAddress(java.net.InetAddress) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReadStream(io.vertx.core.streams.ReadStream) OutputStreamWriter(java.io.OutputStreamWriter) JsonObject(io.vertx.core.json.JsonObject) Assume(org.junit.Assume) Logger(io.vertx.core.logging.Logger) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) BufferedWriter(java.io.BufferedWriter) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Message(io.vertx.core.eventbus.Message) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) X509Certificate(javax.security.cert.X509Certificate) io.vertx.core.net(io.vertx.core.net) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) ClientAuth(io.vertx.core.http.ClientAuth) InternalLoggerFactory(io.netty.util.internal.logging.InternalLoggerFactory) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) TemporaryFolder(org.junit.rules.TemporaryFolder) Trust(io.vertx.test.core.tls.Trust) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) TestUtils.assertIllegalArgumentException(io.vertx.test.core.TestUtils.assertIllegalArgumentException) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) Message(io.vertx.core.eventbus.Message)

Example 3 with MessageConsumer

use of io.vertx.core.eventbus.MessageConsumer in project hono by eclipse.

the class RequestResponseEndpoint method onLinkAttach.

/**
 * Handles a client's request to establish a link for receiving responses
 * to service invocations.
 * <p>
 * This method registers a consumer on the vert.x event bus for the given reply-to address.
 * Response messages received over the event bus are transformed into AMQP messages using
 * the {@link #getAmqpReply(EventBusMessage)} method and sent to the client over the established
 * link.
 *
 * @param con The AMQP connection that the link is part of.
 * @param sender The link to establish.
 * @param replyToAddress The reply-to address to create a consumer on the event bus for.
 */
@Override
public final void onLinkAttach(final ProtonConnection con, final ProtonSender sender, final ResourceIdentifier replyToAddress) {
    if (isValidReplyToAddress(replyToAddress)) {
        logger.debug("establishing sender link with client [{}]", sender.getName());
        final MessageConsumer<JsonObject> replyConsumer = vertx.eventBus().consumer(replyToAddress.toString(), message -> {
            // TODO check for correct session here...?
            if (logger.isTraceEnabled()) {
                logger.trace("forwarding reply to client [{}]: {}", sender.getName(), message.body().encodePrettily());
            }
            final EventBusMessage response = EventBusMessage.fromJson(message.body());
            filterResponse(Constants.getClientPrincipal(con), response).recover(t -> {
                final int status = Optional.of(t).map(cause -> {
                    if (cause instanceof ServiceInvocationException) {
                        return ((ServiceInvocationException) cause).getErrorCode();
                    } else {
                        return null;
                    }
                }).orElse(HttpURLConnection.HTTP_INTERNAL_ERROR);
                return Future.succeededFuture(response.getResponse(status));
            }).map(filteredResponse -> {
                final Message amqpReply = getAmqpReply(filteredResponse);
                sender.send(amqpReply);
                return null;
            });
        });
        sender.setQoS(ProtonQoS.AT_LEAST_ONCE);
        sender.closeHandler(senderClosed -> {
            logger.debug("client [{}] closed sender link, removing associated event bus consumer [{}]", sender.getName(), replyConsumer.address());
            replyConsumer.unregister();
            if (senderClosed.succeeded()) {
                senderClosed.result().close();
            }
        });
        sender.open();
    } else {
        logger.debug("client [{}] provided invalid reply-to address", sender.getName());
        sender.setCondition(ProtonHelper.condition(AmqpError.INVALID_FIELD, String.format("reply-to address must have the following format %s/<tenant>/<reply-address>", getName())));
        sender.close();
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) AmqpErrorException(org.eclipse.hono.util.AmqpErrorException) ProtonDelivery(io.vertx.proton.ProtonDelivery) DecodeException(io.vertx.core.json.DecodeException) Autowired(org.springframework.beans.factory.annotation.Autowired) EventBusMessage(org.eclipse.hono.util.EventBusMessage) HonoUser(org.eclipse.hono.auth.HonoUser) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) ServiceConfigProperties(org.eclipse.hono.config.ServiceConfigProperties) Constants(org.eclipse.hono.util.Constants) Message(org.apache.qpid.proton.message.Message) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) JsonObject(io.vertx.core.json.JsonObject) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) Vertx(io.vertx.core.Vertx) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Objects(java.util.Objects) Optional(java.util.Optional) ProtonSender(io.vertx.proton.ProtonSender) ClaimsBasedAuthorizationService(org.eclipse.hono.service.auth.ClaimsBasedAuthorizationService) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) AuthorizationService(org.eclipse.hono.service.auth.AuthorizationService) EventBusMessage(org.eclipse.hono.util.EventBusMessage) Message(org.apache.qpid.proton.message.Message) EventBusMessage(org.eclipse.hono.util.EventBusMessage) JsonObject(io.vertx.core.json.JsonObject) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException)

Example 4 with MessageConsumer

use of io.vertx.core.eventbus.MessageConsumer in project vertx-openshift-it by cescoffier.

the class DistributedPublish method setup.

void setup(Handler<AsyncResult<Void>> handler) {
    EventBus eventBus = vertx.eventBus();
    MessageConsumer<String> consumer = createMessageConsumer(eventBus, address);
    consumer.handler(msg -> {
        eventBus.send(msg.body(), clusterManager.getNodeID());
    }).completionHandler(ar -> {
        if (ar.succeeded()) {
            handler.handle(Future.succeededFuture());
        } else {
            handler.handle(Future.failedFuture(ar.cause()));
        }
    });
}
Also used : EventBus(io.vertx.core.eventbus.EventBus) VertxInternal(io.vertx.core.impl.VertxInternal) ClusterManager(io.vertx.core.spi.cluster.ClusterManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Vertx(io.vertx.core.Vertx) HttpHeaders(io.vertx.core.http.HttpHeaders) AsyncResult(io.vertx.core.AsyncResult) RoutingContext(io.vertx.ext.web.RoutingContext) UUID(java.util.UUID) Handler(io.vertx.core.Handler) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) Future(io.vertx.core.Future) EventBus(io.vertx.core.eventbus.EventBus)

Example 5 with MessageConsumer

use of io.vertx.core.eventbus.MessageConsumer in project vertx-openshift-it by cescoffier.

the class DistributedTimeout method setup.

void setup(Handler<AsyncResult<Void>> handler) {
    EventBus eventBus = vertx.eventBus();
    MessageConsumer<Boolean> consumer = createMessageConsumer(eventBus, address);
    consumer.handler(msg -> {
        Boolean reply = msg.body();
        if (reply) {
            msg.reply(clusterManager.getNodeID());
        }
    }).completionHandler(ar -> {
        if (ar.succeeded()) {
            handler.handle(Future.succeededFuture());
        } else {
            handler.handle(Future.failedFuture(ar.cause()));
        }
    });
}
Also used : DeliveryOptions(io.vertx.core.eventbus.DeliveryOptions) VertxInternal(io.vertx.core.impl.VertxInternal) ClusterManager(io.vertx.core.spi.cluster.ClusterManager) Vertx(io.vertx.core.Vertx) HttpHeaders(io.vertx.core.http.HttpHeaders) RoutingContext(io.vertx.ext.web.RoutingContext) Future(io.vertx.core.Future) EventBus(io.vertx.core.eventbus.EventBus) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReplyFailure(io.vertx.core.eventbus.ReplyFailure) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) ReplyException(io.vertx.core.eventbus.ReplyException) EventBus(io.vertx.core.eventbus.EventBus)

Aggregations

MessageConsumer (io.vertx.core.eventbus.MessageConsumer)13 Buffer (io.vertx.core.buffer.Buffer)9 EventBus (io.vertx.core.eventbus.EventBus)9 VertxInternal (io.vertx.core.impl.VertxInternal)7 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 Test (org.junit.Test)7 io.vertx.core (io.vertx.core)6 Future (io.vertx.core.Future)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 Vertx (io.vertx.core.Vertx)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 Consumer (java.util.function.Consumer)5 AsyncResult (io.vertx.core.AsyncResult)4 Handler (io.vertx.core.Handler)4 DatagramSocket (io.vertx.core.datagram.DatagramSocket)4 DeliveryOptions (io.vertx.core.eventbus.DeliveryOptions)4 ReplyFailure (io.vertx.core.eventbus.ReplyFailure)4 io.vertx.core.http (io.vertx.core.http)4 HttpHeaders (io.vertx.core.http.HttpHeaders)4