Search in sources :

Example 51 with JsonArray

use of io.vertx.core.json.JsonArray in project hono by eclipse.

the class FileBasedTenantService method saveToFile.

Future<Void> saveToFile() {
    if (!getConfig().isSaveToFile()) {
        return Future.succeededFuture();
    } else if (dirty) {
        return checkFileExists(true).compose(s -> {
            final JsonArray tenantsJson = new JsonArray();
            tenants.values().stream().forEach(tenant -> {
                tenantsJson.add(JsonObject.mapFrom(tenant));
            });
            final Future<Void> writeHandler = Future.future();
            vertx.fileSystem().writeFile(getConfig().getFilename(), Buffer.factory.buffer(tenantsJson.encodePrettily()), writeHandler.completer());
            return writeHandler.map(ok -> {
                dirty = false;
                log.trace("successfully wrote {} tenants to file {}", tenantsJson.size(), getConfig().getFilename());
                return (Void) null;
            }).otherwise(t -> {
                log.warn("could not write tenants to file {}", getConfig().getFilename(), t);
                return (Void) null;
            });
        });
    } else {
        log.trace("tenants registry does not need to be persisted");
        return Future.succeededFuture();
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CacheDirective(org.eclipse.hono.util.CacheDirective) TenantResult(org.eclipse.hono.util.TenantResult) DecodeException(io.vertx.core.json.DecodeException) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) Objects(java.util.Objects) JsonArray(io.vertx.core.json.JsonArray) Buffer(io.vertx.core.buffer.Buffer) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) BaseTenantService(org.eclipse.hono.service.tenant.BaseTenantService) AsyncResult(io.vertx.core.AsyncResult) Repository(org.springframework.stereotype.Repository) Handler(io.vertx.core.Handler) JsonArray(io.vertx.core.json.JsonArray) Future(io.vertx.core.Future)

Example 52 with JsonArray

use of io.vertx.core.json.JsonArray in project hono by eclipse.

the class FileBasedTenantService method addAll.

private Future<Void> addAll(final Buffer tenantsBuffer) {
    final Future<Void> result = Future.future();
    try {
        if (tenantsBuffer.length() > 0) {
            int tenantCount = 0;
            final JsonArray allObjects = tenantsBuffer.toJsonArray();
            for (final Object obj : allObjects) {
                if (JsonObject.class.isInstance(obj)) {
                    tenantCount++;
                    addTenant((JsonObject) obj);
                }
            }
            log.info("successfully loaded {} tenants from file [{}]", tenantCount, getConfig().getFilename());
        }
        result.complete();
    } catch (final DecodeException e) {
        log.warn("cannot read malformed JSON from tenants file [{}]", getConfig().getFilename());
        result.fail(e);
    }
    return result;
}
Also used : JsonArray(io.vertx.core.json.JsonArray) TenantObject(org.eclipse.hono.util.TenantObject) JsonObject(io.vertx.core.json.JsonObject) DecodeException(io.vertx.core.json.DecodeException)

Example 53 with JsonArray

use of io.vertx.core.json.JsonArray in project hono by eclipse.

the class FileBasedCredentialsServiceTest method testGetCredentialsSucceedsForExistingCredentials.

/**
 * Verifies that the service returns existing credentials.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetCredentialsSucceedsForExistingCredentials(final TestContext ctx) {
    register(svc, "tenant", "device", "myId", "myType", new JsonArray(), ctx);
    final Async get = ctx.async();
    svc.get("tenant", "myType", "myId", ctx.asyncAssertSuccess(s -> {
        assertThat(s.getStatus(), is(HttpURLConnection.HTTP_OK));
        assertThat(s.getPayload().getString(CredentialsConstants.FIELD_AUTH_ID), is("myId"));
        assertThat(s.getPayload().getString(CredentialsConstants.FIELD_TYPE), is("myType"));
        get.complete();
    }));
    get.await(2000);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) 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) 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) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Matchers.any(org.mockito.Matchers.any) Mockito(org.mockito.Mockito) JsonArray(io.vertx.core.json.JsonArray) Buffer(io.vertx.core.buffer.Buffer) FileSystem(io.vertx.core.file.FileSystem) CredentialsService(org.eclipse.hono.service.credentials.CredentialsService) Handler(io.vertx.core.Handler) CredentialsObject(org.eclipse.hono.util.CredentialsObject) Async(io.vertx.ext.unit.Async) Test(org.junit.Test)

Example 54 with JsonArray

use of io.vertx.core.json.JsonArray in project hono by eclipse.

the class FileBasedTenantServiceTest method buildTenantPayload.

/**
 * Creates a tenant object for a tenantId.
 * <p>
 * The tenant object created contains configurations for the http and the mqtt adapter.
 *
 * @param tenantId The tenant identifier.
 * @return The tenant object.
 */
private static JsonObject buildTenantPayload(final String tenantId) {
    final JsonObject adapterDetailsHttp = new JsonObject().put(TenantConstants.FIELD_ADAPTERS_TYPE, Constants.PROTOCOL_ADAPTER_TYPE_HTTP).put(TenantConstants.FIELD_ADAPTERS_DEVICE_AUTHENTICATION_REQUIRED, Boolean.TRUE).put(TenantConstants.FIELD_ENABLED, Boolean.TRUE);
    final JsonObject adapterDetailsMqtt = new JsonObject().put(TenantConstants.FIELD_ADAPTERS_TYPE, Constants.PROTOCOL_ADAPTER_TYPE_MQTT).put(TenantConstants.FIELD_ADAPTERS_DEVICE_AUTHENTICATION_REQUIRED, Boolean.TRUE).put(TenantConstants.FIELD_ENABLED, Boolean.TRUE);
    final JsonObject tenantPayload = new JsonObject().put(TenantConstants.FIELD_PAYLOAD_TENANT_ID, tenantId).put(TenantConstants.FIELD_ENABLED, Boolean.TRUE).put(TenantConstants.FIELD_ADAPTERS, new JsonArray().add(adapterDetailsHttp).add(adapterDetailsMqtt));
    return tenantPayload;
}
Also used : JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject)

Example 55 with JsonArray

use of io.vertx.core.json.JsonArray in project hono by eclipse.

the class BaseTenantService method addNotPresentFieldsWithDefaultValuesForTenant.

/**
 * Add default values for optional fields that are not filled in the payload.
 * <p>
 * Payload should be checked for validity first, there is no error handling inside this method anymore.
 * </p>
 *
 * @param checkedPayload The checked payload to add optional fields to.
 * @throws ClassCastException If the {@link TenantConstants#FIELD_ADAPTERS_TYPE} element is not a {@link JsonArray}
 *       or the JsonArray contains elements that are not of type {@link JsonObject}.
 */
protected final void addNotPresentFieldsWithDefaultValuesForTenant(final JsonObject checkedPayload) {
    if (!checkedPayload.containsKey(TenantConstants.FIELD_ENABLED)) {
        log.trace("adding 'enabled' key to payload");
        checkedPayload.put(TenantConstants.FIELD_ENABLED, Boolean.TRUE);
    }
    final JsonArray adapters = checkedPayload.getJsonArray(TenantConstants.FIELD_ADAPTERS);
    if (adapters != null) {
        adapters.forEach(elem -> addNotPresentFieldsWithDefaultValuesForAdapter((JsonObject) elem));
    }
}
Also used : JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject)

Aggregations

JsonArray (io.vertx.core.json.JsonArray)535 JsonObject (io.vertx.core.json.JsonObject)379 Test (org.junit.Test)185 List (java.util.List)69 ArrayList (java.util.ArrayList)66 Map (java.util.Map)52 Handler (io.vertx.core.Handler)49 HashMap (java.util.HashMap)42 Collectors (java.util.stream.Collectors)42 Test (org.junit.jupiter.api.Test)41 Future (io.vertx.core.Future)37 IOException (java.io.IOException)35 AsyncResult (io.vertx.core.AsyncResult)34 Buffer (io.vertx.core.buffer.Buffer)33 HttpURLConnection (java.net.HttpURLConnection)30 StandardCharsets (java.nio.charset.StandardCharsets)29 RoutingContext (io.vertx.ext.web.RoutingContext)26 Objects (java.util.Objects)25 Instant (java.time.Instant)24 Rule (org.junit.Rule)22