Search in sources :

Example 1 with Adapter

use of org.eclipse.hono.util.Adapter in project hono by eclipse.

the class AbstractVertxBasedHttpProtocolAdapterTest method testUploadTelemetryUsesConfiguredMaxTtd.

/**
 * Verifies that the adapter uses the max TTD configured for the adapter if a device provides
 * a TTD value that is greater than the max value.
 */
@Test
public void testUploadTelemetryUsesConfiguredMaxTtd() {
    // GIVEN an adapter with a downstream telemetry consumer attached
    givenAnAdapter(properties);
    givenATelemetrySenderForAnyTenant();
    // WHEN a device publishes a telemetry message that belongs to a tenant with
    // a max TTD of 20 secs
    final TenantObject tenant = TenantObject.from("tenant", true).addAdapter(new Adapter(ADAPTER_TYPE).setEnabled(Boolean.TRUE).setExtensions(Map.of(TenantConstants.FIELD_MAX_TTD, 20)));
    when(tenantClient.get(eq("tenant"), any())).thenReturn(Future.succeededFuture(tenant));
    // and includes a TTD value of 40 in its request
    final Buffer payload = Buffer.buffer("some payload");
    final HttpServerResponse response = mock(HttpServerResponse.class);
    final HttpServerRequest request = mock(HttpServerRequest.class);
    when(request.getHeader(eq(Constants.HEADER_TIME_TILL_DISCONNECT))).thenReturn("40");
    final HttpContext ctx = newHttpContext(payload, "text/plain", request, response);
    adapter.uploadTelemetryMessage(ctx, "tenant", "device");
    // THEN the device receives a 202 response immediately
    verify(response).setStatusCode(202);
    verify(response).end();
    // and the downstream message contains the configured max TTD
    verify(telemetrySender).sendTelemetry(eq(tenant), argThat(assertion -> assertion.getDeviceId().equals("device")), eq(org.eclipse.hono.util.QoS.AT_MOST_ONCE), eq("text/plain"), any(Buffer.class), argThat(props -> props.get(MessageHelper.APP_PROPERTY_DEVICE_TTD).equals(20)), any());
}
Also used : Buffer(io.vertx.core.buffer.Buffer) HttpURLConnection(java.net.HttpURLConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) TenantConstants(org.eclipse.hono.util.TenantConstants) HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router) MIMEHeader(io.vertx.ext.web.MIMEHeader) RoutingContext(io.vertx.ext.web.RoutingContext) Context(io.vertx.core.Context) Timeout(io.vertx.junit5.Timeout) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) TtdStatus(org.eclipse.hono.service.metric.MetricsTags.TtdStatus) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Map(java.util.Map) ParsedHeaderValues(io.vertx.ext.web.ParsedHeaderValues) CommandContext(org.eclipse.hono.client.command.CommandContext) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) Test(org.junit.jupiter.api.Test) Buffer(io.vertx.core.buffer.Buffer) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Optional(java.util.Optional) Span(io.opentracing.Span) QoS(org.eclipse.hono.util.QoS) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) HttpContext(org.eclipse.hono.service.http.HttpContext) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) TracingHandler(org.eclipse.hono.service.http.TracingHandler) ProtocolAdapterTestSupport(org.eclipse.hono.adapter.test.ProtocolAdapterTestSupport) ArgumentCaptor(org.mockito.ArgumentCaptor) HttpUtils(org.eclipse.hono.service.http.HttpUtils) AsyncResult(io.vertx.core.AsyncResult) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) TimeUnit(java.util.concurrent.TimeUnit) Mockito.never(org.mockito.Mockito.never) Adapter(org.eclipse.hono.util.Adapter) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) TenantObject(org.eclipse.hono.util.TenantObject) HttpServerResponse(io.vertx.core.http.HttpServerResponse) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpContext(org.eclipse.hono.service.http.HttpContext) Adapter(org.eclipse.hono.util.Adapter) Test(org.junit.jupiter.api.Test)

Example 2 with Adapter

use of org.eclipse.hono.util.Adapter in project hono by eclipse.

the class CoapContextTest method testStartAckTimerDoesNotStartTimer.

/**
 * Verifies that no ACK timer is started for a timeout value <= 0.
 */
@ParameterizedTest
@ValueSource(longs = { -1L, 0L })
void testStartAckTimerDoesNotStartTimer(final long timeout) {
    final CoapExchange exchange = mock(CoapExchange.class);
    final Adapter coapConfig = new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_COAP);
    // never send separate ACK
    coapConfig.putExtension(CoapConstants.TIMEOUT_TO_ACK, -1L);
    final TenantObject tenant = TenantObject.from("tenant", true).addAdapter(coapConfig);
    final Device authenticatedDevice = new Device(tenant.getTenantId(), "device-id");
    final CoapContext ctx = CoapContext.fromRequest(exchange, authenticatedDevice, authenticatedDevice, "4711", span);
    ctx.startAcceptTimer(vertx, tenant, timeout);
    verify(vertx, never()).setTimer(anyLong(), VertxMockSupport.anyHandler());
}
Also used : TenantObject(org.eclipse.hono.util.TenantObject) Device(org.eclipse.hono.auth.Device) Adapter(org.eclipse.hono.util.Adapter) CoapExchange(org.eclipse.californium.core.server.resources.CoapExchange) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 3 with Adapter

use of org.eclipse.hono.util.Adapter in project hono by eclipse.

the class CoapContextTest method testStartAckTimerUsesTenantSpecificTimeout.

/**
 * Verifies that the tenant specific value set for the ACK timeout gets
 * precedence over the global adapter configuration.
 */
@Test
void testStartAckTimerUsesTenantSpecificTimeout() {
    final CoapExchange exchange = mock(CoapExchange.class);
    final Adapter coapConfig = new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_COAP);
    coapConfig.putExtension(CoapConstants.TIMEOUT_TO_ACK, 200);
    final TenantObject tenant = TenantObject.from("tenant", true).addAdapter(coapConfig);
    final Device authenticatedDevice = new Device(tenant.getTenantId(), "device-id");
    final CoapContext ctx = CoapContext.fromRequest(exchange, authenticatedDevice, authenticatedDevice, "4711", span);
    ctx.startAcceptTimer(vertx, tenant, 500);
    verify(vertx).setTimer(eq(200L), VertxMockSupport.anyHandler());
}
Also used : TenantObject(org.eclipse.hono.util.TenantObject) Device(org.eclipse.hono.auth.Device) Adapter(org.eclipse.hono.util.Adapter) CoapExchange(org.eclipse.californium.core.server.resources.CoapExchange) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 4 with Adapter

use of org.eclipse.hono.util.Adapter in project hono by eclipse.

the class CoapContextTest method testStartAckTimerHandlesNonNumberPropertyValue.

/**
 * Verifies that the global ACK timeout is used if a tenant specific value is configured that is not a number.
 */
@Test
void testStartAckTimerHandlesNonNumberPropertyValue() {
    final CoapExchange exchange = mock(CoapExchange.class);
    final Adapter coapConfig = new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_COAP);
    coapConfig.putExtension(CoapConstants.TIMEOUT_TO_ACK, "not-a-number");
    final TenantObject tenant = TenantObject.from("tenant", true).addAdapter(coapConfig);
    final Device authenticatedDevice = new Device(tenant.getTenantId(), "device-id");
    final CoapContext ctx = CoapContext.fromRequest(exchange, authenticatedDevice, authenticatedDevice, "4711", span);
    ctx.startAcceptTimer(vertx, tenant, 500);
    verify(vertx).setTimer(eq(500L), VertxMockSupport.anyHandler());
}
Also used : TenantObject(org.eclipse.hono.util.TenantObject) Device(org.eclipse.hono.auth.Device) Adapter(org.eclipse.hono.util.Adapter) CoapExchange(org.eclipse.californium.core.server.resources.CoapExchange) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 5 with Adapter

use of org.eclipse.hono.util.Adapter in project hono by eclipse.

the class AbstractVertxBasedMqttProtocolAdapterTest method testMessageLimitExceededForACommandResponseMessage.

/**
 * Verifies that a command response message is rejected due to the limit exceeded.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testMessageLimitExceededForACommandResponseMessage(final VertxTestContext ctx) {
    // GIVEN an adapter
    givenAnAdapter(properties);
    final CommandResponseSender sender = givenACommandResponseSenderForAnyTenant();
    // WHEN the message limit exceeds
    when(resourceLimitChecks.isMessageLimitReached(any(TenantObject.class), anyLong(), any(SpanContext.class))).thenReturn(Future.succeededFuture(Boolean.TRUE));
    // WHEN a device of "tenant" publishes a command response message
    final MqttPublishMessage msg = mock(MqttPublishMessage.class);
    when(msg.topicName()).thenReturn("e/tenant/device");
    when(msg.qosLevel()).thenReturn(MqttQoS.AT_MOST_ONCE);
    when(msg.payload()).thenReturn(Buffer.buffer("test"));
    adapter.uploadMessage(newMqttContext(msg, mockEndpoint(), span), ResourceIdentifier.fromString(String.format("%s/tenant/device/res/%s/200", getCommandEndpoint(), Commands.encodeRequestIdParameters("cmd123", "to", "deviceId", MessagingType.amqp))), msg).onComplete(ctx.failing(t -> {
        ctx.verify(() -> {
            // THEN the request fails with a 429 error
            assertThat(((ClientErrorException) t).getErrorCode()).isEqualTo(HttpUtils.HTTP_TOO_MANY_REQUESTS);
            // AND the response is not being forwarded
            verify(sender, never()).sendCommandResponse(any(TenantObject.class), any(RegistrationAssertion.class), any(CommandResponse.class), (SpanContext) any());
            // AND has reported the message as unprocessable
            verify(metrics).reportCommand(eq(MetricsTags.Direction.RESPONSE), eq("tenant"), any(), eq(MetricsTags.ProcessingOutcome.UNPROCESSABLE), anyInt(), any());
        });
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) Context(io.vertx.core.Context) Timeout(io.vertx.junit5.Timeout) AfterAll(org.junit.jupiter.api.AfterAll) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) MessagingType(org.eclipse.hono.util.MessagingType) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BeforeAll(org.junit.jupiter.api.BeforeAll) Mockito.doAnswer(org.mockito.Mockito.doAnswer) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) AuthHandler(org.eclipse.hono.adapter.auth.device.AuthHandler) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Instant(java.time.Instant) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Test(org.junit.jupiter.api.Test) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) QoS(org.eclipse.hono.util.QoS) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) AbstractNotification(org.eclipse.hono.notification.AbstractNotification) VertxTestContext(io.vertx.junit5.VertxTestContext) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) MqttConnectReturnCode(io.netty.handler.codec.mqtt.MqttConnectReturnCode) ClientErrorException(org.eclipse.hono.client.ClientErrorException) OptionalInt(java.util.OptionalInt) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) Commands(org.eclipse.hono.client.command.Commands) Constants(org.eclipse.hono.util.Constants) ArrayList(java.util.ArrayList) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) MqttServer(io.vertx.mqtt.MqttServer) ProtocolAdapterTestSupport(org.eclipse.hono.adapter.test.ProtocolAdapterTestSupport) SSLSession(javax.net.ssl.SSLSession) ArgumentCaptor(org.mockito.ArgumentCaptor) MqttTopicSubscription(io.vertx.mqtt.MqttTopicSubscription) BiConsumer(java.util.function.BiConsumer) HttpUtils(org.eclipse.hono.service.http.HttpUtils) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) Promise(io.vertx.core.Promise) MqttSubscribeMessage(io.vertx.mqtt.messages.MqttSubscribeMessage) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) TimeUnit(java.util.concurrent.TimeUnit) Mockito.never(org.mockito.Mockito.never) Adapter(org.eclipse.hono.util.Adapter) ConnectionAttemptOutcome(org.eclipse.hono.service.metric.MetricsTags.ConnectionAttemptOutcome) MqttAuth(io.vertx.mqtt.MqttAuth) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) Handler(io.vertx.core.Handler) Collections(java.util.Collections) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) Test(org.junit.jupiter.api.Test)

Aggregations

Adapter (org.eclipse.hono.util.Adapter)77 Test (org.junit.jupiter.api.Test)74 Truth.assertThat (com.google.common.truth.Truth.assertThat)64 VertxTestContext (io.vertx.junit5.VertxTestContext)64 HttpURLConnection (java.net.HttpURLConnection)64 Timeout (io.vertx.junit5.Timeout)63 TimeUnit (java.util.concurrent.TimeUnit)63 Constants (org.eclipse.hono.util.Constants)62 Future (io.vertx.core.Future)61 Promise (io.vertx.core.Promise)61 JsonObject (io.vertx.core.json.JsonObject)47 Tenant (org.eclipse.hono.service.management.tenant.Tenant)47 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)47 IntegrationTestSupport (org.eclipse.hono.tests.IntegrationTestSupport)45 Tenants (org.eclipse.hono.tests.Tenants)45 BeforeEach (org.junit.jupiter.api.BeforeEach)45 RegistryManagementConstants (org.eclipse.hono.util.RegistryManagementConstants)44 VertxExtension (io.vertx.junit5.VertxExtension)42 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)42 Buffer (io.vertx.core.buffer.Buffer)40