Search in sources :

Example 26 with FileSystem

use of io.vertx.core.file.FileSystem in project hono by eclipse.

the class FileBasedRegistrationServiceTest method setUp.

/**
 * Sets up the fixture.
 */
@Before
public void setUp() {
    fileSystem = mock(FileSystem.class);
    Context ctx = mock(Context.class);
    eventBus = mock(EventBus.class);
    vertx = mock(Vertx.class);
    when(vertx.eventBus()).thenReturn(eventBus);
    when(vertx.fileSystem()).thenReturn(fileSystem);
    props = new FileBasedRegistrationConfigProperties();
    props.setFilename(FILE_NAME);
    registrationService = new FileBasedRegistrationService();
    registrationService.setConfig(props);
    registrationService.init(vertx, ctx);
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Context(io.vertx.core.Context) FileSystem(io.vertx.core.file.FileSystem) EventBus(io.vertx.core.eventbus.EventBus) Vertx(io.vertx.core.Vertx) Before(org.junit.Before)

Example 27 with FileSystem

use of io.vertx.core.file.FileSystem in project hono by eclipse.

the class FileBasedRegistrationServiceTest method testDoStartFailsIfFileCannotBeCreated.

/**
 * Verifies that the registration service fails to start if it cannot create the file for
 * persisting device registration data during startup.
 *
 * @param ctx The vert.x context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testDoStartFailsIfFileCannotBeCreated(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);
    // WHEN starting the service but the file cannot be created
    doAnswer(invocation -> {
        Handler handler = invocation.getArgument(1);
        handler.handle(Future.failedFuture("no access"));
        return null;
    }).when(fileSystem).createFile(eq(props.getFilename()), any(Handler.class));
    Async startup = ctx.async();
    Future<Void> startupTracker = Future.future();
    startupTracker.setHandler(ctx.asyncAssertFailure(started -> {
        startup.complete();
    }));
    registrationService.doStart(startupTracker);
    // THEN startup has failed
    startup.await();
}
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)

Example 28 with FileSystem

use of io.vertx.core.file.FileSystem in project hono by eclipse.

the class FileBasedRegistrationServiceTest method testSaveToFileCreatesFile.

/**
 * Verifies that the registration service creates a file for persisting device registration
 * data if it does not exist yet.
 *
 * @param ctx The vert.x context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testSaveToFileCreatesFile(final TestContext ctx) {
    // GIVEN a registration service configured with a non-existing file
    props.setSaveToFile(true);
    doAnswer(invocation -> {
        Handler handler = invocation.getArgument(2);
        handler.handle(Future.succeededFuture());
        return null;
    }).when(fileSystem).writeFile(eq(props.getFilename()), any(Buffer.class), any(Handler.class));
    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));
    // WHEN persisting a dirty registry
    registrationService.addDevice(TENANT, DEVICE, null);
    Async saving = ctx.async();
    registrationService.saveToFile().setHandler(ctx.asyncAssertSuccess(s -> {
        saving.complete();
    }));
    // THEN the file has been created
    saving.await();
    verify(fileSystem).createFile(eq(props.getFilename()), any(Handler.class));
}
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 29 with FileSystem

use of io.vertx.core.file.FileSystem in project hono by eclipse.

the class FileBasedTenantServiceTest method setUp.

/**
 * Sets up fixture.
 */
@Before
public void setUp() {
    fileSystem = mock(FileSystem.class);
    Context ctx = mock(Context.class);
    eventBus = mock(EventBus.class);
    vertx = mock(Vertx.class);
    when(vertx.eventBus()).thenReturn(eventBus);
    when(vertx.fileSystem()).thenReturn(fileSystem);
    props = new FileBasedTenantsConfigProperties();
    svc = new FileBasedTenantService();
    svc.setConfig(props);
    svc.init(vertx, ctx);
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Context(io.vertx.core.Context) FileSystem(io.vertx.core.file.FileSystem) EventBus(io.vertx.core.eventbus.EventBus) Vertx(io.vertx.core.Vertx) Before(org.junit.Before)

Example 30 with FileSystem

use of io.vertx.core.file.FileSystem in project vertx-web by vert-x3.

the class StaticHandlerImpl method sendDirectoryListing.

private void sendDirectoryListing(String dir, RoutingContext context) {
    FileSystem fileSystem = context.vertx().fileSystem();
    HttpServerRequest request = context.request();
    fileSystem.readDir(dir, asyncResult -> {
        if (asyncResult.failed()) {
            context.fail(asyncResult.cause());
        } else {
            String accept = request.headers().get("accept");
            if (accept == null) {
                accept = "text/plain";
            }
            if (accept.contains("html")) {
                String normalizedDir = context.normalisedPath();
                if (!normalizedDir.endsWith("/")) {
                    normalizedDir += "/";
                }
                String file;
                StringBuilder files = new StringBuilder("<ul id=\"files\">");
                List<String> list = asyncResult.result();
                Collections.sort(list);
                for (String s : list) {
                    file = s.substring(s.lastIndexOf(File.separatorChar) + 1);
                    // skip dot files
                    if (!includeHidden && file.charAt(0) == '.') {
                        continue;
                    }
                    files.append("<li><a href=\"");
                    files.append(normalizedDir);
                    files.append(file);
                    files.append("\" title=\"");
                    files.append(file);
                    files.append("\">");
                    files.append(file);
                    files.append("</a></li>");
                }
                files.append("</ul>");
                // link to parent dir
                int slashPos = 0;
                for (int i = normalizedDir.length() - 2; i > 0; i--) {
                    if (normalizedDir.charAt(i) == '/') {
                        slashPos = i;
                        break;
                    }
                }
                String parent = "<a href=\"" + normalizedDir.substring(0, slashPos + 1) + "\">..</a>";
                request.response().putHeader("content-type", "text/html");
                request.response().end(directoryTemplate(context.vertx()).replace("{directory}", normalizedDir).replace("{parent}", parent).replace("{files}", files.toString()));
            } else if (accept.contains("json")) {
                String file;
                JsonArray json = new JsonArray();
                for (String s : asyncResult.result()) {
                    file = s.substring(s.lastIndexOf(File.separatorChar) + 1);
                    // skip dot files
                    if (!includeHidden && file.charAt(0) == '.') {
                        continue;
                    }
                    json.add(file);
                }
                request.response().putHeader("content-type", "application/json");
                request.response().end(json.encode());
            } else {
                String file;
                StringBuilder buffer = new StringBuilder();
                for (String s : asyncResult.result()) {
                    file = s.substring(s.lastIndexOf(File.separatorChar) + 1);
                    // skip dot files
                    if (!includeHidden && file.charAt(0) == '.') {
                        continue;
                    }
                    buffer.append(file);
                    buffer.append('\n');
                }
                request.response().putHeader("content-type", "text/plain");
                request.response().end(buffer.toString());
            }
        }
    });
}
Also used : JsonArray(io.vertx.core.json.JsonArray) FileSystem(io.vertx.core.file.FileSystem) HttpServerRequest(io.vertx.core.http.HttpServerRequest)

Aggregations

FileSystem (io.vertx.core.file.FileSystem)44 Buffer (io.vertx.core.buffer.Buffer)22 Vertx (io.vertx.core.Vertx)21 JsonObject (io.vertx.core.json.JsonObject)21 Future (io.vertx.core.Future)19 Handler (io.vertx.core.Handler)19 Context (io.vertx.core.Context)18 EventBus (io.vertx.core.eventbus.EventBus)18 TestContext (io.vertx.ext.unit.TestContext)18 Before (org.junit.Before)18 Test (org.junit.Test)17 Async (io.vertx.ext.unit.Async)16 StandardCharsets (java.nio.charset.StandardCharsets)16 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)15 HttpURLConnection (java.net.HttpURLConnection)15 Constants (org.eclipse.hono.util.Constants)15 CoreMatchers.is (org.hamcrest.CoreMatchers.is)15 Assert.assertThat (org.junit.Assert.assertThat)15 RunWith (org.junit.runner.RunWith)15 Mockito (org.mockito.Mockito)15