Search in sources :

Example 41 with Handler

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

the class TestSupport method newMockSender.

@SuppressWarnings("unchecked")
public static ProtonSender newMockSender(final boolean drainFlag) {
    @SuppressWarnings("rawtypes") final ArgumentCaptor<Handler> drainHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
    Record attachments = mock(Record.class);
    ProtonSender sender = mock(ProtonSender.class);
    when(sender.attachments()).thenReturn(attachments);
    when(sender.isOpen()).thenReturn(Boolean.TRUE);
    when(sender.getCredit()).thenReturn(DEFAULT_CREDITS);
    when(sender.getQueued()).thenReturn(0);
    when(sender.getDrain()).thenReturn(drainFlag);
    when(sender.open()).then(invocation -> {
        drainHandlerCaptor.getValue().handle(sender);
        return sender;
    });
    when(sender.sendQueueDrainHandler(drainHandlerCaptor.capture())).then(invocation -> {
        return sender;
    });
    Target target = new Target();
    target.setAddress(DEFAULT_ADDRESS);
    when(sender.getTarget()).thenReturn(target);
    return sender;
}
Also used : ProtonSender(io.vertx.proton.ProtonSender) Target(org.apache.qpid.proton.amqp.messaging.Target) Handler(io.vertx.core.Handler) Record(org.apache.qpid.proton.engine.Record)

Example 42 with Handler

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

the class ForwardingEventDownstreamAdapterTest method testProcessMessageForwardsMessageToDownstreamSender.

/**
 * Verifies that an event uploaded by an upstream client is forwarded to the
 * downstream container.
 *
 * @param ctx The test context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testProcessMessageForwardsMessageToDownstreamSender(final TestContext ctx) {
    final UpstreamReceiver client = newClient();
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    final ProtonDelivery downstreamDelivery = mock(ProtonDelivery.class);
    when(downstreamDelivery.getRemoteState()).thenReturn(ACCEPTED);
    when(downstreamDelivery.remotelySettled()).thenReturn(true);
    // GIVEN an adapter with a connection to a downstream container
    final Async msgSent = ctx.async();
    ProtonSender sender = newMockSender(false);
    when(sender.send(any(Message.class), any(Handler.class))).then(invocation -> {
        msgSent.complete();
        final Handler handler = invocation.getArgument(1);
        handler.handle(downstreamDelivery);
        return null;
    });
    ForwardingEventDownstreamAdapter adapter = new ForwardingEventDownstreamAdapter(vertx, newMockSenderFactory(sender));
    adapter.setMetrics(mock(MessagingMetrics.class));
    adapter.setDownstreamConnectionFactory(newMockConnectionFactory(false));
    adapter.start(Future.future());
    adapter.addSender(client, sender);
    // WHEN processing an event
    Message msg = ProtonHelper.message(EVENT_MSG_CONTENT);
    MessageHelper.addDeviceId(msg, DEVICE_ID);
    adapter.processMessage(client, delivery, msg);
    // THEN the message has been delivered to the downstream container
    msgSent.await(1000);
    // and disposition was returned
    verify(delivery).disposition(any(Accepted.class), eq(Boolean.TRUE));
}
Also used : ProtonSender(io.vertx.proton.ProtonSender) ProtonDelivery(io.vertx.proton.ProtonDelivery) Message(org.apache.qpid.proton.message.Message) Async(io.vertx.ext.unit.Async) Handler(io.vertx.core.Handler) UpstreamReceiver(org.eclipse.hono.messaging.UpstreamReceiver) MessagingMetrics(org.eclipse.hono.messaging.MessagingMetrics) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) Test(org.junit.Test)

Example 43 with Handler

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

the class ForwardingDownstreamAdapterTest method testDownstreamLinkHandlerClosesUpstreamReceiver.

@SuppressWarnings({ "unchecked", "rawtypes" })
private void testDownstreamLinkHandlerClosesUpstreamReceiver(final BiConsumer<ProtonSender, ArgumentCaptor<Handler>> handlerCaptor) {
    final UpstreamReceiver client = newClient();
    final ProtonSender downstreamSender = newMockSender(false);
    when(downstreamSender.isOpen()).thenReturn(Boolean.FALSE);
    final HandlerCapturingConnectionFactory factory = new HandlerCapturingConnectionFactory(con);
    // GIVEN an adapter connected to a downstream container
    givenADownstreamAdapter(downstreamSender);
    adapter.setDownstreamConnectionFactory(factory);
    adapter.start(Future.future());
    adapter.onClientAttach(client, s -> {
    });
    final ArgumentCaptor<Handler> captor = ArgumentCaptor.forClass(Handler.class);
    handlerCaptor.accept(downstreamSender, captor);
    // WHEN the downstream container detaches the sender link
    captor.getValue().handle(Future.succeededFuture(downstreamSender));
    // THEN the upstream client is closed
    verify(client).close(any());
    // and the sender is removed from the list of active senders
    assertTrue(adapter.isActiveSendersEmpty());
}
Also used : ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler)

Example 44 with Handler

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

the class BaseRegistrationService method assertRegistration.

/**
 * {@inheritDoc}
 * <p>
 * Subclasses may override this method in order to implement a more sophisticated approach for asserting registration status, e.g.
 * using cached information etc.
 */
@Override
public void assertRegistration(final String tenantId, final String deviceId, final String gatewayId, final Handler<AsyncResult<RegistrationResult>> resultHandler) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(gatewayId);
    Objects.requireNonNull(resultHandler);
    Future<RegistrationResult> deviceInfoTracker = Future.future();
    Future<RegistrationResult> gatewayInfoTracker = Future.future();
    getDevice(tenantId, deviceId, deviceInfoTracker.completer());
    getDevice(tenantId, gatewayId, gatewayInfoTracker.completer());
    CompositeFuture.all(deviceInfoTracker, gatewayInfoTracker).compose(ok -> {
        final RegistrationResult deviceResult = deviceInfoTracker.result();
        final RegistrationResult gatewayResult = gatewayInfoTracker.result();
        if (!isDeviceEnabled(deviceResult)) {
            return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_NOT_FOUND));
        } else if (!isDeviceEnabled(gatewayResult)) {
            return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_FORBIDDEN));
        } else {
            final JsonObject deviceData = deviceResult.getPayload().getJsonObject(RegistrationConstants.FIELD_DATA, new JsonObject());
            final JsonObject gatewayData = gatewayResult.getPayload().getJsonObject(RegistrationConstants.FIELD_DATA, new JsonObject());
            if (isGatewayAuthorized(gatewayId, gatewayData, deviceId, deviceData)) {
                return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_OK, getAssertionPayload(tenantId, deviceId, deviceData), CacheDirective.maxAgeDirective(assertionFactory.getAssertionLifetime())));
            } else {
                return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_FORBIDDEN));
            }
        }
    }).setHandler(resultHandler);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CacheDirective(org.eclipse.hono.util.CacheDirective) Autowired(org.springframework.beans.factory.annotation.Autowired) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) ClientErrorException(org.eclipse.hono.client.ClientErrorException) EventBusMessage(org.eclipse.hono.util.EventBusMessage) Future(io.vertx.core.Future) Objects(java.util.Objects) EventBusService(org.eclipse.hono.service.EventBusService) CompositeFuture(io.vertx.core.CompositeFuture) RegistrationResult(org.eclipse.hono.util.RegistrationResult) Qualifier(org.springframework.beans.factory.annotation.Qualifier) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) JsonObject(io.vertx.core.json.JsonObject) RegistrationResult(org.eclipse.hono.util.RegistrationResult)

Example 45 with Handler

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

the class AmqpServiceBaseTest method testServerCallsPublishEventOnClientDisconnect.

/**
 * Verifies that the service invokes the <em>publishConnectionClosedEvent</em>
 * method when a client disconnects.
 */
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testServerCallsPublishEventOnClientDisconnect() {
    // GIVEN a server to which a client is connected
    final Handler<ProtonConnection> publishConnectionClosedEvent = mock(Handler.class);
    final AmqpServiceBase<ServiceConfigProperties> server = createServer(null, publishConnectionClosedEvent);
    final ProtonConnection con = newConnection(Constants.PRINCIPAL_ANONYMOUS);
    server.onRemoteConnectionOpen(con);
    final ArgumentCaptor<Handler> closeHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
    verify(con).disconnectHandler(closeHandlerCaptor.capture());
    // WHEN the client disconnects from the service
    closeHandlerCaptor.getValue().handle(con);
    // THEN the publishConnectionClosedEvent method is invoked
    verify(publishConnectionClosedEvent).handle(any(ProtonConnection.class));
}
Also used : ProtonConnection(io.vertx.proton.ProtonConnection) Handler(io.vertx.core.Handler) ServiceConfigProperties(org.eclipse.hono.config.ServiceConfigProperties) 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