Search in sources :

Example 16 with HttpContext

use of org.eclipse.hono.service.http.HttpContext in project hono by eclipse.

the class LoraProtocolAdapterTest method handleCommandForLNS.

/**
 * Verifies that an uplink message triggers a command subscription.
 */
@SuppressWarnings("unchecked")
@Test
public void handleCommandForLNS() {
    givenATelemetrySenderForAnyTenant();
    final LoraProvider providerMock = getLoraProviderMock();
    final HttpServerRequest request = mock(HttpServerRequest.class);
    final HttpContext httpContext = newHttpContext();
    when(httpContext.request()).thenReturn(request);
    final CommandEndpoint commandEndpoint = new CommandEndpoint();
    commandEndpoint.setHeaders(Map.of("my-header", "my-header-value"));
    commandEndpoint.setUri("https://my-server.com/commands/{{deviceId}}/send");
    setGatewayDeviceCommandEndpoint(commandEndpoint);
    final CommandConsumer commandConsumer = mock(CommandConsumer.class);
    when(commandConsumer.close(any())).thenReturn(Future.succeededFuture());
    when(commandConsumerFactory.createCommandConsumer(any(), any(), any(), any(), any())).thenReturn(Future.succeededFuture(commandConsumer));
    adapter.handleProviderRoute(httpContext, providerMock);
    final ArgumentCaptor<Handler<CommandContext>> handlerArgumentCaptor = VertxMockSupport.argumentCaptorHandler();
    verify(commandConsumerFactory).createCommandConsumer(eq(TEST_TENANT_ID), eq(TEST_GATEWAY_ID), handlerArgumentCaptor.capture(), isNull(), any());
    final Handler<CommandContext> commandHandler = handlerArgumentCaptor.getValue();
    final Command command = mock(Command.class);
    when(command.getTenant()).thenReturn(TEST_TENANT_ID);
    when(command.getDeviceId()).thenReturn(TEST_DEVICE_ID);
    when(command.getGatewayId()).thenReturn(TEST_GATEWAY_ID);
    when(command.getPayload()).thenReturn(Buffer.buffer("bumlux"));
    when(command.isValid()).thenReturn(true);
    final CommandContext commandContext = mock(CommandContext.class);
    when(commandContext.getCommand()).thenReturn(command);
    when(commandContext.getTracingSpan()).thenReturn(processMessageSpan);
    final JsonObject json = new JsonObject().put("my-payload", "bumlux");
    final LoraCommand loraCommand = new LoraCommand(json, "https://my-server.com/commands/deviceId/send");
    when(providerMock.getCommand(any(), any(), any(), any())).thenReturn(loraCommand);
    when(providerMock.getDefaultHeaders()).thenReturn(Map.of("my-provider-header", "my-provider-header-value"));
    final HttpRequest<Buffer> httpClientRequest = mock(HttpRequest.class, withSettings().defaultAnswer(RETURNS_SELF));
    final HttpResponse<Buffer> httpResponse = mock(HttpResponse.class);
    when(httpResponse.statusCode()).thenReturn(HttpURLConnection.HTTP_NO_CONTENT);
    when(httpClientRequest.sendJson(any(JsonObject.class))).thenReturn(Future.succeededFuture(httpResponse));
    when(webClient.postAbs(anyString())).thenReturn(httpClientRequest);
    commandHandler.handle(commandContext);
    verify(webClient, times(1)).postAbs("https://my-server.com/commands/deviceId/send");
    verify(httpClientRequest, times(1)).putHeader("my-header", "my-header-value");
    verify(httpClientRequest, times(1)).putHeader("my-provider-header", "my-provider-header-value");
    verify(httpClientRequest, times(1)).sendJson(json);
}
Also used : Buffer(io.vertx.core.buffer.Buffer) LoraProvider(org.eclipse.hono.adapter.lora.providers.LoraProvider) CommandContext(org.eclipse.hono.client.command.CommandContext) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpContext(org.eclipse.hono.service.http.HttpContext) TracingHandler(org.eclipse.hono.service.http.TracingHandler) Handler(io.vertx.core.Handler) JsonObject(io.vertx.core.json.JsonObject) Command(org.eclipse.hono.client.command.Command) CommandEndpoint(org.eclipse.hono.util.CommandEndpoint) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Test(org.junit.jupiter.api.Test)

Example 17 with HttpContext

use of org.eclipse.hono.service.http.HttpContext in project hono by eclipse.

the class LoraProtocolAdapterTest method handleProviderRouteSuccessfullyForOptionsRequest.

/**
 * Verifies that an options request is routed to a provider correctly.
 */
@Test
public void handleProviderRouteSuccessfullyForOptionsRequest() {
    final HttpContext httpContext = newHttpContext();
    adapter.handleOptionsRoute(httpContext.getRoutingContext());
    verify(httpContext.getRoutingContext().response()).setStatusCode(HttpResponseStatus.OK.code());
}
Also used : HttpContext(org.eclipse.hono.service.http.HttpContext) Test(org.junit.jupiter.api.Test)

Example 18 with HttpContext

use of org.eclipse.hono.service.http.HttpContext in project hono by eclipse.

the class HonoBasicAuthHandler method authenticate.

@Override
public void authenticate(final RoutingContext context, final Handler<AsyncResult<User>> handler) {
    parseAuthorization(context, parseAuthorization -> {
        if (parseAuthorization.failed()) {
            handler.handle(Future.failedFuture(parseAuthorization.cause()));
            return;
        }
        final String suser;
        final String spass;
        try {
            // decode the payload
            final String decoded = new String(Base64.getDecoder().decode(parseAuthorization.result()));
            final int colonIdx = decoded.indexOf(":");
            if (colonIdx != -1) {
                suser = decoded.substring(0, colonIdx);
                spass = decoded.substring(colonIdx + 1);
            } else {
                suser = decoded;
                spass = null;
            }
        } catch (RuntimeException e) {
            handler.handle(Future.failedFuture(new HttpException(400, e)));
            return;
        }
        final var credentials = new JsonObject().put("username", suser).put("password", spass);
        final ExecutionContextAuthHandler<HttpContext> authHandler = new ExecutionContextAuthHandler<>((DeviceCredentialsAuthProvider<?>) authProvider, preCredentialsValidationHandler) {

            @Override
            public Future<JsonObject> parseCredentials(final HttpContext context) {
                return Future.succeededFuture(credentials);
            }
        };
        authHandler.authenticateDevice(HttpContext.from(context)).map(deviceUser -> (User) deviceUser).onComplete(handler);
    });
}
Also used : HttpContext(org.eclipse.hono.service.http.HttpContext) AuthenticationProvider(io.vertx.ext.auth.authentication.AuthenticationProvider) RoutingContext(io.vertx.ext.web.RoutingContext) Future(io.vertx.core.Future) BasicAuthHandler(io.vertx.ext.web.handler.BasicAuthHandler) Objects(java.util.Objects) Base64(java.util.Base64) User(io.vertx.ext.auth.User) DeviceCredentialsAuthProvider(org.eclipse.hono.adapter.auth.device.DeviceCredentialsAuthProvider) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) PreCredentialsValidationHandler(org.eclipse.hono.adapter.auth.device.PreCredentialsValidationHandler) Handler(io.vertx.core.Handler) HttpException(io.vertx.ext.web.handler.HttpException) HTTPAuthorizationHandler(io.vertx.ext.web.handler.impl.HTTPAuthorizationHandler) ExecutionContextAuthHandler(org.eclipse.hono.adapter.auth.device.ExecutionContextAuthHandler) User(io.vertx.ext.auth.User) ExecutionContextAuthHandler(org.eclipse.hono.adapter.auth.device.ExecutionContextAuthHandler) HttpContext(org.eclipse.hono.service.http.HttpContext) JsonObject(io.vertx.core.json.JsonObject) HttpException(io.vertx.ext.web.handler.HttpException)

Example 19 with HttpContext

use of org.eclipse.hono.service.http.HttpContext in project hono by eclipse.

the class LoraProtocolAdapterTest method handleProviderRouteSuccessfullyForUplinkMessage.

/**
 * Verifies that an uplink message is routed to a provider correctly.
 */
@Test
public void handleProviderRouteSuccessfullyForUplinkMessage() {
    givenATelemetrySenderForAnyTenant();
    final LoraProvider providerMock = getLoraProviderMock();
    final HttpServerRequest request = mock(HttpServerRequest.class);
    final HttpContext httpContext = newHttpContext();
    when(httpContext.request()).thenReturn(request);
    setGatewayDeviceCommandEndpoint(new CommandEndpoint());
    final CommandConsumer commandConsumer = mock(CommandConsumer.class);
    when(commandConsumer.close(any())).thenReturn(Future.succeededFuture());
    when(commandConsumerFactory.createCommandConsumer(any(), any(), any(), any(), any())).thenReturn(Future.succeededFuture(commandConsumer));
    adapter.handleProviderRoute(httpContext, providerMock);
    verify(httpContext.getRoutingContext()).put(LoraConstants.APP_PROPERTY_ORIG_LORA_PROVIDER, TEST_PROVIDER);
    @SuppressWarnings("unchecked") final ArgumentCaptor<Map<String, Object>> props = ArgumentCaptor.forClass(Map.class);
    verify(telemetrySender).sendTelemetry(argThat(tenant -> TEST_TENANT_ID.equals(tenant.getTenantId())), argThat(assertion -> TEST_DEVICE_ID.equals(assertion.getDeviceId())), eq(QoS.AT_MOST_ONCE), eq(LoraConstants.CONTENT_TYPE_LORA_BASE + TEST_PROVIDER), eq(Buffer.buffer(TEST_PAYLOAD)), props.capture(), any());
    assertThat(props.getValue()).containsEntry(LoraConstants.APP_PROPERTY_FUNCTION_PORT, TEST_FUNCTION_PORT);
    final String metaData = (String) props.getValue().get(LoraConstants.APP_PROPERTY_META_DATA);
    assertThat(metaData).isNotNull();
    final JsonObject metaDataJson = new JsonObject(metaData);
    assertThat(metaDataJson.getInteger(LoraConstants.APP_PROPERTY_FUNCTION_PORT)).isEqualTo(TEST_FUNCTION_PORT);
    verify(httpContext.getRoutingContext().response()).setStatusCode(HttpResponseStatus.ACCEPTED.code());
    verify(processMessageSpan).finish();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) LoraProviderMalformedPayloadException(org.eclipse.hono.adapter.lora.providers.LoraProviderMalformedPayloadException) RoutingContext(io.vertx.ext.web.RoutingContext) Context(io.vertx.core.Context) RETURNS_SELF(org.mockito.Mockito.RETURNS_SELF) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) CommandContext(org.eclipse.hono.client.command.CommandContext) Set(java.util.Set) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) 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) Span(io.opentracing.Span) Mockito.withSettings(org.mockito.Mockito.withSettings) CommandEndpoint(org.eclipse.hono.util.CommandEndpoint) HttpAdapterMetrics(org.eclipse.hono.adapter.http.HttpAdapterMetrics) QoS(org.eclipse.hono.util.QoS) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpContext(org.eclipse.hono.service.http.HttpContext) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpResponse(io.vertx.ext.web.client.HttpResponse) LoraProvider(org.eclipse.hono.adapter.lora.providers.LoraProvider) WebClient(io.vertx.ext.web.client.WebClient) Command(org.eclipse.hono.client.command.Command) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) SpanBuilder(io.opentracing.Tracer.SpanBuilder) 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) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ArgumentMatchers.isNull(org.mockito.ArgumentMatchers.isNull) Tracer(io.opentracing.Tracer) Vertx(io.vertx.core.Vertx) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Sample(io.micrometer.core.instrument.Timer.Sample) Mockito.verify(org.mockito.Mockito.verify) SpanContext(io.opentracing.SpanContext) HttpRequest(io.vertx.ext.web.client.HttpRequest) HttpProtocolAdapterProperties(org.eclipse.hono.adapter.http.HttpProtocolAdapterProperties) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) LoraProvider(org.eclipse.hono.adapter.lora.providers.LoraProvider) HttpServerRequest(io.vertx.core.http.HttpServerRequest) CommandEndpoint(org.eclipse.hono.util.CommandEndpoint) HttpContext(org.eclipse.hono.service.http.HttpContext) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) JsonObject(io.vertx.core.json.JsonObject) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.jupiter.api.Test)

Example 20 with HttpContext

use of org.eclipse.hono.service.http.HttpContext in project hono by eclipse.

the class LoraProtocolAdapterTest method handleCommandSubscriptionSuccessfullyForUplinkMessage.

/**
 * Verifies that an uplink message triggers a command subscription.
 */
@Test
public void handleCommandSubscriptionSuccessfullyForUplinkMessage() {
    givenATelemetrySenderForAnyTenant();
    final LoraProvider providerMock = getLoraProviderMock();
    final HttpServerRequest request = mock(HttpServerRequest.class);
    final HttpContext httpContext = newHttpContext();
    when(httpContext.request()).thenReturn(request);
    setGatewayDeviceCommandEndpoint(new CommandEndpoint());
    final CommandConsumer commandConsumer = mock(CommandConsumer.class);
    when(commandConsumer.close(any())).thenReturn(Future.succeededFuture());
    when(commandConsumerFactory.createCommandConsumer(any(), any(), any(), any(), any())).thenReturn(Future.succeededFuture(commandConsumer));
    adapter.handleProviderRoute(httpContext, providerMock);
    verify(commandConsumerFactory).createCommandConsumer(eq("myTenant"), eq("myLoraGateway"), VertxMockSupport.anyHandler(), isNull(), any());
}
Also used : LoraProvider(org.eclipse.hono.adapter.lora.providers.LoraProvider) HttpServerRequest(io.vertx.core.http.HttpServerRequest) CommandEndpoint(org.eclipse.hono.util.CommandEndpoint) HttpContext(org.eclipse.hono.service.http.HttpContext) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Test(org.junit.jupiter.api.Test)

Aggregations

HttpContext (org.eclipse.hono.service.http.HttpContext)31 Test (org.junit.jupiter.api.Test)27 Buffer (io.vertx.core.buffer.Buffer)21 HttpServerResponse (io.vertx.core.http.HttpServerResponse)18 HttpServerRequest (io.vertx.core.http.HttpServerRequest)15 TenantObject (org.eclipse.hono.util.TenantObject)11 SpanContext (io.opentracing.SpanContext)9 ClientErrorException (org.eclipse.hono.client.ClientErrorException)9 Handler (io.vertx.core.Handler)8 RoutingContext (io.vertx.ext.web.RoutingContext)8 LoraProvider (org.eclipse.hono.adapter.lora.providers.LoraProvider)8 CommandConsumer (org.eclipse.hono.client.command.CommandConsumer)8 EndpointType (org.eclipse.hono.service.metric.MetricsTags.EndpointType)8 TtdStatus (org.eclipse.hono.service.metric.MetricsTags.TtdStatus)8 Future (io.vertx.core.Future)6 HashMap (java.util.HashMap)6 Span (io.opentracing.Span)5 AsyncResult (io.vertx.core.AsyncResult)5 HttpURLConnection (java.net.HttpURLConnection)5 ServerErrorException (org.eclipse.hono.client.ServerErrorException)5