Search in sources :

Example 26 with Future

use of io.vertx.core.Future in project hono by eclipse.

the class FileBasedTenantServiceTest method testDoStartCreatesFile.

/**
 * Verifies that the tenant service creates a file for persisting tenants
 * data if it does not exist yet during startup.
 *
 * @param ctx The vert.x context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testDoStartCreatesFile(final TestContext ctx) {
    // GIVEN a tenant service configured to persist data to a not yet existing file
    props.setSaveToFile(true);
    props.setFilename(FILE_NAME);
    when(fileSystem.existsBlocking(FILE_NAME)).thenReturn(Boolean.FALSE);
    doAnswer(invocation -> {
        final Handler handler = invocation.getArgument(1);
        handler.handle(Future.succeededFuture());
        return null;
    }).when(fileSystem).createFile(eq(props.getFilename()), any(Handler.class));
    doAnswer(invocation -> {
        final Handler handler = invocation.getArgument(1);
        handler.handle(Future.failedFuture("malformed file"));
        return null;
    }).when(fileSystem).readFile(eq(props.getFilename()), any(Handler.class));
    // WHEN starting the service
    final Async startup = ctx.async();
    final Future<Void> startupTracker = Future.future();
    startupTracker.setHandler(ctx.asyncAssertSuccess(started -> {
        startup.complete();
    }));
    svc.doStart(startupTracker);
    // THEN the file gets created
    startup.await();
    verify(fileSystem).createFile(eq(FILE_NAME), any(Handler.class));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) TenantConstants(org.eclipse.hono.util.TenantConstants) RunWith(org.junit.runner.RunWith) Constants(org.eclipse.hono.util.Constants) Context(io.vertx.core.Context) Assert.assertThat(org.junit.Assert.assertThat) ArgumentCaptor(org.mockito.ArgumentCaptor) EventBus(io.vertx.core.eventbus.EventBus) Matchers.eq(org.mockito.Matchers.eq) TenantService(org.eclipse.hono.service.tenant.TenantService) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) Matchers.any(org.mockito.Matchers.any) Mockito(org.mockito.Mockito) JsonArray(io.vertx.core.json.JsonArray) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) FileSystem(io.vertx.core.file.FileSystem) Handler(io.vertx.core.Handler) Async(io.vertx.ext.unit.Async) Handler(io.vertx.core.Handler) Test(org.junit.Test)

Example 27 with Future

use of io.vertx.core.Future in project hono by eclipse.

the class BaseCredentialsService method processRemoveRequest.

private Future<EventBusMessage> processRemoveRequest(final EventBusMessage request) {
    final String tenantId = request.getTenant();
    final JsonObject payload = request.getJsonPayload();
    if (tenantId == null || payload == null) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    } else {
        final String type = getTypesafeValueForField(payload, CredentialsConstants.FIELD_TYPE);
        final String authId = getTypesafeValueForField(payload, CredentialsConstants.FIELD_AUTH_ID);
        final String deviceId = getTypesafeValueForField(payload, CredentialsConstants.FIELD_PAYLOAD_DEVICE_ID);
        if (type == null) {
            log.debug("remove credentials request does not contain mandatory type parameter");
            return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
        } else if (!type.equals(CredentialsConstants.SPECIFIER_WILDCARD) && authId != null) {
            // delete a single credentials instance
            log.debug("removing specific credentials [tenant: {}, type: {}, auth-id: {}]", tenantId, type, authId);
            final Future<CredentialsResult<JsonObject>> result = Future.future();
            remove(tenantId, type, authId, result.completer());
            return result.map(res -> {
                return request.getResponse(res.getStatus()).setCacheDirective(res.getCacheDirective());
            });
        } else if (deviceId != null && type.equals(CredentialsConstants.SPECIFIER_WILDCARD)) {
            // delete all credentials for device
            log.debug("removing all credentials for device [tenant: {}, device-id: {}]", tenantId, deviceId);
            final Future<CredentialsResult<JsonObject>> result = Future.future();
            removeAll(tenantId, deviceId, result.completer());
            return result.map(res -> {
                return request.getResponse(res.getStatus()).setDeviceId(deviceId).setCacheDirective(res.getCacheDirective());
            });
        } else {
            log.debug("remove credentials request contains invalid search criteria [type: {}, device-id: {}, auth-id: {}]", type, deviceId, authId);
            return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CredentialsResult(org.eclipse.hono.util.CredentialsResult) TenantConstants(org.eclipse.hono.util.TenantConstants) ClientErrorException(org.eclipse.hono.client.ClientErrorException) EventBusMessage(org.eclipse.hono.util.EventBusMessage) Future(io.vertx.core.Future) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Objects(java.util.Objects) EventBusService(org.eclipse.hono.service.EventBusService) Optional(java.util.Optional) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) CredentialsObject(org.eclipse.hono.util.CredentialsObject) JsonObject(io.vertx.core.json.JsonObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Future(io.vertx.core.Future) CredentialsResult(org.eclipse.hono.util.CredentialsResult)

Example 28 with Future

use of io.vertx.core.Future in project hono by eclipse.

the class BaseCredentialsService method processUpdateRequest.

private Future<EventBusMessage> processUpdateRequest(final EventBusMessage request) {
    final String tenantId = request.getTenant();
    final CredentialsObject payload = Optional.ofNullable(request.getJsonPayload()).map(json -> json.mapTo(CredentialsObject.class)).orElse(null);
    if (tenantId == null || payload == null) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    } else if (payload.isValid()) {
        final Future<CredentialsResult<JsonObject>> result = Future.future();
        update(tenantId, JsonObject.mapFrom(payload), result.completer());
        return result.map(res -> {
            return request.getResponse(res.getStatus()).setDeviceId(payload.getDeviceId()).setCacheDirective(res.getCacheDirective());
        });
    } else {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CredentialsResult(org.eclipse.hono.util.CredentialsResult) TenantConstants(org.eclipse.hono.util.TenantConstants) ClientErrorException(org.eclipse.hono.client.ClientErrorException) EventBusMessage(org.eclipse.hono.util.EventBusMessage) Future(io.vertx.core.Future) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Objects(java.util.Objects) EventBusService(org.eclipse.hono.service.EventBusService) Optional(java.util.Optional) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) CredentialsObject(org.eclipse.hono.util.CredentialsObject) CredentialsObject(org.eclipse.hono.util.CredentialsObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Future(io.vertx.core.Future) JsonObject(io.vertx.core.json.JsonObject)

Example 29 with Future

use of io.vertx.core.Future in project hono by eclipse.

the class BaseRegistrationService method assertRegistration.

/**
 * {@inheritDoc}
 * <p>
 * Subclasses may override this method in order to implement a more sophisticated approach for asserting registration status, e.g.
 * using cached information etc.
 */
@Override
public void assertRegistration(final String tenantId, final String deviceId, final String gatewayId, final Handler<AsyncResult<RegistrationResult>> resultHandler) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(gatewayId);
    Objects.requireNonNull(resultHandler);
    Future<RegistrationResult> deviceInfoTracker = Future.future();
    Future<RegistrationResult> gatewayInfoTracker = Future.future();
    getDevice(tenantId, deviceId, deviceInfoTracker.completer());
    getDevice(tenantId, gatewayId, gatewayInfoTracker.completer());
    CompositeFuture.all(deviceInfoTracker, gatewayInfoTracker).compose(ok -> {
        final RegistrationResult deviceResult = deviceInfoTracker.result();
        final RegistrationResult gatewayResult = gatewayInfoTracker.result();
        if (!isDeviceEnabled(deviceResult)) {
            return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_NOT_FOUND));
        } else if (!isDeviceEnabled(gatewayResult)) {
            return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_FORBIDDEN));
        } else {
            final JsonObject deviceData = deviceResult.getPayload().getJsonObject(RegistrationConstants.FIELD_DATA, new JsonObject());
            final JsonObject gatewayData = gatewayResult.getPayload().getJsonObject(RegistrationConstants.FIELD_DATA, new JsonObject());
            if (isGatewayAuthorized(gatewayId, gatewayData, deviceId, deviceData)) {
                return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_OK, getAssertionPayload(tenantId, deviceId, deviceData), CacheDirective.maxAgeDirective(assertionFactory.getAssertionLifetime())));
            } else {
                return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_FORBIDDEN));
            }
        }
    }).setHandler(resultHandler);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CacheDirective(org.eclipse.hono.util.CacheDirective) Autowired(org.springframework.beans.factory.annotation.Autowired) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) ClientErrorException(org.eclipse.hono.client.ClientErrorException) EventBusMessage(org.eclipse.hono.util.EventBusMessage) Future(io.vertx.core.Future) Objects(java.util.Objects) EventBusService(org.eclipse.hono.service.EventBusService) CompositeFuture(io.vertx.core.CompositeFuture) RegistrationResult(org.eclipse.hono.util.RegistrationResult) Qualifier(org.springframework.beans.factory.annotation.Qualifier) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) JsonObject(io.vertx.core.json.JsonObject) RegistrationResult(org.eclipse.hono.util.RegistrationResult)

Example 30 with Future

use of io.vertx.core.Future in project hono by eclipse.

the class BaseRegistrationService method processAssertRequest.

private Future<EventBusMessage> processAssertRequest(final EventBusMessage request) {
    final String tenantId = request.getTenant();
    final String deviceId = request.getDeviceId();
    final String gatewayId = request.getGatewayId();
    if (tenantId == null || deviceId == null) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    } else if (gatewayId == null) {
        log.debug("asserting registration of device [{}] with tenant [{}]", deviceId, tenantId);
        final Future<RegistrationResult> result = Future.future();
        assertRegistration(tenantId, deviceId, result.completer());
        return result.map(res -> {
            return request.getResponse(res.getStatus()).setDeviceId(deviceId).setJsonPayload(res.getPayload()).setCacheDirective(res.getCacheDirective());
        });
    } else {
        log.debug("asserting registration of device [{}] with tenant [{}] for gateway [{}]", deviceId, tenantId, gatewayId);
        final Future<RegistrationResult> result = Future.future();
        assertRegistration(tenantId, deviceId, gatewayId, result.completer());
        return result.map(res -> {
            return request.getResponse(res.getStatus()).setDeviceId(deviceId).setJsonPayload(res.getPayload()).setCacheDirective(res.getCacheDirective());
        });
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CacheDirective(org.eclipse.hono.util.CacheDirective) Autowired(org.springframework.beans.factory.annotation.Autowired) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) ClientErrorException(org.eclipse.hono.client.ClientErrorException) EventBusMessage(org.eclipse.hono.util.EventBusMessage) Future(io.vertx.core.Future) Objects(java.util.Objects) EventBusService(org.eclipse.hono.service.EventBusService) CompositeFuture(io.vertx.core.CompositeFuture) RegistrationResult(org.eclipse.hono.util.RegistrationResult) Qualifier(org.springframework.beans.factory.annotation.Qualifier) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture)

Aggregations

Future (io.vertx.core.Future)375 HttpURLConnection (java.net.HttpURLConnection)195 Handler (io.vertx.core.Handler)174 List (java.util.List)166 Objects (java.util.Objects)164 JsonObject (io.vertx.core.json.JsonObject)163 Promise (io.vertx.core.Promise)159 Vertx (io.vertx.core.Vertx)157 Buffer (io.vertx.core.buffer.Buffer)149 Optional (java.util.Optional)147 Logger (org.slf4j.Logger)136 LoggerFactory (org.slf4j.LoggerFactory)136 CompositeFuture (io.vertx.core.CompositeFuture)127 ClientErrorException (org.eclipse.hono.client.ClientErrorException)127 Map (java.util.Map)122 Span (io.opentracing.Span)117 AsyncResult (io.vertx.core.AsyncResult)112 TracingHelper (org.eclipse.hono.tracing.TracingHelper)98 Constants (org.eclipse.hono.util.Constants)97 ArrayList (java.util.ArrayList)94