Search in sources :

Example 31 with Future

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

the class BaseTenantService method processAddRequest.

private Future<EventBusMessage> processAddRequest(final EventBusMessage request) {
    final String tenantId = request.getTenant();
    final JsonObject payload = getRequestPayload(request.getJsonPayload());
    if (tenantId == null) {
        log.debug("request does not contain mandatory property [{}]", MessageHelper.APP_PROPERTY_TENANT_ID);
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    } else if (isValidRequestPayload(payload)) {
        log.debug("creating tenant [{}]", tenantId);
        final Future<TenantResult<JsonObject>> addResult = Future.future();
        addNotPresentFieldsWithDefaultValuesForTenant(payload);
        add(tenantId, payload, addResult.completer());
        return addResult.map(tr -> {
            return request.getResponse(tr.getStatus()).setJsonPayload(tr.getPayload()).setCacheDirective(tr.getCacheDirective());
        });
    } else {
        log.debug("request contains malformed payload");
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TenantResult(org.eclipse.hono.util.TenantResult) TenantConstants(org.eclipse.hono.util.TenantConstants) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ClientErrorException(org.eclipse.hono.client.ClientErrorException) EventBusMessage(org.eclipse.hono.util.EventBusMessage) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Objects(java.util.Objects) EventBusService(org.eclipse.hono.service.EventBusService) JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) JsonObject(io.vertx.core.json.JsonObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Future(io.vertx.core.Future)

Example 32 with Future

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

the class BaseTenantService method processGetRequest.

private Future<EventBusMessage> processGetRequest(final EventBusMessage request) {
    final String tenantId = request.getTenant();
    final JsonObject payload = request.getJsonPayload();
    if (tenantId == null && payload == null) {
        log.debug("request does not contain any query parameters");
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    } else if (payload != null) {
        final String tenantIdFromPayload = getTypesafeValueForField(payload, TenantConstants.FIELD_PAYLOAD_TENANT_ID);
        if (tenantIdFromPayload == null) {
            log.debug("payload does not contain any query parameters");
            return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
        } else {
            log.debug("retrieving tenant [id: {}]", tenantIdFromPayload);
            final Future<TenantResult<JsonObject>> getResult = Future.future();
            get(tenantIdFromPayload, getResult.completer());
            return getResult.map(tr -> {
                return request.getResponse(tr.getStatus()).setJsonPayload(tr.getPayload()).setTenant(tenantIdFromPayload).setCacheDirective(tr.getCacheDirective());
            });
        }
    } else {
        // deprecated API
        log.debug("retrieving tenant [{}] using deprecated variant of get tenant request", tenantId);
        final Future<TenantResult<JsonObject>> getResult = Future.future();
        get(tenantId, getResult.completer());
        return getResult.map(tr -> {
            return request.getResponse(tr.getStatus()).setJsonPayload(tr.getPayload()).setTenant(tenantId).setCacheDirective(tr.getCacheDirective());
        });
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TenantResult(org.eclipse.hono.util.TenantResult) TenantConstants(org.eclipse.hono.util.TenantConstants) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ClientErrorException(org.eclipse.hono.client.ClientErrorException) EventBusMessage(org.eclipse.hono.util.EventBusMessage) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Objects(java.util.Objects) EventBusService(org.eclipse.hono.service.EventBusService) JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) JsonObject(io.vertx.core.json.JsonObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Future(io.vertx.core.Future)

Example 33 with Future

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

the class AbstractVertxBasedMqttProtocolAdapter method uploadMessage.

private Future<Void> uploadMessage(final MqttContext ctx, final String tenant, final String deviceId, final Buffer payload, final Future<MessageSender> senderTracker, final String endpointName) {
    if (payload.length() == 0) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "payload must not be empty"));
    } else {
        final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId, ctx.authenticatedDevice());
        final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant);
        return CompositeFuture.all(tokenTracker, tenantConfigTracker, senderTracker).compose(ok -> {
            if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) {
                final Message downstreamMessage = newMessage(String.format("%s/%s", endpointName, tenant), deviceId, ctx.message().topicName(), ctx.contentType(), payload, tokenTracker.result());
                customizeDownstreamMessage(downstreamMessage, ctx);
                return senderTracker.result().send(downstreamMessage);
            } else {
                // this adapter is not enabled for the tenant
                return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN));
            }
        }).compose(delivery -> {
            LOG.trace("successfully processed message [topic: {}, QoS: {}] for device [tenantId: {}, deviceId: {}]", ctx.message().topicName(), ctx.message().qosLevel(), tenant, deviceId);
            metrics.incrementProcessedMqttMessages(endpointName, tenant);
            onMessageSent(ctx);
            // check that the remote MQTT client is still connected before sending PUBACK
            if (ctx.deviceEndpoint().isConnected() && ctx.message().qosLevel() == MqttQoS.AT_LEAST_ONCE) {
                ctx.deviceEndpoint().publishAcknowledge(ctx.message().messageId());
            }
            return Future.<Void>succeededFuture();
        }).recover(t -> {
            if (ClientErrorException.class.isInstance(t)) {
                ClientErrorException e = (ClientErrorException) t;
                LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]: {} - {}", tenant, deviceId, endpointName, e.getErrorCode(), e.getMessage());
            } else {
                LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]", tenant, deviceId, endpointName, t);
                metrics.incrementUndeliverableMqttMessages(endpointName, tenant);
                onMessageUndeliverable(ctx);
            }
            return Future.failedFuture(t);
        });
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) MqttConnectReturnCode(io.netty.handler.codec.mqtt.MqttConnectReturnCode) LoggerFactory(org.slf4j.LoggerFactory) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) Autowired(org.springframework.beans.factory.annotation.Autowired) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) MqttServer(io.vertx.mqtt.MqttServer) CompositeFuture(io.vertx.core.CompositeFuture) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) MessageSender(org.eclipse.hono.client.MessageSender) AbstractProtocolAdapterBase(org.eclipse.hono.service.AbstractProtocolAdapterBase) Message(org.apache.qpid.proton.message.Message) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) JsonObject(io.vertx.core.json.JsonObject) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) UsernamePasswordCredentials(org.eclipse.hono.service.auth.device.UsernamePasswordCredentials) Logger(org.slf4j.Logger) MqttServerOptions(io.vertx.mqtt.MqttServerOptions) DeviceCredentials(org.eclipse.hono.service.auth.device.DeviceCredentials) ServerErrorException(org.eclipse.hono.client.ServerErrorException) EndpointType(org.eclipse.hono.util.EndpointType) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) Objects(java.util.Objects) Buffer(io.vertx.core.buffer.Buffer) MqttAuth(io.vertx.mqtt.MqttAuth) Device(org.eclipse.hono.service.auth.device.Device) TenantObject(org.eclipse.hono.util.TenantObject) Message(org.apache.qpid.proton.message.Message) ClientErrorException(org.eclipse.hono.client.ClientErrorException) JsonObject(io.vertx.core.json.JsonObject)

Example 34 with Future

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

the class HonoClientImplTest method testGetOrCreateRequestResponseClientFailsIfInvokedConcurrently.

/**
 * Verifies that a concurrent request to create a request-response client fails the given
 * future for tracking the attempt.
 *
 * @param ctx The helper to use for running async tests.
 */
@Test
public void testGetOrCreateRequestResponseClientFailsIfInvokedConcurrently(final TestContext ctx) {
    // GIVEN a client that already tries to create a registration client for "tenant"
    final Async connected = ctx.async();
    client.connect(new ProtonClientOptions()).setHandler(ctx.asyncAssertSuccess(ok -> connected.complete()));
    connected.await();
    client.getOrCreateRequestResponseClient("registration/tenant", () -> Future.future(), result -> {
    });
    // WHEN an additional, concurrent attempt is made to create a client for "tenant"
    client.getOrCreateRequestResponseClient("registration/tenant", () -> {
        ctx.fail("should not create concurrent client");
        return Future.succeededFuture(mock(RegistrationClient.class));
    }, ctx.<RequestResponseClient>asyncAssertFailure(t -> {
        // THEN the concurrent attempt fails without any attempt being made to create another client
        ctx.assertTrue(ServerErrorException.class.isInstance(t));
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) RequestResponseClient(org.eclipse.hono.client.RequestResponseClient) TestContext(io.vertx.ext.unit.TestContext) ProtonConnection(io.vertx.proton.ProtonConnection) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) InetAddress(java.net.InetAddress) ConnectionFactory(org.eclipse.hono.connection.ConnectionFactory) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) MessageSender(org.eclipse.hono.client.MessageSender) Timeout(org.junit.rules.Timeout) RegistrationClient(org.eclipse.hono.client.RegistrationClient) AsyncResult(io.vertx.core.AsyncResult) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Before(org.junit.Before) AfterClass(org.junit.AfterClass) Vertx(io.vertx.core.Vertx) Assert.assertTrue(org.junit.Assert.assertTrue) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Handler(io.vertx.core.Handler) Async(io.vertx.ext.unit.Async) RegistrationClient(org.eclipse.hono.client.RegistrationClient) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Test(org.junit.Test)

Example 35 with Future

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

the class HonoClientImplTest method testGetOrCreateTelemetrySenderFailsIfInvokedConcurrently.

/**
 * Verifies that a concurrent request to create a sender fails the given future for tracking the attempt.
 *
 * @param ctx The helper to use for running async tests.
 */
@Test
public void testGetOrCreateTelemetrySenderFailsIfInvokedConcurrently(final TestContext ctx) {
    // GIVEN a client that already tries to create a telemetry sender for "tenant"
    final Async connected = ctx.async();
    client.connect(new ProtonClientOptions()).setHandler(ctx.asyncAssertSuccess(ok -> connected.complete()));
    connected.await();
    client.getOrCreateSender("telemetry/tenant", () -> Future.future());
    // WHEN an additional, concurrent attempt is made to create a telemetry sender for "tenant"
    client.getOrCreateSender("telemetry/tenant", () -> {
        ctx.fail("should not create concurrent client");
        return Future.succeededFuture(mock(MessageSender.class));
    }).setHandler(ctx.asyncAssertFailure(t -> {
        // THEN the concurrent attempt fails without any attempt being made to create another sender
        ctx.assertTrue(ServerErrorException.class.isInstance(t));
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) RequestResponseClient(org.eclipse.hono.client.RequestResponseClient) TestContext(io.vertx.ext.unit.TestContext) ProtonConnection(io.vertx.proton.ProtonConnection) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) InetAddress(java.net.InetAddress) ConnectionFactory(org.eclipse.hono.connection.ConnectionFactory) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) MessageSender(org.eclipse.hono.client.MessageSender) Timeout(org.junit.rules.Timeout) RegistrationClient(org.eclipse.hono.client.RegistrationClient) AsyncResult(io.vertx.core.AsyncResult) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Before(org.junit.Before) AfterClass(org.junit.AfterClass) Vertx(io.vertx.core.Vertx) Assert.assertTrue(org.junit.Assert.assertTrue) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Handler(io.vertx.core.Handler) Async(io.vertx.ext.unit.Async) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Test(org.junit.Test)

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