Search in sources :

Example 11 with ProtonDelivery

use of io.vertx.proton.ProtonDelivery in project hono by eclipse.

the class EventSenderImpl method sendMessage.

@Override
protected Future<ProtonDelivery> sendMessage(final Message message) {
    Objects.requireNonNull(message);
    final Future<ProtonDelivery> result = Future.future();
    final String messageId = String.format("%s-%d", getClass().getSimpleName(), MESSAGE_COUNTER.getAndIncrement());
    message.setMessageId(messageId);
    sender.send(message, deliveryUpdated -> {
        if (deliveryUpdated.remotelySettled()) {
            if (Accepted.class.isInstance(deliveryUpdated.getRemoteState())) {
                LOG.trace("event [message ID: {}] accepted by peer", messageId);
                result.complete(deliveryUpdated);
            } else if (Rejected.class.isInstance(deliveryUpdated.getRemoteState())) {
                Rejected rejected = (Rejected) deliveryUpdated.getRemoteState();
                if (rejected.getError() == null) {
                    LOG.debug("event [message ID: {}] rejected by peer", messageId);
                    result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
                } else {
                    LOG.debug("event [message ID: {}] rejected by peer: {}, {}", messageId, rejected.getError().getCondition(), rejected.getError().getDescription());
                    result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, rejected.getError().getDescription()));
                }
            } else {
                LOG.debug("event [message ID: {}] not accepted by peer: {}", messageId, deliveryUpdated.getRemoteState());
                result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
            }
        } else {
            LOG.warn("peer did not settle event, failing delivery [new remote state: {}]", deliveryUpdated.getRemoteState());
            result.fail(new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR));
        }
    });
    LOG.trace("sent event [ID: {}], remaining credit: {}, queued messages: {}", messageId, sender.getCredit(), sender.getQueued());
    return result;
}
Also used : ProtonDelivery(io.vertx.proton.ProtonDelivery) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) ServerErrorException(org.eclipse.hono.client.ServerErrorException)

Example 12 with ProtonDelivery

use of io.vertx.proton.ProtonDelivery in project hono by eclipse.

the class TelemetrySenderImpl method sendMessage.

@Override
protected Future<ProtonDelivery> sendMessage(final Message message) {
    Objects.requireNonNull(message);
    final String messageId = String.format("%s-%d", getClass().getSimpleName(), MESSAGE_COUNTER.getAndIncrement());
    message.setMessageId(messageId);
    final ProtonDelivery result = sender.send(message, deliveryUpdated -> {
        if (deliveryUpdated.remotelySettled()) {
            if (Accepted.class.isInstance(deliveryUpdated.getRemoteState())) {
                LOG.trace("message [message ID: {}] accepted by peer", messageId);
            } else if (Rejected.class.isInstance(deliveryUpdated.getRemoteState())) {
                Rejected remoteState = (Rejected) deliveryUpdated.getRemoteState();
                if (remoteState.getError() == null) {
                    LOG.debug("message [message ID: {}] rejected by peer", messageId);
                } else {
                    LOG.debug("message [message ID: {}] rejected by peer: {}, {}", messageId, remoteState.getError().getCondition(), remoteState.getError().getDescription());
                }
            } else {
                LOG.debug("message [message ID: {}] not accepted by peer: {}", messageId, deliveryUpdated.getRemoteState());
            }
        } else {
            LOG.warn("peer did not settle telemetry message [message ID: {}, remote state: {}]", messageId, deliveryUpdated.getRemoteState());
        }
    });
    LOG.trace("sent telemetry message [ID: {}], remaining credit: {}, queued messages: {}", messageId, sender.getCredit(), sender.getQueued());
    return Future.succeededFuture(result);
}
Also used : ProtonDelivery(io.vertx.proton.ProtonDelivery) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected)

Example 13 with ProtonDelivery

use of io.vertx.proton.ProtonDelivery 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 14 with ProtonDelivery

use of io.vertx.proton.ProtonDelivery in project hono by eclipse.

the class EventSenderImplTest method testSendMessageFailsOnLackOfCredit.

/**
 * Verifies that the sender fails if no credit is available.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testSendMessageFailsOnLackOfCredit(final TestContext ctx) {
    // GIVEN a sender that has no credit
    when(sender.sendQueueFull()).thenReturn(Boolean.TRUE);
    MessageSender messageSender = new EventSenderImpl(config, sender, "tenant", "telemetry/tenant", context);
    // WHEN trying to send a message
    final Future<ProtonDelivery> result = messageSender.send("device", "some payload", "application/text", "token");
    // THEN the message is not sent
    assertFalse(result.succeeded());
    verify(sender, never()).send(any(Message.class), any(Handler.class));
}
Also used : ProtonDelivery(io.vertx.proton.ProtonDelivery) Message(org.apache.qpid.proton.message.Message) MessageSender(org.eclipse.hono.client.MessageSender) Handler(io.vertx.core.Handler) Test(org.junit.Test)

Example 15 with ProtonDelivery

use of io.vertx.proton.ProtonDelivery in project hono by eclipse.

the class RegistrationClientImplTest method testAssertRegistrationAddsResponseToCacheOnCacheMiss.

/**
 * Verifies that on a cache miss the adapter retrieves registration information
 * from the Device Registration service and puts it to the cache.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testAssertRegistrationAddsResponseToCacheOnCacheMiss(final TestContext ctx) {
    // GIVEN an adapter with an empty cache
    client.setResponseCache(cache);
    // WHEN getting registration information
    final Async assertion = ctx.async();
    client.assertRegistration("device").setHandler(ctx.asyncAssertSuccess(result -> assertion.complete()));
    final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    verify(sender).send(messageCaptor.capture(), any(Handler.class));
    final JsonObject registrationAssertion = newRegistrationAssertionResult();
    final Message response = ProtonHelper.message(registrationAssertion.encode());
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    MessageHelper.addCacheDirective(response, CacheDirective.maxAgeDirective(60));
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    client.handleResponse(delivery, response);
    // THEN the registration information has been added to the cache
    verify(cache).put(eq(TriTuple.of("assert", "device", null)), any(RegistrationResult.class), any(Duration.class));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpURLConnection(java.net.HttpURLConnection) CacheDirective(org.eclipse.hono.util.CacheDirective) TestContext(io.vertx.ext.unit.TestContext) ProtonReceiver(io.vertx.proton.ProtonReceiver) Async(io.vertx.ext.unit.Async) ProtonDelivery(io.vertx.proton.ProtonDelivery) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RunWith(org.junit.runner.RunWith) ExpiringValueCache(org.eclipse.hono.cache.ExpiringValueCache) Context(io.vertx.core.Context) Assert.assertThat(org.junit.Assert.assertThat) ArgumentCaptor(org.mockito.ArgumentCaptor) Duration(java.time.Duration) RegistrationResult(org.eclipse.hono.util.RegistrationResult) Timeout(org.junit.rules.Timeout) SignatureAlgorithm(io.jsonwebtoken.SignatureAlgorithm) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) RequestResponseClientConfigProperties(org.eclipse.hono.client.RequestResponseClientConfigProperties) Before(org.junit.Before) TriTuple(org.eclipse.hono.util.TriTuple) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Instant(java.time.Instant) MessageHelper(org.eclipse.hono.util.MessageHelper) Date(java.sql.Date) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) Jwts(io.jsonwebtoken.Jwts) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) Message(org.apache.qpid.proton.message.Message) ProtonDelivery(io.vertx.proton.ProtonDelivery) Async(io.vertx.ext.unit.Async) Handler(io.vertx.core.Handler) JsonObject(io.vertx.core.json.JsonObject) Duration(java.time.Duration) RegistrationResult(org.eclipse.hono.util.RegistrationResult) Test(org.junit.Test)

Aggregations

ProtonDelivery (io.vertx.proton.ProtonDelivery)38 Test (org.junit.Test)31 Message (org.apache.qpid.proton.message.Message)29 Handler (io.vertx.core.Handler)21 ProtonSender (io.vertx.proton.ProtonSender)15 Rejected (org.apache.qpid.proton.amqp.messaging.Rejected)15 ProtonReceiver (io.vertx.proton.ProtonReceiver)13 Async (io.vertx.ext.unit.Async)12 Vertx (io.vertx.core.Vertx)11 ProtonHelper (io.vertx.proton.ProtonHelper)11 JsonObject (io.vertx.core.json.JsonObject)10 TestContext (io.vertx.ext.unit.TestContext)10 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)10 Before (org.junit.Before)10 Rule (org.junit.Rule)10 RunWith (org.junit.runner.RunWith)10 ArgumentCaptor (org.mockito.ArgumentCaptor)10 Mockito (org.mockito.Mockito)10 Context (io.vertx.core.Context)9 HttpURLConnection (java.net.HttpURLConnection)9