Search in sources :

Example 1 with Id

use of org.eclipse.hono.service.management.Id in project hono by eclipse.

the class DelegatingDeviceManagementHttpEndpoint method doCreateDevice.

private void doCreateDevice(final RoutingContext ctx) {
    final Span span = TracingHelper.buildServerChildSpan(tracer, TracingHandler.serverSpanContext(ctx), SPAN_NAME_CREATE_DEVICE, getClass().getSimpleName()).start();
    final Future<String> tenantId = getRequestParameter(ctx, PARAM_TENANT_ID, getPredicate(config.getTenantIdPattern(), false));
    final Future<String> deviceId = getRequestParameter(ctx, PARAM_DEVICE_ID, getPredicate(config.getDeviceIdPattern(), true));
    final Future<Device> device = fromPayload(ctx);
    CompositeFuture.all(tenantId, deviceId, device).compose(ok -> {
        final Optional<String> did = Optional.ofNullable(deviceId.result());
        TracingHelper.TAG_TENANT_ID.set(span, tenantId.result());
        did.ifPresent(s -> TracingHelper.TAG_DEVICE_ID.set(span, s));
        logger.debug("creating device [tenant: {}, device-id: {}]", tenantId.result(), did.orElse("<auto>"));
        return getService().createDevice(tenantId.result(), did, device.result(), span);
    }).onSuccess(operationResult -> writeResponse(ctx, operationResult, (responseHeaders, status) -> {
        Optional.ofNullable(operationResult.getPayload()).map(Id::getId).ifPresent(id -> responseHeaders.set(HttpHeaders.LOCATION, String.format("/%s/%s/%s", getName(), tenantId.result(), id)));
    }, span)).onFailure(t -> failRequest(ctx, t, span)).onComplete(s -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) DecodeException(io.vertx.core.json.DecodeException) AbstractDelegatingRegistryHttpEndpoint(org.eclipse.hono.service.management.AbstractDelegatingRegistryHttpEndpoint) Filter(org.eclipse.hono.service.management.Filter) Router(io.vertx.ext.web.Router) ClientErrorException(org.eclipse.hono.client.ClientErrorException) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) ServiceConfigProperties(org.eclipse.hono.config.ServiceConfigProperties) TracingHandler(org.eclipse.hono.service.http.TracingHandler) CompositeFuture(io.vertx.core.CompositeFuture) Sort(org.eclipse.hono.service.management.Sort) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Set(java.util.Set) HttpHeaders(io.vertx.core.http.HttpHeaders) Future(io.vertx.core.Future) Objects(java.util.Objects) List(java.util.List) HttpMethod(io.vertx.core.http.HttpMethod) Optional(java.util.Optional) Span(io.opentracing.Span) Id(org.eclipse.hono.service.management.Id) Optional(java.util.Optional) Id(org.eclipse.hono.service.management.Id) Span(io.opentracing.Span)

Example 2 with Id

use of org.eclipse.hono.service.management.Id in project hono by eclipse.

the class AbstractDeviceManagementService method deleteDevice.

@Override
public final Future<Result<Void>> deleteDevice(final String tenantId, final String deviceId, final Optional<String> resourceVersion, final Span span) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(resourceVersion);
    Objects.requireNonNull(span);
    return this.tenantInformationService.tenantExists(tenantId, span).otherwise(t -> Result.from(ServiceInvocationException.extractStatusCode(t))).compose(result -> {
        switch(result.getStatus()) {
            case HttpURLConnection.HTTP_OK:
                break;
            case HttpURLConnection.HTTP_NOT_FOUND:
                span.log("tenant does not exist (anymore)");
                LOG.info("trying to delete device of non-existing tenant [tenant-id: {}, device-id: {}]", tenantId, deviceId);
                break;
            default:
                span.log(Map.of(Fields.EVENT, "could not determine tenant status", Tags.HTTP_STATUS.getKey(), result.getStatus()));
                LOG.info("could not determine tenant status [tenant-id: {}, code: {}]", tenantId, result.getStatus());
        }
        return processDeleteDevice(DeviceKey.from(tenantId, deviceId), resourceVersion, span);
    }).onSuccess(result -> NotificationEventBusSupport.sendNotification(vertx, new DeviceChangeNotification(LifecycleChange.DELETE, tenantId, deviceId, Instant.now(), false))).recover(t -> DeviceRegistryUtils.mapError(t, tenantId));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Tags(io.opentracing.tag.Tags) DeviceManagementService(org.eclipse.hono.service.management.device.DeviceManagementService) Sort(org.eclipse.hono.service.management.Sort) SearchResult(org.eclipse.hono.service.management.SearchResult) Map(java.util.Map) Fields(io.opentracing.log.Fields) TenantInformationService(org.eclipse.hono.deviceregistry.service.tenant.TenantInformationService) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) NoopTenantInformationService(org.eclipse.hono.deviceregistry.service.tenant.NoopTenantInformationService) Device(org.eclipse.hono.service.management.device.Device) DeviceWithId(org.eclipse.hono.service.management.device.DeviceWithId) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) UUID(java.util.UUID) Instant(java.time.Instant) Result(org.eclipse.hono.service.management.Result) Future(io.vertx.core.Future) Objects(java.util.Objects) List(java.util.List) Optional(java.util.Optional) OperationResult(org.eclipse.hono.service.management.OperationResult) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) DeviceRegistryUtils(org.eclipse.hono.deviceregistry.util.DeviceRegistryUtils) Id(org.eclipse.hono.service.management.Id) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification)

Example 3 with Id

use of org.eclipse.hono.service.management.Id in project hono by eclipse.

the class AbstractDeviceManagementService method createDevice.

@Override
public final Future<OperationResult<Id>> createDevice(final String tenantId, final Optional<String> deviceId, final Device device, final Span span) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(device);
    Objects.requireNonNull(span);
    final String deviceIdValue = deviceId.orElseGet(() -> generateDeviceId(tenantId));
    return this.tenantInformationService.tenantExists(tenantId, span).compose(result -> result.isError() ? Future.failedFuture(ServiceInvocationException.create(tenantId, result.getStatus(), "tenant does not exist", null)) : processCreateDevice(DeviceKey.from(result.getPayload(), deviceIdValue), device, span)).onSuccess(result -> NotificationEventBusSupport.sendNotification(vertx, new DeviceChangeNotification(LifecycleChange.CREATE, tenantId, deviceIdValue, Instant.now(), device.isEnabled()))).recover(t -> DeviceRegistryUtils.mapError(t, tenantId));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Tags(io.opentracing.tag.Tags) DeviceManagementService(org.eclipse.hono.service.management.device.DeviceManagementService) Sort(org.eclipse.hono.service.management.Sort) SearchResult(org.eclipse.hono.service.management.SearchResult) Map(java.util.Map) Fields(io.opentracing.log.Fields) TenantInformationService(org.eclipse.hono.deviceregistry.service.tenant.TenantInformationService) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) NoopTenantInformationService(org.eclipse.hono.deviceregistry.service.tenant.NoopTenantInformationService) Device(org.eclipse.hono.service.management.device.Device) DeviceWithId(org.eclipse.hono.service.management.device.DeviceWithId) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) UUID(java.util.UUID) Instant(java.time.Instant) Result(org.eclipse.hono.service.management.Result) Future(io.vertx.core.Future) Objects(java.util.Objects) List(java.util.List) Optional(java.util.Optional) OperationResult(org.eclipse.hono.service.management.OperationResult) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) DeviceRegistryUtils(org.eclipse.hono.deviceregistry.util.DeviceRegistryUtils) Id(org.eclipse.hono.service.management.Id) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification)

Example 4 with Id

use of org.eclipse.hono.service.management.Id in project hono by eclipse.

the class DelegatingDeviceManagementHttpEndpointTest method testCreateDeviceUsesIdFromUriParam.

/**
 * Verifies that the endpoint uses the device ID provided in a request's URI
 * for creating a device.
 */
@SuppressWarnings("unchecked")
@Test
public void testCreateDeviceUsesIdFromUriParam() {
    final JsonObject json = new JsonObject().put(RegistryManagementConstants.FIELD_DOWNSTREAM_MESSAGE_MAPPER, "my-mapper").put(RegistryManagementConstants.FIELD_EXT, new JsonObject().put("custom", "value"));
    requestBody = json.toBuffer();
    when(service.createDevice(anyString(), any(Optional.class), any(Device.class), any(Span.class))).thenAnswer(invocation -> {
        final Optional<String> deviceId = invocation.getArgument(1);
        return Future.succeededFuture(OperationResult.ok(HttpURLConnection.HTTP_CREATED, Id.of(deviceId.get()), Optional.empty(), Optional.empty()));
    });
    final HttpServerResponse response = newResponse();
    final HttpServerRequest request = newRequest(HttpMethod.POST, "/v1/devices/mytenant/mydeviceid", requestHeaders, requestParams, response);
    router.handle(request);
    verify(response).setStatusCode(HttpURLConnection.HTTP_CREATED);
    verify(response).write(argThat((Buffer buffer) -> "mydeviceid".equals(buffer.toJsonObject().getString(RegistryManagementConstants.FIELD_ID))));
    verify(service).createDevice(eq("mytenant"), argThat(deviceId -> "mydeviceid".equals(deviceId.get())), argThat(device -> {
        return "my-mapper".equals(device.getDownstreamMessageMapper()) && "value".equals(device.getExtensions().get("custom"));
    }), any(Span.class));
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpURLConnection(java.net.HttpURLConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Filter(org.eclipse.hono.service.management.Filter) MultiMap(io.vertx.core.MultiMap) Router(io.vertx.ext.web.Router) ServiceConfigProperties(org.eclipse.hono.config.ServiceConfigProperties) Sort(org.eclipse.hono.service.management.Sort) ArgumentCaptor(org.mockito.ArgumentCaptor) JsonObject(io.vertx.core.json.JsonObject) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Vertx(io.vertx.core.Vertx) HttpHeaders(io.vertx.core.http.HttpHeaders) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Future(io.vertx.core.Future) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) HttpServerRequestInternal(io.vertx.core.http.impl.HttpServerRequestInternal) Mockito.never(org.mockito.Mockito.never) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Operator(org.eclipse.hono.service.management.Filter.Operator) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerResponse(io.vertx.core.http.HttpServerResponse) DefaultFailureHandler(org.eclipse.hono.service.http.DefaultFailureHandler) Optional(java.util.Optional) OperationResult(org.eclipse.hono.service.management.OperationResult) Span(io.opentracing.Span) Handler(io.vertx.core.Handler) Id(org.eclipse.hono.service.management.Id) Direction(org.eclipse.hono.service.management.Sort.Direction) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) Optional(java.util.Optional) HttpServerResponse(io.vertx.core.http.HttpServerResponse) HttpServerRequest(io.vertx.core.http.HttpServerRequest) JsonObject(io.vertx.core.json.JsonObject) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Span(io.opentracing.Span) Test(org.junit.jupiter.api.Test)

Example 5 with Id

use of org.eclipse.hono.service.management.Id in project hono by eclipse.

the class DelegatingTenantManagementHttpEndpoint method getTenant.

private void getTenant(final RoutingContext ctx) {
    final Span span = TracingHelper.buildServerChildSpan(tracer, TracingHandler.serverSpanContext(ctx), SPAN_NAME_GET_TENANT, getClass().getSimpleName()).start();
    getRequestParameter(ctx, PARAM_TENANT_ID, getPredicate(config.getTenantIdPattern(), false)).compose(tenantId -> {
        TracingHelper.TAG_TENANT_ID.set(span, tenantId);
        logger.debug("retrieving tenant [id: {}]", tenantId);
        return getService().readTenant(tenantId, span);
    }).onSuccess(operationResult -> writeResponse(ctx, operationResult, span)).onFailure(t -> failRequest(ctx, t, span)).onComplete(s -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) DecodeException(io.vertx.core.json.DecodeException) AbstractDelegatingRegistryHttpEndpoint(org.eclipse.hono.service.management.AbstractDelegatingRegistryHttpEndpoint) Filter(org.eclipse.hono.service.management.Filter) Router(io.vertx.ext.web.Router) ClientErrorException(org.eclipse.hono.client.ClientErrorException) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) ServiceConfigProperties(org.eclipse.hono.config.ServiceConfigProperties) TracingHandler(org.eclipse.hono.service.http.TracingHandler) CompositeFuture(io.vertx.core.CompositeFuture) Sort(org.eclipse.hono.service.management.Sort) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Set(java.util.Set) HttpHeaders(io.vertx.core.http.HttpHeaders) Future(io.vertx.core.Future) Objects(java.util.Objects) List(java.util.List) HttpMethod(io.vertx.core.http.HttpMethod) Optional(java.util.Optional) Span(io.opentracing.Span) Id(org.eclipse.hono.service.management.Id) Span(io.opentracing.Span)

Aggregations

Span (io.opentracing.Span)12 Future (io.vertx.core.Future)12 Vertx (io.vertx.core.Vertx)12 HttpURLConnection (java.net.HttpURLConnection)12 List (java.util.List)12 Optional (java.util.Optional)12 Filter (org.eclipse.hono.service.management.Filter)12 Id (org.eclipse.hono.service.management.Id)12 Sort (org.eclipse.hono.service.management.Sort)12 Objects (java.util.Objects)11 HttpHeaders (io.vertx.core.http.HttpHeaders)7 HttpMethod (io.vertx.core.http.HttpMethod)7 JsonObject (io.vertx.core.json.JsonObject)7 Router (io.vertx.ext.web.Router)7 ServiceConfigProperties (org.eclipse.hono.config.ServiceConfigProperties)7 RegistryManagementConstants (org.eclipse.hono.util.RegistryManagementConstants)7 CompositeFuture (io.vertx.core.CompositeFuture)6 Promise (io.vertx.core.Promise)6 ClientErrorException (org.eclipse.hono.client.ClientErrorException)6 OperationResult (org.eclipse.hono.service.management.OperationResult)6