Search in sources :

Example 31 with RegistrationAssertion

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

the class VertxBasedAmqpProtocolAdapter method doUploadCommandResponseMessage.

private Future<Void> doUploadCommandResponseMessage(final AmqpContext context, final ResourceIdentifier resource, final Span currentSpan) {
    final Future<CommandResponse> responseTracker = Optional.ofNullable(getCommandResponse(context.getMessage())).map(Future::succeededFuture).orElseGet(() -> {
        TracingHelper.logError(currentSpan, String.format("invalid message (correlationId: %s, address: %s, status: %s)", context.getMessage().getCorrelationId(), context.getMessage().getAddress(), MessageHelper.getStatus(context.getMessage())));
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "malformed command response message"));
    });
    final Future<TenantObject> tenantTracker = getTenantConfiguration(resource.getTenantId(), currentSpan.context());
    return CompositeFuture.all(tenantTracker, responseTracker).compose(ok -> {
        final CommandResponse commandResponse = responseTracker.result();
        log.trace("sending command response [device-id: {}, status: {}, correlation-id: {}, reply-to: {}]", resource.getResourceId(), commandResponse.getStatus(), commandResponse.getCorrelationId(), commandResponse.getReplyToId());
        final Map<String, Object> items = new HashMap<>(3);
        items.put(Fields.EVENT, "sending command response");
        items.put(TracingHelper.TAG_CORRELATION_ID.getKey(), commandResponse.getCorrelationId());
        items.put(MessageHelper.APP_PROPERTY_STATUS, commandResponse.getStatus());
        currentSpan.log(items);
        final Future<RegistrationAssertion> tokenFuture = getRegistrationAssertion(resource.getTenantId(), resource.getResourceId(), context.getAuthenticatedDevice(), currentSpan.context());
        final Future<TenantObject> tenantValidationTracker = CompositeFuture.all(isAdapterEnabled(tenantTracker.result()), checkMessageLimit(tenantTracker.result(), context.getPayloadSize(), currentSpan.context())).map(success -> tenantTracker.result());
        return CompositeFuture.all(tenantValidationTracker, tokenFuture).compose(success -> sendCommandResponse(tenantTracker.result(), tokenFuture.result(), commandResponse, currentSpan.context()));
    }).map(delivery -> {
        log.trace("forwarded command response from device [tenant: {}, device-id: {}]", resource.getTenantId(), resource.getResourceId());
        metrics.reportCommand(Direction.RESPONSE, resource.getTenantId(), tenantTracker.result(), ProcessingOutcome.FORWARDED, context.getPayloadSize(), context.getTimer());
        return delivery;
    }).recover(t -> {
        log.debug("cannot process command response from device [tenant: {}, device-id: {}]", resource.getTenantId(), resource.getResourceId(), t);
        metrics.reportCommand(Direction.RESPONSE, resource.getTenantId(), tenantTracker.result(), ProcessingOutcome.from(t), context.getPayloadSize(), context.getTimer());
        return Future.failedFuture(t);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) Tags(io.opentracing.tag.Tags) ProtonServer(io.vertx.proton.ProtonServer) HonoProtonHelper(org.eclipse.hono.util.HonoProtonHelper) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) Modified(org.apache.qpid.proton.amqp.messaging.Modified) DeviceCredentials(org.eclipse.hono.adapter.auth.device.DeviceCredentials) Map(java.util.Map) DeliveryState(org.apache.qpid.proton.amqp.transport.DeliveryState) AuthorizationException(org.eclipse.hono.adapter.AuthorizationException) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) Fields(io.opentracing.log.Fields) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) TracingHelper(org.eclipse.hono.tracing.TracingHelper) ProtonSaslAuthenticatorFactory(io.vertx.proton.sasl.ProtonSaslAuthenticatorFactory) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) TenantServiceBasedX509Authentication(org.eclipse.hono.adapter.auth.device.TenantServiceBasedX509Authentication) Predicate(java.util.function.Predicate) Collection(java.util.Collection) CommandContext(org.eclipse.hono.client.command.CommandContext) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) ProtonQoS(io.vertx.proton.ProtonQoS) MessageHelper(org.eclipse.hono.util.MessageHelper) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Objects(java.util.Objects) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) List(java.util.List) QoS(org.eclipse.hono.service.metric.MetricsTags.QoS) TenantTraceSamplingHelper(org.eclipse.hono.tracing.TenantTraceSamplingHelper) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Optional(java.util.Optional) Span(io.opentracing.Span) ProtonSender(io.vertx.proton.ProtonSender) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) ProtonLink(io.vertx.proton.ProtonLink) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) ProtonServerOptions(io.vertx.proton.ProtonServerOptions) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) ConnectionLimitManager(org.eclipse.hono.adapter.limiting.ConnectionLimitManager) Command(org.eclipse.hono.client.command.Command) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) AdapterDisabledException(org.eclipse.hono.adapter.AdapterDisabledException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) OptionalInt(java.util.OptionalInt) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Commands(org.eclipse.hono.client.command.Commands) Constants(org.eclipse.hono.util.Constants) CompositeFuture(io.vertx.core.CompositeFuture) ProtonSession(io.vertx.proton.ProtonSession) Symbol(org.apache.qpid.proton.amqp.Symbol) AdapterConnectionsExceededException(org.eclipse.hono.adapter.AdapterConnectionsExceededException) Target(org.apache.qpid.proton.amqp.transport.Target) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) Message(org.apache.qpid.proton.message.Message) HttpUtils(org.eclipse.hono.service.http.HttpUtils) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) Strings(org.eclipse.hono.util.Strings) UsernamePasswordAuthProvider(org.eclipse.hono.adapter.auth.device.UsernamePasswordAuthProvider) CredentialsApiAuthProvider(org.eclipse.hono.adapter.auth.device.CredentialsApiAuthProvider) AbstractProtocolAdapterBase(org.eclipse.hono.adapter.AbstractProtocolAdapterBase) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ProtonHelper(io.vertx.proton.ProtonHelper) Sample(io.micrometer.core.instrument.Timer.Sample) Released(org.apache.qpid.proton.amqp.messaging.Released) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) Source(org.apache.qpid.proton.amqp.transport.Source) ConnectionAttemptOutcome(org.eclipse.hono.service.metric.MetricsTags.ConnectionAttemptOutcome) MemoryBasedConnectionLimitStrategy(org.eclipse.hono.adapter.limiting.MemoryBasedConnectionLimitStrategy) X509AuthProvider(org.eclipse.hono.adapter.auth.device.X509AuthProvider) Handler(io.vertx.core.Handler) Collections(java.util.Collections) DefaultConnectionLimitManager(org.eclipse.hono.adapter.limiting.DefaultConnectionLimitManager) TenantObject(org.eclipse.hono.util.TenantObject) HashMap(java.util.HashMap) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) ClientErrorException(org.eclipse.hono.client.ClientErrorException) TenantObject(org.eclipse.hono.util.TenantObject) CommandResponse(org.eclipse.hono.client.command.CommandResponse)

Example 32 with RegistrationAssertion

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

the class CommandResponseResource method uploadCommandResponseMessage.

/**
 * Forwards a command response to a downstream application.
 *
 * @param context The context representing the command response to be forwarded.
 * @return A future indicating the outcome of the operation.
 *         The future will be succeeded if the message has been forwarded successfully.
 *         In this case one of the context's <em>respond</em> methods will have been invoked to send a CoAP response
 *         back to the device.
 *         Otherwise the future will be failed with a {@link org.eclipse.hono.client.ServiceInvocationException}.
 * @throws NullPointerException if context is {@code null}.
 */
public final Future<Void> uploadCommandResponseMessage(final CoapContext context) {
    Objects.requireNonNull(context);
    final Device device = context.getOriginDevice();
    final Device authenticatedDevice = context.getAuthenticatedDevice();
    if (!context.isConfirmable()) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "command response endpoint supports confirmable request messages only"));
    }
    final Buffer payload = context.getPayload();
    final String contentType = context.getContentType();
    final String commandRequestId = context.getCommandRequestId();
    final Integer responseStatus = context.getCommandResponseStatus();
    LOG.debug("processing response to command [tenantId: {}, deviceId: {}, cmd-req-id: {}, status code: {}]", device.getTenantId(), device.getDeviceId(), commandRequestId, responseStatus);
    final Span currentSpan = TracingHelper.buildChildSpan(getTracer(), context.getTracingContext(), "upload Command response", getAdapter().getTypeName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).withTag(TracingHelper.TAG_TENANT_ID, device.getTenantId()).withTag(TracingHelper.TAG_DEVICE_ID, device.getDeviceId()).withTag(Constants.HEADER_COMMAND_RESPONSE_STATUS, responseStatus).withTag(Constants.HEADER_COMMAND_REQUEST_ID, commandRequestId).withTag(TracingHelper.TAG_AUTHENTICATED.getKey(), authenticatedDevice != null).start();
    final Future<RegistrationAssertion> deviceRegistrationTracker = getAdapter().getRegistrationAssertion(device.getTenantId(), device.getDeviceId(), authenticatedDevice, currentSpan.context());
    final Future<TenantObject> tenantTracker = getAdapter().getTenantClient().get(device.getTenantId(), currentSpan.context());
    final Optional<CommandResponse> cmdResponse = Optional.ofNullable(CommandResponse.fromRequestId(commandRequestId, device.getTenantId(), device.getDeviceId(), payload, contentType, responseStatus));
    final Future<CommandResponse> commandResponseTracker = cmdResponse.map(res -> Future.succeededFuture(res)).orElseGet(() -> Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, String.format("command-request-id [%s] or status code [%s] is missing/invalid", commandRequestId, responseStatus))));
    return CompositeFuture.all(tenantTracker, commandResponseTracker, deviceRegistrationTracker).compose(ok -> CompositeFuture.all(getAdapter().isAdapterEnabled(tenantTracker.result()), getAdapter().checkMessageLimit(tenantTracker.result(), payload.length(), currentSpan.context())).mapEmpty()).compose(ok -> getAdapter().getCommandResponseSender(commandResponseTracker.result().getMessagingType(), tenantTracker.result()).sendCommandResponse(tenantTracker.result(), deviceRegistrationTracker.result(), commandResponseTracker.result(), currentSpan.context())).onSuccess(ok -> {
        LOG.trace("forwarded command response [command-request-id: {}] to downstream application", commandRequestId);
        currentSpan.log("forwarded command response to application");
        getAdapter().getMetrics().reportCommand(Direction.RESPONSE, device.getTenantId(), tenantTracker.result(), ProcessingOutcome.FORWARDED, payload.length(), context.getTimer());
        context.respondWithCode(ResponseCode.CHANGED);
    }).onFailure(t -> {
        LOG.debug("could not send command response [command-request-id: {}] to application", commandRequestId, t);
        TracingHelper.logError(currentSpan, t);
        getAdapter().getMetrics().reportCommand(Direction.RESPONSE, device.getTenantId(), tenantTracker.result(), ProcessingOutcome.from(t), payload.length(), context.getTimer());
    }).onComplete(r -> currentSpan.finish());
}
Also used : Buffer(io.vertx.core.buffer.Buffer) HttpURLConnection(java.net.HttpURLConnection) ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) LoggerFactory(org.slf4j.LoggerFactory) Vertx(io.vertx.core.Vertx) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) Tags(io.opentracing.tag.Tags) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) Objects(java.util.Objects) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) CompositeFuture(io.vertx.core.CompositeFuture) Buffer(io.vertx.core.buffer.Buffer) Optional(java.util.Optional) Span(io.opentracing.Span) TracingHelper(org.eclipse.hono.tracing.TracingHelper) CommandConstants(org.eclipse.hono.util.CommandConstants) Device(org.eclipse.hono.auth.Device) CommandResponse(org.eclipse.hono.client.command.CommandResponse) Span(io.opentracing.Span) TenantObject(org.eclipse.hono.util.TenantObject) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) ClientErrorException(org.eclipse.hono.client.ClientErrorException)

Example 33 with RegistrationAssertion

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

the class ProtonBasedDeviceRegistrationClient method assertRegistration.

@Override
public Future<RegistrationAssertion> assertRegistration(final String tenantId, final String deviceId, final String gatewayId, final SpanContext context) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    final AnnotatedCacheKey<CacheKey> responseCacheKey = new AnnotatedCacheKey<>(new CacheKey(tenantId, deviceId, gatewayId));
    final Span span = newChildSpan(context, "assert Device Registration");
    TracingHelper.setDeviceTags(span, tenantId, deviceId);
    TracingHelper.TAG_GATEWAY_ID.set(span, gatewayId);
    return getResponseFromCache(responseCacheKey, span).recover(t -> getOrCreateClient(tenantId).compose(client -> {
        final Map<String, Object> properties = createDeviceIdProperties(deviceId);
        if (gatewayId != null) {
            properties.put(MessageHelper.APP_PROPERTY_GATEWAY_ID, gatewayId);
        }
        return client.createAndSendRequest(RegistrationConstants.ACTION_ASSERT, properties, null, RegistrationConstants.CONTENT_TYPE_APPLICATION_JSON, this::getRequestResponseResult, span);
    }).map(registrationResult -> {
        addToCache(responseCacheKey, registrationResult);
        return registrationResult;
    })).recover(t -> {
        Tags.HTTP_STATUS.set(span, ServiceInvocationException.extractStatusCode(t));
        TracingHelper.logError(span, t);
        return Future.failedFuture(t);
    }).map(registrationResult -> {
        Tags.HTTP_STATUS.set(span, registrationResult.getStatus());
        if (registrationResult.isError()) {
            Tags.ERROR.set(span, Boolean.TRUE);
        }
        switch(registrationResult.getStatus()) {
            case HttpURLConnection.HTTP_OK:
                final JsonObject payload = registrationResult.getPayload();
                try {
                    return payload.mapTo(RegistrationAssertion.class);
                } catch (final DecodeException e) {
                    if (log.isDebugEnabled()) {
                        log.debug("registration service returned invalid response:{}{}", System.lineSeparator(), payload.encodePrettily());
                    }
                    TracingHelper.logError(span, "registration service returned invalid response", e);
                    throw new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR, "registration service returned invalid response");
                }
            case HttpURLConnection.HTTP_NOT_FOUND:
                throw new ClientErrorException(registrationResult.getStatus(), "device unknown or disabled");
            case HttpURLConnection.HTTP_FORBIDDEN:
                throw new ClientErrorException(registrationResult.getStatus(), "gateway unknown, disabled or not authorized to act on behalf of device");
            default:
                throw StatusCodeMapper.from(registrationResult);
        }
    }).onComplete(o -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CacheDirective(org.eclipse.hono.util.CacheDirective) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) DecodeException(io.vertx.core.json.DecodeException) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) LoggerFactory(org.slf4j.LoggerFactory) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Cache(com.github.benmanes.caffeine.cache.Cache) Constants(org.eclipse.hono.util.Constants) Tags(io.opentracing.tag.Tags) StatusCodeMapper(org.eclipse.hono.client.StatusCodeMapper) DeviceRegistrationClient(org.eclipse.hono.client.registry.DeviceRegistrationClient) Map(java.util.Map) RegistrationResult(org.eclipse.hono.util.RegistrationResult) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) HonoConnection(org.eclipse.hono.client.HonoConnection) AbstractRequestResponseServiceClient(org.eclipse.hono.client.amqp.AbstractRequestResponseServiceClient) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) Logger(org.slf4j.Logger) RequestResponseClient(org.eclipse.hono.client.amqp.RequestResponseClient) CachingClientFactory(org.eclipse.hono.client.impl.CachingClientFactory) ServerErrorException(org.eclipse.hono.client.ServerErrorException) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) ApplicationProperties(org.apache.qpid.proton.amqp.messaging.ApplicationProperties) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) AnnotatedCacheKey(org.eclipse.hono.client.util.AnnotatedCacheKey) Buffer(io.vertx.core.buffer.Buffer) Span(io.opentracing.Span) SendMessageSampler(org.eclipse.hono.client.SendMessageSampler) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) JsonObject(io.vertx.core.json.JsonObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServerErrorException(org.eclipse.hono.client.ServerErrorException) AnnotatedCacheKey(org.eclipse.hono.client.util.AnnotatedCacheKey) Span(io.opentracing.Span) Map(java.util.Map) DecodeException(io.vertx.core.json.DecodeException) AnnotatedCacheKey(org.eclipse.hono.client.util.AnnotatedCacheKey)

Example 34 with RegistrationAssertion

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

the class JmsBasedRegistrationClient method sendRequest.

/**
 * Sends a request for an operation.
 *
 * @param tenantId The tenant to send the request for.
 * @param operation The name of the operation to invoke or {@code null} if the message
 *                  should not have a subject.
 * @param applicationProperties Application properties to set on the request message or
 *                              {@code null} if no properties should be set.
 * @param payload Payload to include or {@code null} if the message should have no body.
 * @return A future indicating the outcome of the operation.
 */
public Future<RegistrationAssertion> sendRequest(final String tenantId, final String operation, final Map<String, Object> applicationProperties, final Buffer payload) {
    final Message request;
    try {
        request = createMessage(payload);
        addProperties(request, applicationProperties);
        if (operation != null) {
            request.setJMSType(operation);
        }
    } catch (final JMSException e) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    }
    final Future<JmsBasedRequestResponseClient<RegistrationResult>> client = JmsBasedRequestResponseClient.forEndpoint(connection, RegistrationConstants.REGISTRATION_ENDPOINT, tenantId);
    return client.compose(c -> c.send(request, this::getResult)).compose(registrationResult -> {
        final Promise<RegistrationAssertion> result = Promise.promise();
        switch(registrationResult.getStatus()) {
            case HttpURLConnection.HTTP_OK:
                try {
                    final var assertion = registrationResult.getPayload().mapTo(RegistrationAssertion.class);
                    result.complete(assertion);
                } catch (final DecodeException e) {
                    result.fail(e);
                }
                break;
            case HttpURLConnection.HTTP_NOT_FOUND:
                result.fail(new ClientErrorException(registrationResult.getStatus(), "no such device"));
                break;
            default:
                result.fail(StatusCodeMapper.from(registrationResult));
        }
        return result.future();
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Logger(org.slf4j.Logger) DecodeException(io.vertx.core.json.DecodeException) Promise(io.vertx.core.Promise) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) MessageHelper(org.eclipse.hono.util.MessageHelper) JMSException(javax.jms.JMSException) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) Buffer(io.vertx.core.buffer.Buffer) StatusCodeMapper(org.eclipse.hono.client.StatusCodeMapper) DeviceRegistrationClient(org.eclipse.hono.client.registry.DeviceRegistrationClient) Map(java.util.Map) RegistrationResult(org.eclipse.hono.util.RegistrationResult) JsonObject(io.vertx.core.json.JsonObject) Message(javax.jms.Message) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Message(javax.jms.Message) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) ClientErrorException(org.eclipse.hono.client.ClientErrorException) JMSException(javax.jms.JMSException) DecodeException(io.vertx.core.json.DecodeException)

Example 35 with RegistrationAssertion

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

the class AbstractProtocolAdapterBaseTest method testGetRegistrationAssertionSucceedsForExistingDevice.

/**
 * Verifies that the adapter successfully retrieves a registration assertion
 * for an existing device.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetRegistrationAssertionSucceedsForExistingDevice(final VertxTestContext ctx) {
    // GIVEN an adapter connected to a registration service
    final RegistrationAssertion assertionResult = newRegistrationAssertionResult("device");
    assertionResult.setAuthorizedGateways(List.of("gw", "gw2"));
    when(registrationClient.assertRegistration(eq("tenant"), eq("device"), any(), any())).thenReturn(Future.succeededFuture(assertionResult));
    when(commandRouterClient.setLastKnownGatewayForDevice(anyString(), anyString(), anyString(), any())).thenReturn(Future.succeededFuture());
    // WHEN an assertion for the device is retrieved
    adapter.getRegistrationAssertion("tenant", "device", new Device("tenant", "gw"), mock(SpanContext.class)).onComplete(ctx.succeeding(result -> {
        ctx.verify(() -> {
            // THEN the result contains the registration assertion
            assertThat(result.getDeviceId()).isEqualTo("device");
            // and the last known gateway has been updated
            verify(commandRouterClient).setLastKnownGatewayForDevice(eq("tenant"), eq("device"), eq("gw"), any());
        });
        ctx.completeNow();
    }));
}
Also used : 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) Context(io.vertx.core.Context) TelemetrySender(org.eclipse.hono.client.telemetry.TelemetrySender) MessagingType(org.eclipse.hono.util.MessagingType) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Map(java.util.Map) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) EventSender(org.eclipse.hono.client.telemetry.EventSender) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) TenantClient(org.eclipse.hono.client.registry.TenantClient) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) EventConstants(org.eclipse.hono.util.EventConstants) 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) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) CommandRouterClient(org.eclipse.hono.client.command.CommandRouterClient) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Optional(java.util.Optional) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ConnectionEventProducer(org.eclipse.hono.adapter.monitoring.ConnectionEventProducer) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) Commands(org.eclipse.hono.client.command.Commands) Constants(org.eclipse.hono.util.Constants) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) DeviceRegistrationClient(org.eclipse.hono.client.registry.DeviceRegistrationClient) TelemetryExecutionContext(org.eclipse.hono.util.TelemetryExecutionContext) HttpUtils(org.eclipse.hono.service.http.HttpUtils) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) MessagingClient(org.eclipse.hono.util.MessagingClient) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) MessagingClientProvider(org.eclipse.hono.client.util.MessagingClientProvider) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) 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) CommandConsumerFactory(org.eclipse.hono.client.command.CommandConsumerFactory) Mockito.never(org.mockito.Mockito.never) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) HonoEventConnectionEventProducer(org.eclipse.hono.adapter.monitoring.HonoEventConnectionEventProducer) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Device(org.eclipse.hono.auth.Device) Test(org.junit.jupiter.api.Test)

Aggregations

RegistrationAssertion (org.eclipse.hono.util.RegistrationAssertion)42 Future (io.vertx.core.Future)31 HttpURLConnection (java.net.HttpURLConnection)29 MessageHelper (org.eclipse.hono.util.MessageHelper)29 Map (java.util.Map)27 Span (io.opentracing.Span)26 TenantObject (org.eclipse.hono.util.TenantObject)26 Buffer (io.vertx.core.buffer.Buffer)24 Constants (org.eclipse.hono.util.Constants)22 ServerErrorException (org.eclipse.hono.client.ServerErrorException)21 Device (org.eclipse.hono.auth.Device)20 Test (org.junit.jupiter.api.Test)20 ClientErrorException (org.eclipse.hono.client.ClientErrorException)18 Handler (io.vertx.core.Handler)17 Objects (java.util.Objects)17 ResourceIdentifier (org.eclipse.hono.util.ResourceIdentifier)17 HashMap (java.util.HashMap)16 Command (org.eclipse.hono.client.command.Command)16 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)16 SpanContext (io.opentracing.SpanContext)15