Search in sources :

Example 11 with Future

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

the class CrudHttpClient method create.

/**
 * Creates a resource using HTTP POST.
 *
 * @param uri The URI to post to.
 * @param body The body to post (may be {@code null}).
 * @param contentType The content type to set in the request (may be {@code null}).
 * @param successPredicate A predicate on the returned HTTP status code for determining success.
 * @return A future that will succeed if the predicate evaluates to {@code true}.
 */
public Future<Void> create(final String uri, final Buffer body, final String contentType, final Predicate<HttpClientResponse> successPredicate) {
    Objects.requireNonNull(uri);
    Objects.requireNonNull(successPredicate);
    final Future<Void> result = Future.future();
    final HttpClientRequest req = vertx.createHttpClient().post(port, host, uri).handler(response -> {
        if (successPredicate.test(response)) {
            result.complete();
        } else {
            result.fail(new ServiceInvocationException(response.statusCode()));
        }
    }).exceptionHandler(result::fail);
    if (contentType != null) {
        req.putHeader(HttpHeaders.CONTENT_TYPE, contentType);
    }
    if (body == null) {
        req.end();
    } else {
        req.end(body);
    }
    return result;
}
Also used : Objects(java.util.Objects) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) Buffer(io.vertx.core.buffer.Buffer) Predicate(java.util.function.Predicate) Vertx(io.vertx.core.Vertx) Optional(java.util.Optional) HttpHeaders(io.vertx.core.http.HttpHeaders) JsonObject(io.vertx.core.json.JsonObject) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Future(io.vertx.core.Future) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException)

Example 12 with Future

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

the class ClientTestBase method connect.

/**
 * Sets up the environment:
 * <ol>
 * <li>connect to the AMQP messaging network</li>
 * <li>connects to the Hono Server</li>
 * <li>connects to the Hono Device Registry</li>
 * <li>creates a RegistrationClient for TEST_TENANT_ID</li>
 * <li>creates a MessageSender for TEST_TENANT_ID</li>
 * </ul>
 *
 * @param ctx The test context
 */
@Before
public void connect(final TestContext ctx) {
    final ClientConfigProperties downstreamProps = new ClientConfigProperties();
    downstreamProps.setHost(IntegrationTestSupport.DOWNSTREAM_HOST);
    downstreamProps.setPort(IntegrationTestSupport.DOWNSTREAM_PORT);
    downstreamProps.setPathSeparator(IntegrationTestSupport.PATH_SEPARATOR);
    downstreamProps.setUsername(IntegrationTestSupport.RESTRICTED_CONSUMER_NAME);
    downstreamProps.setPassword(IntegrationTestSupport.RESTRICTED_CONSUMER_PWD);
    downstreamClient = new HonoClientImpl(vertx, ConnectionFactoryBuilder.newBuilder(downstreamProps).vertx(vertx).build(), downstreamProps);
    final ClientConfigProperties honoProps = new ClientConfigProperties();
    honoProps.setHost(IntegrationTestSupport.HONO_HOST);
    honoProps.setPort(IntegrationTestSupport.HONO_PORT);
    honoProps.setUsername(IntegrationTestSupport.HONO_USER);
    honoProps.setPassword(IntegrationTestSupport.HONO_PWD);
    honoClient = new HonoClientImpl(vertx, ConnectionFactoryBuilder.newBuilder(honoProps).vertx(vertx).build(), honoProps);
    final ClientConfigProperties registryProps = new ClientConfigProperties();
    registryProps.setHost(IntegrationTestSupport.HONO_DEVICEREGISTRY_HOST);
    registryProps.setPort(IntegrationTestSupport.HONO_DEVICEREGISTRY_AMQP_PORT);
    registryProps.setUsername(IntegrationTestSupport.HONO_USER);
    registryProps.setPassword(IntegrationTestSupport.HONO_PWD);
    honoDeviceRegistryClient = new HonoClientImpl(vertx, ConnectionFactoryBuilder.newBuilder(registryProps).vertx(vertx).build(), registryProps);
    final ProtonClientOptions options = new ProtonClientOptions();
    // connect to AMQP messaging network
    final Future<HonoClient> downstreamTracker = downstreamClient.connect(options);
    // create sender
    final Future<MessageSender> senderTracker = honoClient.connect(options).compose(connectedClient -> createProducer(TEST_TENANT_ID)).map(s -> {
        sender = s;
        return s;
    });
    // create registration client
    final Future<RegistrationClient> registrationClientTracker = honoDeviceRegistryClient.connect(options).compose(connectedClient -> connectedClient.getOrCreateRegistrationClient(TEST_TENANT_ID)).map(c -> {
        registrationClient = c;
        return c;
    });
    CompositeFuture.all(downstreamTracker, senderTracker, registrationClientTracker).setHandler(ctx.asyncAssertSuccess(s -> {
        LOGGER.info("connections to Hono server, Hono device registry and AMQP messaging network established");
    }));
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) LoggerFactory(org.slf4j.LoggerFactory) MessageConsumer(org.eclipse.hono.client.MessageConsumer) AtomicReference(java.util.concurrent.atomic.AtomicReference) Constants(org.eclipse.hono.util.Constants) CompositeFuture(io.vertx.core.CompositeFuture) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConnectionFactoryBuilder(org.eclipse.hono.connection.ConnectionFactoryImpl.ConnectionFactoryBuilder) MessageSender(org.eclipse.hono.client.MessageSender) After(org.junit.After) Message(org.apache.qpid.proton.message.Message) RegistrationClient(org.eclipse.hono.client.RegistrationClient) HonoClient(org.eclipse.hono.client.HonoClient) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Before(org.junit.Before) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) HonoClient(org.eclipse.hono.client.HonoClient) MessageSender(org.eclipse.hono.client.MessageSender) RegistrationClient(org.eclipse.hono.client.RegistrationClient) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Before(org.junit.Before)

Example 13 with Future

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

the class TelemetryMqttIT method testConnectFailsForDisabledTenant.

/**
 * Verifies that the adapter rejects connection attempts from devices
 * that belong to a tenant for which the adapter has been disabled.
 *
 * @param ctx The test context
 */
@Test
public void testConnectFailsForDisabledTenant(final TestContext ctx) {
    // GIVEN a tenant for which the HTTP adapter is disabled
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String password = "secret";
    final JsonObject adapterDetailsHttp = new JsonObject().put(TenantConstants.FIELD_ADAPTERS_TYPE, Constants.PROTOCOL_ADAPTER_TYPE_MQTT).put(TenantConstants.FIELD_ENABLED, Boolean.FALSE);
    final TenantObject tenant = TenantObject.from(tenantId, true);
    tenant.addAdapterConfiguration(adapterDetailsHttp);
    helper.registry.addDeviceForTenant(tenant, deviceId, password).compose(ok -> {
        final Future<MqttConnAckMessage> result = Future.future();
        final MqttClientOptions options = new MqttClientOptions().setUsername(IntegrationTestSupport.getUsername(deviceId, tenantId)).setPassword(password);
        mqttClient = MqttClient.create(VERTX, options);
        // WHEN a device that belongs to the tenant tries to connect to the adapter
        mqttClient.connect(IntegrationTestSupport.MQTT_PORT, IntegrationTestSupport.MQTT_HOST, result.completer());
        return result;
    }).setHandler(ctx.asyncAssertFailure(t -> {
    // THEN the connection attempt gets rejected
    }));
}
Also used : TestContext(io.vertx.ext.unit.TestContext) MqttConnAckMessage(io.vertx.mqtt.messages.MqttConnAckMessage) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) TenantConstants(org.eclipse.hono.util.TenantConstants) RunWith(org.junit.runner.RunWith) MessageConsumer(org.eclipse.hono.client.MessageConsumer) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Constants(org.eclipse.hono.util.Constants) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) Consumer(java.util.function.Consumer) MqttClientOptions(io.vertx.mqtt.MqttClientOptions) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) Buffer(io.vertx.core.buffer.Buffer) MqttClient(io.vertx.mqtt.MqttClient) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) TenantObject(org.eclipse.hono.util.TenantObject) MqttClientOptions(io.vertx.mqtt.MqttClientOptions) JsonObject(io.vertx.core.json.JsonObject) Future(io.vertx.core.Future) Test(org.junit.Test)

Example 14 with Future

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

the class CredentialsHttpIT method addMultipleCredentials.

private static Future<Integer> addMultipleCredentials(final List<JsonObject> credentialsList) {
    final Future<Integer> result = Future.future();
    @SuppressWarnings("rawtypes") final List<Future> addTrackers = new ArrayList<>();
    for (JsonObject creds : credentialsList) {
        addTrackers.add(registry.addCredentials(TENANT, creds));
    }
    CompositeFuture.all(addTrackers).setHandler(r -> {
        if (r.succeeded()) {
            result.complete(HttpURLConnection.HTTP_CREATED);
        } else {
            result.fail(r.cause());
        }
    });
    return result;
}
Also used : ArrayList(java.util.ArrayList) CompositeFuture(io.vertx.core.CompositeFuture) Future(io.vertx.core.Future) JsonObject(io.vertx.core.json.JsonObject)

Example 15 with Future

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

the class FileBasedRegistrationService method saveToFile.

Future<Void> saveToFile() {
    if (!getConfig().isSaveToFile()) {
        return Future.succeededFuture();
    } else if (dirty) {
        return checkFileExists(true).compose(s -> {
            final AtomicInteger idCount = new AtomicInteger();
            final JsonArray tenants = new JsonArray();
            for (Entry<String, Map<String, JsonObject>> entry : identities.entrySet()) {
                final JsonArray devices = new JsonArray();
                for (Entry<String, JsonObject> deviceEntry : entry.getValue().entrySet()) {
                    devices.add(new JsonObject().put(FIELD_PAYLOAD_DEVICE_ID, deviceEntry.getKey()).put(FIELD_DATA, deviceEntry.getValue()));
                    idCount.incrementAndGet();
                }
                tenants.add(new JsonObject().put(FIELD_TENANT, entry.getKey()).put(ARRAY_DEVICES, devices));
            }
            Future<Void> writeHandler = Future.future();
            vertx.fileSystem().writeFile(getConfig().getFilename(), Buffer.factory.buffer(tenants.encodePrettily()), writeHandler.completer());
            return writeHandler.map(ok -> {
                dirty = false;
                log.trace("successfully wrote {} device identities to file {}", idCount.get(), getConfig().getFilename());
                return (Void) null;
            }).otherwise(t -> {
                log.warn("could not write device identities to file {}", getConfig().getFilename(), t);
                return (Void) null;
            });
        });
    } else {
        log.trace("registry does not need to be persisted");
        return Future.succeededFuture();
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) FIELD_ENABLED(org.eclipse.hono.util.RequestResponseApiConstants.FIELD_ENABLED) DecodeException(io.vertx.core.json.DecodeException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) BaseRegistrationService(org.eclipse.hono.service.registration.BaseRegistrationService) Future(io.vertx.core.Future) Objects(java.util.Objects) FIELD_PAYLOAD_DEVICE_ID(org.eclipse.hono.util.RequestResponseApiConstants.FIELD_PAYLOAD_DEVICE_ID) JsonArray(io.vertx.core.json.JsonArray) Buffer(io.vertx.core.buffer.Buffer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) RegistrationResult(org.eclipse.hono.util.RegistrationResult) FIELD_DATA(org.eclipse.hono.util.RegistrationConstants.FIELD_DATA) Entry(java.util.Map.Entry) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Repository(org.springframework.stereotype.Repository) Handler(io.vertx.core.Handler) JsonArray(io.vertx.core.json.JsonArray) Entry(java.util.Map.Entry) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JsonObject(io.vertx.core.json.JsonObject) Future(io.vertx.core.Future)

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