Search in sources :

Example 11 with Device

use of org.eclipse.hono.auth.Device 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 12 with Device

use of org.eclipse.hono.auth.Device in project hono by eclipse.

the class DeviceInfoSupplier method getInfo.

/**
 * {@inheritDoc}
 */
@Override
public AdditionalInfo getInfo(final Principal clientIdentity, final Object customArgument) {
    if (customArgument instanceof AdditionalInfo) {
        final AdditionalInfo info = (AdditionalInfo) customArgument;
        final String authId = info.get(EXT_INFO_KEY_HONO_AUTH_ID, String.class);
        final Device device = info.get(EXT_INFO_KEY_HONO_DEVICE, Device.class);
        LOG.debug("get additional info auth-id: {}, device: {}@{}", authId, device.getDeviceId(), device.getTenantId());
        return info;
    }
    LOG.debug("get no additional info");
    return AdditionalInfo.empty();
}
Also used : AdditionalInfo(org.eclipse.californium.elements.auth.AdditionalInfo) Device(org.eclipse.hono.auth.Device)

Example 13 with Device

use of org.eclipse.hono.auth.Device in project hono by eclipse.

the class MqttContextTest method verifyPropertyBagRetrievedFromTopic.

/**
 * Verifies the values retrieved from the <em>property-bag</em> of a message's topic.
 */
@Test
public void verifyPropertyBagRetrievedFromTopic() {
    final Device device = new Device("tenant", "device");
    final MqttPublishMessage msg = mock(MqttPublishMessage.class);
    when(msg.topicName()).thenReturn("event/tenant/device/?param1=value1&param2=value2");
    final MqttContext context = MqttContext.fromPublishPacket(msg, mock(MqttEndpoint.class), span, device);
    assertNotNull(context.propertyBag());
    assertEquals("value1", context.propertyBag().getProperty("param1"));
    assertEquals("value2", context.propertyBag().getProperty("param2"));
    assertEquals("event/tenant/device", context.topic().toString());
}
Also used : MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) Device(org.eclipse.hono.auth.Device) Test(org.junit.jupiter.api.Test)

Example 14 with Device

use of org.eclipse.hono.auth.Device in project hono by eclipse.

the class MqttContextTest method verifyContentType.

/**
 * Verifies the <em>content-type</em> value retrieved from the <em>property-bag</em> in a message's topic.
 */
@Test
public void verifyContentType() {
    final String contentType = "application/vnd.eclipse.ditto+json";
    final String encodedContentType = URLEncoder.encode(contentType, StandardCharsets.UTF_8);
    final Device device = new Device("tenant", "device");
    final MqttPublishMessage msg = mock(MqttPublishMessage.class);
    when(msg.topicName()).thenReturn(String.format("event/tenant/device/?Content-Type=%s&param2=value2&param3=value3", encodedContentType));
    final MqttContext context = MqttContext.fromPublishPacket(msg, mock(MqttEndpoint.class), span, device);
    assertNotNull(context.propertyBag());
    assertEquals(contentType, context.propertyBag().getProperty(MessageHelper.SYS_PROPERTY_CONTENT_TYPE));
}
Also used : MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) Device(org.eclipse.hono.auth.Device) Test(org.junit.jupiter.api.Test)

Example 15 with Device

use of org.eclipse.hono.auth.Device in project hono by eclipse.

the class HttpBasedMessageMappingTest method testMapMessageSucceeds.

/**
 * Verifies that the result returned by the mapping service contains the
 * mapped payload, device ID and additional properties.
 *
 * @param ctx The helper to use for running tests on vert.x.
 */
@SuppressWarnings("unchecked")
@Test
public void testMapMessageSucceeds(final VertxTestContext ctx) {
    config.setMapperEndpoints(Map.of("mapper", MapperEndpoint.from("host", 1234, "/uri", false)));
    final ResourceIdentifier targetAddress = ResourceIdentifier.from(TelemetryConstants.TELEMETRY_ENDPOINT, TEST_TENANT_ID, "gateway");
    final String newDeviceId = "new-device";
    final HttpRequest<Buffer> httpRequest = mock(HttpRequest.class, withSettings().defaultAnswer(RETURNS_SELF));
    final MultiMap responseHeaders = MultiMap.caseInsensitiveMultiMap();
    responseHeaders.add(MessageHelper.APP_PROPERTY_DEVICE_ID, newDeviceId);
    responseHeaders.add("foo", "bar");
    final Buffer responseBody = Buffer.buffer("changed");
    final HttpResponse<Buffer> httpResponse = mock(HttpResponse.class);
    when(httpResponse.headers()).thenReturn(responseHeaders);
    when(httpResponse.bodyAsBuffer()).thenReturn(responseBody);
    when(httpResponse.statusCode()).thenReturn(HttpURLConnection.HTTP_OK);
    when(mapperWebClient.post(anyInt(), anyString(), anyString())).thenReturn(httpRequest);
    final String topic = String.format("%s/?content-type=%s", TelemetryConstants.TELEMETRY_ENDPOINT, URLEncoder.encode("text/plain", StandardCharsets.UTF_8));
    final MqttPublishMessage message = newMessage(MqttQoS.AT_LEAST_ONCE, topic);
    final MqttContext context = newContext(message, span, new Device(TEST_TENANT_ID, "gateway"));
    final RegistrationAssertion assertion = new RegistrationAssertion("gateway").setDownstreamMessageMapper("mapper");
    messageMapping.mapDownstreamMessage(context, targetAddress, assertion).onComplete(ctx.succeeding(mappedMessage -> {
        ctx.verify(() -> {
            assertThat(mappedMessage.getTargetAddress().getResourceId()).isEqualTo("new-device");
            assertThat(mappedMessage.getPayload()).isEqualTo(responseBody);
            assertThat(mappedMessage.getAdditionalProperties()).doesNotContainKey(MessageHelper.APP_PROPERTY_DEVICE_ID);
            assertThat(mappedMessage.getAdditionalProperties()).containsEntry("foo", "bar");
        });
        ctx.completeNow();
    }));
    final ArgumentCaptor<Handler<AsyncResult<HttpResponse<Buffer>>>> handleCaptor = VertxMockSupport.argumentCaptorHandler();
    verify(httpRequest).sendBuffer(any(Buffer.class), handleCaptor.capture());
    handleCaptor.getValue().handle(Future.succeededFuture(httpResponse));
    final ArgumentCaptor<MultiMap> headersCaptor = ArgumentCaptor.forClass(MultiMap.class);
    verify(httpRequest).putHeaders(headersCaptor.capture());
    final MultiMap addedHeaders = headersCaptor.getValue();
    assertThat(addedHeaders.contains(MessageHelper.APP_PROPERTY_ORIG_ADDRESS, topic, false)).isTrue();
    assertThat(addedHeaders.contains(HttpHeaders.CONTENT_TYPE.toString(), "text/plain", false));
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) HttpResponse(io.vertx.ext.web.client.HttpResponse) WebClient(io.vertx.ext.web.client.WebClient) Command(org.eclipse.hono.client.command.Command) MultiMap(io.vertx.core.MultiMap) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) Constants(org.eclipse.hono.util.Constants) RETURNS_SELF(org.mockito.Mockito.RETURNS_SELF) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Map(java.util.Map) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) AsyncResult(io.vertx.core.AsyncResult) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) MapperEndpoint(org.eclipse.hono.config.MapperEndpoint) ServerErrorException(org.eclipse.hono.client.ServerErrorException) HttpHeaders(io.vertx.core.http.HttpHeaders) Mockito.times(org.mockito.Mockito.times) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) Device(org.eclipse.hono.auth.Device) Mockito.verify(org.mockito.Mockito.verify) HttpRequest(io.vertx.ext.web.client.HttpRequest) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) URLEncoder(java.net.URLEncoder) Buffer(io.vertx.core.buffer.Buffer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) MqttProtocolAdapterProperties(org.eclipse.hono.adapter.mqtt.MqttProtocolAdapterProperties) Span(io.opentracing.Span) Mockito.withSettings(org.mockito.Mockito.withSettings) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) Device(org.eclipse.hono.auth.Device) Handler(io.vertx.core.Handler) HttpResponse(io.vertx.ext.web.client.HttpResponse) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) MultiMap(io.vertx.core.MultiMap) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Test(org.junit.jupiter.api.Test)

Aggregations

Device (org.eclipse.hono.auth.Device)115 HttpURLConnection (java.net.HttpURLConnection)74 Test (org.junit.jupiter.api.Test)72 Future (io.vertx.core.Future)69 ClientErrorException (org.eclipse.hono.client.ClientErrorException)67 Buffer (io.vertx.core.buffer.Buffer)66 Handler (io.vertx.core.Handler)63 TenantObject (org.eclipse.hono.util.TenantObject)63 Promise (io.vertx.core.Promise)59 Constants (org.eclipse.hono.util.Constants)58 Span (io.opentracing.Span)55 RegistrationAssertion (org.eclipse.hono.util.RegistrationAssertion)55 SpanContext (io.opentracing.SpanContext)53 VertxTestContext (io.vertx.junit5.VertxTestContext)52 VertxExtension (io.vertx.junit5.VertxExtension)51 MessageHelper (org.eclipse.hono.util.MessageHelper)51 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)51 Mockito.when (org.mockito.Mockito.when)51 Truth.assertThat (com.google.common.truth.Truth.assertThat)50 ResourceIdentifier (org.eclipse.hono.util.ResourceIdentifier)47