Search in sources :

Example 56 with Handler

use of io.vertx.core.Handler in project hono by eclipse.

the class EventConsumerImplTest method testCreateRegistersBiConsumerAsMessageHandler.

/**
 * Verifies that the message delivery for a received event is forwarded to the
 * registered event consumer.
 *
 * @param ctx The test context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testCreateRegistersBiConsumerAsMessageHandler(final TestContext ctx) {
    // GIVEN an event consumer that releases all messages
    final Async consumerCreation = ctx.async();
    final BiConsumer<ProtonDelivery, Message> eventConsumer = (delivery, message) -> {
        ProtonHelper.released(delivery, true);
    };
    final RecordImpl attachments = new RecordImpl();
    final Source source = mock(Source.class);
    when(source.toString()).thenReturn("event/tenant");
    final ProtonReceiver receiver = mock(ProtonReceiver.class);
    when(receiver.getSource()).thenReturn(source);
    when(receiver.attachments()).thenReturn(attachments);
    when(receiver.getRemoteQoS()).thenReturn(ProtonQoS.AT_LEAST_ONCE);
    when(receiver.open()).then(answer -> {
        consumerCreation.complete();
        return receiver;
    });
    final ProtonConnection con = mock(ProtonConnection.class);
    when(con.createReceiver(anyString())).thenReturn(receiver);
    when(receiver.openHandler(any(Handler.class))).thenAnswer(invocation -> {
        final Handler handler = invocation.getArgument(0);
        handler.handle(Future.succeededFuture(receiver));
        return receiver;
    });
    final ArgumentCaptor<ProtonMessageHandler> messageHandler = ArgumentCaptor.forClass(ProtonMessageHandler.class);
    EventConsumerImpl.create(vertx.getOrCreateContext(), new ClientConfigProperties(), con, "tenant", eventConsumer, open -> {
    }, remoteDetach -> {
    });
    consumerCreation.await();
    verify(receiver).handler(messageHandler.capture());
    // WHEN an event is received
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    final Message msg = mock(Message.class);
    messageHandler.getValue().handle(delivery, msg);
    // THEN the message is released and settled
    verify(delivery).disposition(any(Released.class), eq(Boolean.TRUE));
}
Also used : TestContext(io.vertx.ext.unit.TestContext) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) Async(io.vertx.ext.unit.Async) ProtonDelivery(io.vertx.proton.ProtonDelivery) RunWith(org.junit.runner.RunWith) Timeout(io.vertx.ext.unit.junit.Timeout) ArgumentCaptor(org.mockito.ArgumentCaptor) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) RecordImpl(org.apache.qpid.proton.engine.impl.RecordImpl) After(org.junit.After) BiConsumer(java.util.function.BiConsumer) Message(org.apache.qpid.proton.message.Message) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Released(org.apache.qpid.proton.amqp.messaging.Released) Future(io.vertx.core.Future) Mockito(org.mockito.Mockito) Source(org.apache.qpid.proton.amqp.transport.Source) Rule(org.junit.Rule) Handler(io.vertx.core.Handler) ProtonReceiver(io.vertx.proton.ProtonReceiver) Released(org.apache.qpid.proton.amqp.messaging.Released) ProtonDelivery(io.vertx.proton.ProtonDelivery) Message(org.apache.qpid.proton.message.Message) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) Handler(io.vertx.core.Handler) RecordImpl(org.apache.qpid.proton.engine.impl.RecordImpl) Source(org.apache.qpid.proton.amqp.transport.Source) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) Async(io.vertx.ext.unit.Async) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Test(org.junit.Test)

Example 57 with Handler

use of io.vertx.core.Handler in project hono by eclipse.

the class HonoClientUnitTestHelper method mockContext.

/**
 * Creates a mocked vert.x Context which immediately invokes any handler that is passed to its runOnContext method.
 *
 * @param vertx The vert.x instance that the mock of the context is created for.
 * @return The mocked context.
 */
@SuppressWarnings("unchecked")
public static final Context mockContext(final Vertx vertx) {
    final Context context = mock(Context.class);
    when(context.owner()).thenReturn(vertx);
    doAnswer(invocation -> {
        Handler<Void> handler = invocation.getArgument(0);
        handler.handle(null);
        return null;
    }).when(context).runOnContext(any(Handler.class));
    return context;
}
Also used : Context(io.vertx.core.Context) Handler(io.vertx.core.Handler)

Example 58 with Handler

use of io.vertx.core.Handler in project hono by eclipse.

the class TelemetrySenderImplTest method testSendMessageDoesNotWaitForAcceptedOutcome.

/**
 * Verifies that the sender does not wait for the peer to settle and
 * accept a message before succeeding.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings({ "unchecked" })
@Test
public void testSendMessageDoesNotWaitForAcceptedOutcome(final TestContext ctx) {
    // GIVEN a sender that has credit
    when(sender.sendQueueFull()).thenReturn(Boolean.FALSE);
    MessageSender messageSender = new TelemetrySenderImpl(config, sender, "tenant", "telemetry/tenant", context);
    final AtomicReference<Handler<ProtonDelivery>> handlerRef = new AtomicReference<>();
    doAnswer(invocation -> {
        handlerRef.set(invocation.getArgument(1));
        return mock(ProtonDelivery.class);
    }).when(sender).send(any(Message.class), any(Handler.class));
    // WHEN trying to send a message
    final Future<ProtonDelivery> result = messageSender.send("device", "some payload", "application/text", "token");
    // which gets rejected by the peer
    ProtonDelivery rejected = mock(ProtonDelivery.class);
    when(rejected.remotelySettled()).thenReturn(Boolean.TRUE);
    when(rejected.getRemoteState()).thenReturn(new Rejected());
    handlerRef.get().handle(rejected);
    // THEN the resulting future is succeeded nevertheless
    assertTrue(result.succeeded());
    // and the message has been sent
    verify(sender).send(any(Message.class), eq(handlerRef.get()));
}
Also used : Message(org.apache.qpid.proton.message.Message) ProtonDelivery(io.vertx.proton.ProtonDelivery) MessageSender(org.eclipse.hono.client.MessageSender) Handler(io.vertx.core.Handler) AtomicReference(java.util.concurrent.atomic.AtomicReference) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) Test(org.junit.Test)

Example 59 with Handler

use of io.vertx.core.Handler in project hono by eclipse.

the class ConnectionFactoryImpl method handleConnectionAttemptResult.

private void handleConnectionAttemptResult(final AsyncResult<ProtonConnection> conAttempt, final ProtonClientOptions clientOptions, final Handler<AsyncResult<ProtonConnection>> closeHandler, final Handler<ProtonConnection> disconnectHandler, final Handler<AsyncResult<ProtonConnection>> connectionResultHandler) {
    if (conAttempt.failed()) {
        logger.debug("can't connect to AMQP 1.0 container [{}://{}:{}]: {}", clientOptions.isSsl() ? "amqps" : "amqp", config.getHost(), config.getPort(), conAttempt.cause().getMessage());
        connectionResultHandler.handle(Future.failedFuture(conAttempt.cause()));
    } else {
        // at this point the SASL exchange has completed successfully
        logger.debug("connected to AMQP 1.0 container [{}://{}:{}], opening connection ...", clientOptions.isSsl() ? "amqps" : "amqp", config.getHost(), config.getPort());
        ProtonConnection downstreamConnection = conAttempt.result();
        downstreamConnection.setContainer(String.format("%s-%s", config.getName(), UUID.randomUUID())).setHostname(config.getAmqpHostname()).openHandler(openCon -> {
            if (openCon.succeeded()) {
                logger.debug("connection to container [{}] at [{}://{}:{}] open", downstreamConnection.getRemoteContainer(), clientOptions.isSsl() ? "amqps" : "amqp", config.getHost(), config.getPort());
                downstreamConnection.disconnectHandler(disconnectHandler);
                downstreamConnection.closeHandler(closeHandler);
                connectionResultHandler.handle(Future.succeededFuture(downstreamConnection));
            } else {
                final ErrorCondition error = downstreamConnection.getRemoteCondition();
                if (error == null) {
                    logger.warn("can't open connection to container [{}] at [{}://{}:{}]", downstreamConnection.getRemoteContainer(), clientOptions.isSsl() ? "amqps" : "amqp", config.getHost(), config.getPort(), openCon.cause());
                } else {
                    logger.warn("can't open connection to container [{}] at [{}://{}:{}]: {} -{}", downstreamConnection.getRemoteContainer(), clientOptions.isSsl() ? "amqps" : "amqp", config.getHost(), config.getPort(), error.getCondition(), error.getDescription());
                }
                connectionResultHandler.handle(Future.failedFuture(openCon.cause()));
            }
        }).open();
    }
}
Also used : ProtonConnection(io.vertx.proton.ProtonConnection) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) Vertx(io.vertx.core.Vertx) ProtonClient(io.vertx.proton.ProtonClient) UUID(java.util.UUID) Future(io.vertx.core.Future) Objects(java.util.Objects) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) TrustOptions(io.vertx.core.net.TrustOptions) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) KeyCertOptions(io.vertx.core.net.KeyCertOptions) ProtonSaslExternalImpl(io.vertx.proton.sasl.impl.ProtonSaslExternalImpl) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) ProtonSaslPlainImpl(io.vertx.proton.sasl.impl.ProtonSaslPlainImpl) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Strings(org.eclipse.hono.util.Strings) ProtonConnection(io.vertx.proton.ProtonConnection) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition)

Example 60 with Handler

use of io.vertx.core.Handler in project hono by eclipse.

the class ConnectionFactoryImplTest method testConnectInvokesHandlerOnfailureToConnect.

/**
 * Verifies that the given result handler is invoked if a connection attempt fails.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testConnectInvokesHandlerOnfailureToConnect(final TestContext ctx) {
    // GIVEN a factory configured to connect to a non-existing server
    ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, props);
    // WHEN trying to connect to the server
    final Async handlerInvocation = ctx.async();
    ProtonClientOptions options = new ProtonClientOptions().setConnectTimeout(100);
    factory.connect(options, null, null, ctx.asyncAssertFailure(t -> {
        handlerInvocation.complete();
    }));
    // THEN the connection attempt fails and the given handler is invoked
    handlerInvocation.await(2000);
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) RunWith(org.junit.runner.RunWith) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) ProtonClient(io.vertx.proton.ProtonClient) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Mockito(org.mockito.Mockito) ArgumentCaptor(org.mockito.ArgumentCaptor) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Assert(org.junit.Assert) Handler(io.vertx.core.Handler) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Before(org.junit.Before) Async(io.vertx.ext.unit.Async) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Test(org.junit.Test)

Aggregations

Handler (io.vertx.core.Handler)119 Test (org.junit.Test)78 Future (io.vertx.core.Future)67 Vertx (io.vertx.core.Vertx)59 AsyncResult (io.vertx.core.AsyncResult)57 Context (io.vertx.core.Context)52 Buffer (io.vertx.core.buffer.Buffer)48 Async (io.vertx.ext.unit.Async)41 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)39 Map (java.util.Map)38 TestContext (io.vertx.ext.unit.TestContext)37 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)36 RunWith (org.junit.runner.RunWith)36 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)34 Collections (java.util.Collections)33 JsonObject (io.vertx.core.json.JsonObject)31 HttpURLConnection (java.net.HttpURLConnection)31 Before (org.junit.Before)31 StandardCharsets (java.nio.charset.StandardCharsets)29 TimeUnit (java.util.concurrent.TimeUnit)29