Search in sources :

Example 16 with Future

use of io.vertx.core.Future 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 17 with Future

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

the class FileBasedCredentialsServiceTest method testDoStartLoadsCredentials.

/**
 * Verifies that credentials are successfully loaded from file during startup.
 *
 * @param ctx The test context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testDoStartLoadsCredentials(final TestContext ctx) {
    // GIVEN a service configured with a file name
    props.setFilename(FILE_NAME);
    when(fileSystem.existsBlocking(props.getFilename())).thenReturn(Boolean.TRUE);
    doAnswer(invocation -> {
        final Buffer data = DeviceRegistryTestUtils.readFile(FILE_NAME);
        Handler handler = invocation.getArgument(1);
        handler.handle(Future.succeededFuture(data));
        return null;
    }).when(fileSystem).readFile(eq(props.getFilename()), any(Handler.class));
    // WHEN the service is started
    Async startup = ctx.async();
    Future<Void> startFuture = Future.future();
    startFuture.setHandler(ctx.asyncAssertSuccess(s -> {
        startup.complete();
    }));
    svc.doStart(startFuture);
    // THEN the credentials from the file are loaded
    startup.await(2000);
    assertRegistered(svc, Constants.DEFAULT_TENANT, "sensor1", CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD, ctx);
}
Also used : Buffer(io.vertx.core.buffer.Buffer) 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) Handler(io.vertx.core.Handler) Test(org.junit.Test)

Example 18 with Future

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

the class FileBasedCredentialsServiceTest method testDoStartIgnoresMalformedJson.

/**
 * Verifies that the credentials service successfully starts up even if
 * the file to read credentials from contains malformed JSON.
 *
 * @param ctx The vert.x context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testDoStartIgnoresMalformedJson(final TestContext ctx) {
    // GIVEN a registration service configured to read data from a file
    // that contains malformed JSON
    props.setFilename(FILE_NAME);
    when(fileSystem.existsBlocking(FILE_NAME)).thenReturn(Boolean.TRUE);
    doAnswer(invocation -> {
        final Buffer data = mock(Buffer.class);
        when(data.getBytes()).thenReturn("NO JSON".getBytes(StandardCharsets.UTF_8));
        Handler handler = invocation.getArgument(1);
        handler.handle(Future.succeededFuture(data));
        return null;
    }).when(fileSystem).readFile(eq(props.getFilename()), any(Handler.class));
    // WHEN starting the service
    Async startup = ctx.async();
    Future<Void> startupTracker = Future.future();
    startupTracker.setHandler(ctx.asyncAssertSuccess(started -> {
        startup.complete();
    }));
    svc.doStart(startupTracker);
    // THEN startup succeeds
    startup.await(2000);
}
Also used : Buffer(io.vertx.core.buffer.Buffer) 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) Handler(io.vertx.core.Handler) Test(org.junit.Test)

Example 19 with Future

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

the class FileBasedRegistrationServiceTest method testDoStartIgnoresMalformedJson.

/**
 * Verifies that the registration service successfully starts up even if
 * the file to read device information from contains malformed JSON.
 *
 * @param ctx The vert.x context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testDoStartIgnoresMalformedJson(final TestContext ctx) {
    // GIVEN a registration service configured to read data from a file
    // that contains malformed JSON
    when(fileSystem.existsBlocking(props.getFilename())).thenReturn(Boolean.TRUE);
    doAnswer(invocation -> {
        final Buffer data = mock(Buffer.class);
        when(data.getBytes()).thenReturn("NO JSON".getBytes(StandardCharsets.UTF_8));
        Handler handler = invocation.getArgument(1);
        handler.handle(Future.succeededFuture(data));
        return null;
    }).when(fileSystem).readFile(eq(props.getFilename()), any(Handler.class));
    // WHEN starting the service
    Async startup = ctx.async();
    Future<Void> startupTracker = Future.future();
    startupTracker.setHandler(ctx.asyncAssertSuccess(started -> {
        startup.complete();
    }));
    registrationService.doStart(startupTracker);
    // THEN startup succeeds
    startup.await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) ArgumentMatchers(org.mockito.ArgumentMatchers) RunWith(org.junit.runner.RunWith) EventBusMessage(org.eclipse.hono.util.EventBusMessage) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) Context(io.vertx.core.Context) Assert.assertThat(org.junit.Assert.assertThat) EventBus(io.vertx.core.eventbus.EventBus) RegistrationResult(org.eclipse.hono.util.RegistrationResult) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) Assert.assertFalse(org.junit.Assert.assertFalse) 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 20 with Future

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

the class FileBasedRegistrationServiceTest method testDoStartCreatesFile.

/**
 * Verifies that the registration service creates a file for persisting device registration
 * 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 registration service configured to persist data to a not yet existing file
    props.setSaveToFile(true);
    when(fileSystem.existsBlocking(props.getFilename())).thenReturn(Boolean.FALSE);
    doAnswer(invocation -> {
        Handler handler = invocation.getArgument(1);
        handler.handle(Future.succeededFuture());
        return null;
    }).when(fileSystem).createFile(eq(props.getFilename()), any(Handler.class));
    doAnswer(invocation -> {
        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
    Async startup = ctx.async();
    Future<Void> startupTracker = Future.future();
    startupTracker.setHandler(ctx.asyncAssertSuccess(started -> {
        startup.complete();
    }));
    registrationService.doStart(startupTracker);
    // THEN the file gets created
    startup.await();
    verify(fileSystem).createFile(eq(props.getFilename()), 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) ArgumentMatchers(org.mockito.ArgumentMatchers) RunWith(org.junit.runner.RunWith) EventBusMessage(org.eclipse.hono.util.EventBusMessage) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) Context(io.vertx.core.Context) Assert.assertThat(org.junit.Assert.assertThat) EventBus(io.vertx.core.eventbus.EventBus) RegistrationResult(org.eclipse.hono.util.RegistrationResult) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) Assert.assertFalse(org.junit.Assert.assertFalse) 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)

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