Java Code Examples for io.vertx.core.file.OpenOptions

The following examples show how to use io.vertx.core.file.OpenOptions. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: vertx-spring-boot   Source File: HttpFileTransferIT.java    License: Apache License 2.0 6 votes vote down vote up
private static Flux<DataBuffer> readFile(Vertx vertx, Path path) {
    AsyncFile file = vertx.fileSystem().openBlocking(path.toString(), new OpenOptions());

    Flux<Buffer> buffers = Flux.create(sink -> {
        file.pause();
        file.endHandler(v -> sink.complete());
        file.exceptionHandler(sink::error);
        file.handler(sink::next);
        sink.onRequest(file::fetch);
    });

    DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();

    return Flux.from(buffers)
        .map(Buffer::getBytes)
        .map(dataBufferFactory::wrap);
}
 
Example 2
Source Project: vertx-in-action   Source File: Jukebox.java    License: MIT License 6 votes vote down vote up
private void download(String path, HttpServerRequest request) {
  String file = "tracks/" + path;
  if (!vertx.fileSystem().existsBlocking(file)) {
    request.response().setStatusCode(404).end();
    return;
  }
  OpenOptions opts = new OpenOptions().setRead(true);
  vertx.fileSystem().open(file, opts, ar -> {
    if (ar.succeeded()) {
      downloadFile(ar.result(), request);
    } else {
      logger.error("Read failed", ar.cause());
      request.response().setStatusCode(500).end();
    }
  });
}
 
Example 3
Source Project: vertx-in-action   Source File: VertxStreams.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {
  Vertx vertx = Vertx.vertx();
  OpenOptions opts = new OpenOptions().setRead(true);
  vertx.fileSystem().open("build.gradle.kts", opts, ar -> {
    if (ar.succeeded()) {
      AsyncFile file = ar.result();
      file.handler(System.out::println)
        .exceptionHandler(Throwable::printStackTrace)
        .endHandler(done -> {
          System.out.println("\n--- DONE");
          vertx.close();
        });
    } else {
      ar.cause().printStackTrace();
    }
  });
}
 
Example 4
Source Project: quarkus   Source File: MutinyMailerImpl.java    License: Apache License 2.0 6 votes vote down vote up
public static Uni<Buffer> getAttachmentStream(Vertx vertx, Attachment attachment) {
    if (attachment.getFile() != null) {
        Uni<AsyncFile> open = vertx.fileSystem().open(attachment.getFile().getAbsolutePath(),
                new OpenOptions().setRead(true).setCreate(false));
        return open
                .flatMap(af -> af.toMulti()
                        .map(io.vertx.mutiny.core.buffer.Buffer::getDelegate)
                        .on().termination((r, f) -> af.close())
                        .collectItems().in(Buffer::buffer, Buffer::appendBuffer));
    } else if (attachment.getData() != null) {
        Publisher<Byte> data = attachment.getData();
        return Multi.createFrom().publisher(data)
                .collectItems().in(Buffer::buffer, Buffer::appendByte);
    } else {
        return Uni.createFrom().failure(new IllegalArgumentException("Attachment has no data"));
    }
}
 
Example 5
Source Project: quarkus   Source File: AttachmentTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testAttachmentCreationFromStream() {
    Publisher<Byte> publisher = vertx.fileSystem().open(LOREM.getAbsolutePath(), new OpenOptions().setRead(true))
            .onItem().produceMulti(af -> af.toMulti()
                    .onItem().produceIterable(this::getBytes).concatenate());

    Attachment attachment = new Attachment("lorem.txt", publisher, "text/plain");
    assertThat(attachment.getFile()).isNull();
    assertThat(attachment.getName()).isEqualTo("lorem.txt");
    assertThat(attachment.getDisposition()).isEqualTo(Attachment.DISPOSITION_ATTACHMENT);
    assertThat(attachment.getContentId()).isNull();
    assertThat(attachment.getDescription()).isNull();
    assertThat(attachment.getContentType()).isEqualTo("text/plain");
    assertThat(attachment.getData()).isNotNull().isEqualTo(publisher);

    String content = getContent(attachment);
    assertThat(content).startsWith(BEGINNING);
}
 
Example 6
Source Project: quarkus   Source File: AttachmentTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testInlineAttachmentCreationFromStream() {
    Publisher<Byte> publisher = vertx.fileSystem().open(LOREM.getAbsolutePath(), new OpenOptions().setRead(true))
            .onItem().produceMulti(af -> af.toMulti()
                    .onItem().produceIterable(this::getBytes).concatenate());

    Attachment attachment = new Attachment("lorem.txt", publisher, "text/plain", "<my-id>");
    assertThat(attachment.getFile()).isNull();
    assertThat(attachment.getName()).isEqualTo("lorem.txt");
    assertThat(attachment.getDisposition()).isEqualTo(Attachment.DISPOSITION_INLINE);
    assertThat(attachment.getContentId()).isEqualTo("<my-id>");
    assertThat(attachment.getDescription()).isNull();
    assertThat(attachment.getContentType()).isEqualTo("text/plain");
    assertThat(attachment.getData()).isNotNull().isEqualTo(publisher);

    String content = getContent(attachment);
    assertThat(content).startsWith(BEGINNING);
}
 
Example 7
Source Project: quarkus   Source File: AttachmentTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testAttachmentCreationWithDescription() {
    Publisher<Byte> publisher = vertx.fileSystem().open(LOREM.getAbsolutePath(), new OpenOptions().setRead(true))
            .onItem().produceMulti(af -> af.toMulti()
                    .onItem().produceIterable(this::getBytes).concatenate());

    Attachment attachment = new Attachment("lorem.txt", publisher, "text/plain",
            DESCRIPTION, Attachment.DISPOSITION_ATTACHMENT);
    assertThat(attachment.getFile()).isNull();
    assertThat(attachment.getName()).isEqualTo("lorem.txt");
    assertThat(attachment.getDisposition()).isEqualTo(Attachment.DISPOSITION_ATTACHMENT);
    assertThat(attachment.getContentId()).isNull();
    assertThat(attachment.getDescription()).isEqualTo(DESCRIPTION);
    assertThat(attachment.getContentType()).isEqualTo("text/plain");
    assertThat(attachment.getData()).isNotNull().isEqualTo(publisher);

    String content = getContent(attachment);
    assertThat(content).startsWith(BEGINNING);
}
 
Example 8
Source Project: quarkus   Source File: AttachmentTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testInlineAttachmentCreationWithDescription() {
    Publisher<Byte> publisher = vertx.fileSystem().open(LOREM.getAbsolutePath(), new OpenOptions().setRead(true))
            .onItem().produceMulti(af -> af.toMulti()
                    .onItem().produceIterable(this::getBytes).concatenate());

    Attachment attachment = new Attachment("lorem.txt", publisher, "text/plain",
            DESCRIPTION, Attachment.DISPOSITION_INLINE);
    assertThat(attachment.getFile()).isNull();
    assertThat(attachment.getName()).isEqualTo("lorem.txt");
    assertThat(attachment.getDisposition()).isEqualTo(Attachment.DISPOSITION_INLINE);
    assertThat(attachment.getContentId()).isNull();
    assertThat(attachment.getDescription()).isEqualTo(DESCRIPTION);
    assertThat(attachment.getContentType()).isEqualTo("text/plain");
    assertThat(attachment.getData()).isNotNull().isEqualTo(publisher);

    String content = getContent(attachment);
    assertThat(content).startsWith(BEGINNING);
}
 
Example 9
Source Project: sfs   Source File: AsyncIOTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void copyZeroLength(TestContext context) throws IOException {
    runOnServerContext(context, () -> {
        Path tmpFile = Files.createTempFile(tmpDir(), "", "");

        AsyncFile asyncFile = vertx().fileSystem().openBlocking(tmpFile.toString(), new OpenOptions());
        final BufferWriteEndableWriteStream bufferWriteStream = new BufferWriteEndableWriteStream();

        return AsyncIO.pump(EndableReadStream.from(asyncFile), bufferWriteStream)
                .map(new Func1<Void, Void>() {
                    @Override
                    public Void call(Void aVoid) {
                        VertxAssert.assertEquals(context, 0, bufferWriteStream.toBuffer().length());
                        return null;
                    }
                });
    });
}
 
Example 10
Source Project: vertx-mail-client   Source File: AttachmentPart.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized Future<Void> cacheBuffer(Buffer buffer) {
  caching = true;
  Promise<Void> promise = Promise.promise();
  if (cacheInMemory) {
    cachedBuffer.appendBuffer(buffer);
    promise.complete();
  } else {
    if (cachedFile == null) {
      context.owner().fileSystem().open(cachedFilePath, new OpenOptions().setAppend(true))
        .onComplete(c -> context.runOnContext(h -> {
          if (c.succeeded()) {
            synchronized (BodyReadStream.this) {
              cachedFile = c.result();
              cachedFile.write(buffer, promise);
            }
          } else {
            promise.fail(c.cause());
          }
        }));
    } else {
      cachedFile.write(buffer, promise);
    }
  }
  return promise.future();
}
 
Example 11
@Test
public void mailWithOneAttachmentStream(TestContext testContext) {
  this.testContext = testContext;
  String text = "This is a message with an attachment and with stream specified";
  MailMessage message = exampleMessage().setText(text);
  String path = "log4j.properties";
  Buffer buffer = vertx.fileSystem().readFileBlocking(path);
  MailAttachment attachment = MailAttachment.create()
    .setContentType("text/plain")
    .setName("file")
    .setSize(buffer.length())
    .setStream(vertx.fileSystem().openBlocking(path, new OpenOptions()));
  message.setAttachment(attachment);
  testSuccess(mailClientLogin(), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(text, TestUtils.conv2nl(TestUtils.inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(buffer.getBytes(), TestUtils.inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
  });
}
 
Example 12
private List<MailAttachment> mailAttachments(String deposition, Buffer logoBuffer) {
  List<MailAttachment> list = new ArrayList<>();
  String imgPath = "logo-white-big.png";
  list.add(MailAttachment.create()
    .setStream(vertx.fileSystem().openBlocking(imgPath, new OpenOptions()))
    .setSize(logoBuffer.length())
    .setName(imgPath)
    .setContentType("image/png")
    .setContentId("<[email protected]>")
    .setDisposition(deposition)
    .setDescription("logo of vert.x web page"));

  String path = "log4j.properties";
  list.add(MailAttachment.create()
    .setStream(vertx.fileSystem().openBlocking(path, new OpenOptions()))
    .setName(path)
    .setContentType("text/plain")
    .setDisposition(deposition)
    .setDescription("This is a log4j properties file")
  );
  return list;
}
 
Example 13
Source Project: vertx-mail-client   Source File: MailWithDKIMSignTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMailSimpleSimpleAttachmentStream(TestContext testContext) {
  System.setProperty("vertx.mail.attachment.cache.file", "true");
  this.testContext = testContext;
  String path = "logo-white-big.png";
  Buffer img = vertx.fileSystem().readFileBlocking(path);
  ReadStream<Buffer> stream = vertx.fileSystem().openBlocking(path, new OpenOptions());
  MailAttachment attachment = MailAttachment.create().setName(path).setStream(stream).setSize(img.length());
  MailMessage message = exampleMessage().setText(TEXT_BODY).setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.SIMPLE).setBodyCanonAlgo(CanonicalizationAlgorithm.SIMPLE);
  testSuccess(dkimMailClient(dkimOps), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
    testDKIMSign(dkimOps, testContext);
  });
}
 
Example 14
Source Project: vertx-mail-client   Source File: MailWithDKIMSignTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMailSimpleRelaxedAttachmentStream(TestContext testContext) {
  System.setProperty("vertx.mail.attachment.cache.file", "false");
  this.testContext = testContext;
  String path = "logo-white-big.png";
  Buffer img = vertx.fileSystem().readFileBlocking(path);
  ReadStream<Buffer> stream = vertx.fileSystem().openBlocking(path, new OpenOptions());
  MailAttachment attachment = MailAttachment.create().setName("logo-white-big.png").setStream(stream).setSize(img.length());
  MailMessage message = exampleMessage().setText(TEXT_BODY).setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.SIMPLE).setBodyCanonAlgo(CanonicalizationAlgorithm.RELAXED);
  testSuccess(dkimMailClient(dkimOps), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
    testDKIMSign(dkimOps, testContext);
  });
}
 
Example 15
Source Project: vertx-mail-client   Source File: MailWithDKIMSignTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMailRelaxedSimpleAttachmentStream(TestContext testContext) {
  System.setProperty("vertx.mail.attachment.cache.file", "true");
  this.testContext = testContext;
  String path = "logo-white-big.png";
  Buffer img = vertx.fileSystem().readFileBlocking(path);
  ReadStream<Buffer> stream = vertx.fileSystem().openBlocking(path, new OpenOptions());
  MailAttachment attachment = MailAttachment.create().setName("logo-white-big.png").setStream(stream).setSize(img.length());
  MailMessage message = exampleMessage().setText(TEXT_BODY).setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.RELAXED).setBodyCanonAlgo(CanonicalizationAlgorithm.SIMPLE);
  testSuccess(dkimMailClient(dkimOps), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
    testDKIMSign(dkimOps, testContext);
  });
}
 
Example 16
Source Project: vertx-mail-client   Source File: MailWithDKIMSignTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMailRelaxedRelaxedAttachmentStream(TestContext testContext) {
  System.setProperty("vertx.mail.attachment.cache.file", "false");
  this.testContext = testContext;
  String path = "logo-white-big.png";
  Buffer img = vertx.fileSystem().readFileBlocking(path);
  ReadStream<Buffer> stream = vertx.fileSystem().openBlocking(path, new OpenOptions());
  MailAttachment attachment = MailAttachment.create().setName("logo-white-big.png").setStream(stream).setSize(img.length());
  MailMessage message = exampleMessage().setText(TEXT_BODY).setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.RELAXED).setBodyCanonAlgo(CanonicalizationAlgorithm.RELAXED);
  testSuccess(dkimMailClient(dkimOps), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
    testDKIMSign(dkimOps, testContext);
  });
}
 
Example 17
Source Project: vertx-mail-client   Source File: MailWithDKIMSignTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMailRelaxedRelaxedAttachmentStreamWithLimit(TestContext testContext) {
  System.setProperty("vertx.mail.attachment.cache.file", "true");
  this.testContext = testContext;
  String path = "logo-white-big.png";
  Buffer img = vertx.fileSystem().readFileBlocking(path);
  ReadStream<Buffer> stream = vertx.fileSystem().openBlocking(path, new OpenOptions());
  MailAttachment attachment = MailAttachment.create().setName("logo-white-big.png").setStream(stream).setSize(img.length());
  MailMessage message = exampleMessage().setText(TEXT_BODY).setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase).setBodyLimit(100)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.RELAXED).setBodyCanonAlgo(CanonicalizationAlgorithm.RELAXED);
  testSuccess(dkimMailClient(dkimOps), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
    testDKIMSign(dkimOps, testContext);
  });
}
 
Example 18
Source Project: vertx-mail-client   Source File: MailWithDKIMSignTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMailRelaxedSimpleAttachmentStreamWithLimit(TestContext testContext) {
  System.setProperty("vertx.mail.attachment.cache.file", "false");
  this.testContext = testContext;
  String path = "logo-white-big.png";
  Buffer img = vertx.fileSystem().readFileBlocking(path);
  ReadStream<Buffer> stream = vertx.fileSystem().openBlocking(path, new OpenOptions());
  MailAttachment attachment = MailAttachment.create().setName("logo-white-big.png").setStream(stream).setSize(img.length());
  MailMessage message = exampleMessage().setText(TEXT_BODY).setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase).setBodyLimit(50)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.RELAXED).setBodyCanonAlgo(CanonicalizationAlgorithm.SIMPLE);
  testSuccess(dkimMailClient(dkimOps), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
    testDKIMSign(dkimOps, testContext);
  });
}
 
Example 19
Source Project: vertx-mongo-client   Source File: MongoGridFsClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Future<String> uploadFileWithOptions(String fileName, GridFsUploadOptions options) {
  requireNonNull(fileName, "fileName cannot be null");

  OpenOptions openOptions = new OpenOptions().setRead(true);

  return vertx.fileSystem().open(fileName, openOptions)
    .flatMap(file -> {
      GridFSReadStreamPublisher publisher = new GridFSReadStreamPublisher(file);
      Promise<ObjectId> promise = vertx.promise();
      if (options == null) {
        bucket.uploadFromPublisher(fileName, publisher).subscribe(new SingleResultSubscriber<>(promise));
      } else {
        GridFSUploadOptions uploadOptions = new GridFSUploadOptions();
        uploadOptions.chunkSizeBytes(options.getChunkSizeBytes());
        if (options.getMetadata() != null) {
          uploadOptions.metadata(new Document(options.getMetadata().getMap()));
        }
        bucket.uploadFromPublisher(fileName, publisher, uploadOptions).subscribe(new SingleResultSubscriber<>(promise));
      }
      return promise.future().map(ObjectId::toHexString);
    });
}
 
Example 20
Source Project: vertx-web   Source File: WebClientExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void sendStream(WebClient client, FileSystem fs) {
  fs.open("content.txt", new OpenOptions(), fileRes -> {
    if (fileRes.succeeded()) {
      ReadStream<Buffer> fileStream = fileRes.result();

      String fileLen = "1024";

      // Send the file to the server using POST
      client
        .post(8080, "myserver.mycompany.com", "/some-uri")
        .putHeader("content-length", fileLen)
        .sendStream(fileStream)
        .onSuccess(res -> {
          // OK
        })
      ;
    }
  });
}
 
Example 21
Source Project: vertx-web   Source File: InterceptorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMutateCodecInterceptor() throws Exception {
  server.requestHandler(req -> req.response().end("foo!"));
  startServer();
  File f = Files.createTempFile("vertx", ".dat").toFile();
  assertTrue(f.delete());
  AsyncFile foo = vertx.fileSystem().openBlocking(f.getAbsolutePath(), new OpenOptions().setSync(true).setTruncateExisting(true));
  client.addInterceptor(this::handleMutateCodec);
  HttpRequest<Void> builder = client.get("/somepath").as(BodyCodec.pipe(foo));
  builder.send(onSuccess(resp -> {
    foo.write(Buffer.buffer("bar!"));
    foo.close(onSuccess(v -> {
      assertEquals("bar!", vertx.fileSystem().readFileBlocking(f.getAbsolutePath()).toString());
      testComplete();
    }));
  }));
  await();
  if (f.exists()) {
    f.delete();
  }
}
 
Example 22
Source Project: vertx-spring-boot   Source File: MailAttachmentConverter.java    License: Apache License 2.0 5 votes vote down vote up
private Mono<Buffer> fileAttachmentToBuffer(File file) {
    CompletionStage<AsyncFile> fileFuture = vertx.fileSystem()
        .open(file.getAbsolutePath(), new OpenOptions().setRead(true).setCreate(false));

    CompletionStage<Buffer> bufferFuture = ReactiveStreams.fromCompletionStage(fileFuture)
        .flatMap(asyncFile -> asyncFile
            .toPublisherBuilder()
            .map(io.vertx.axle.core.buffer.Buffer::getDelegate)
            .onTerminate(asyncFile::close))
        .collect(Buffer::buffer, Buffer::appendBuffer)
        .run();

    return Mono.fromCompletionStage(bufferFuture);
}
 
Example 23
Source Project: vertx-in-action   Source File: DatabaseReader.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
  Vertx vertx = Vertx.vertx();

  AsyncFile file = vertx.fileSystem().openBlocking("sample.db",
    new OpenOptions().setRead(true));

  RecordParser parser = RecordParser.newFixed(4, file);
  parser.handler(header -> readMagicNumber(header, parser));
  parser.endHandler(v -> vertx.close());
}
 
Example 24
Source Project: vertx-in-action   Source File: FetchDatabaseReader.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
  Vertx vertx = Vertx.vertx();

  AsyncFile file = vertx.fileSystem().openBlocking("sample.db",
    new OpenOptions().setRead(true));

  RecordParser parser = RecordParser.newFixed(4, file);
  parser.pause();
  parser.fetch(1);
  parser.handler(header -> readMagicNumber(header, parser));
  parser.endHandler(v -> vertx.close());
}
 
Example 25
Source Project: vertx-in-action   Source File: SampleDatabaseWriter.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
  Vertx vertx = Vertx.vertx();
  AsyncFile file = vertx.fileSystem().openBlocking("sample.db",
    new OpenOptions().setWrite(true).setCreate(true));

  Buffer buffer = Buffer.buffer();

  // Magic number
  buffer.appendBytes(new byte[] { 1, 2, 3, 4});

  // Version
  buffer.appendInt(2);

  // DB name
  buffer.appendString("Sample database\n");

  // Entry 1
  String key = "abc";
  String value = "123456-abcdef";
  buffer
    .appendInt(key.length())
    .appendString(key)
    .appendInt(value.length())
    .appendString(value);

  // Entry 2
  key = "[email protected]";
  value = "Foo Bar Baz";
  buffer
    .appendInt(key.length())
    .appendString(key)
    .appendInt(value.length())
    .appendString(value);

  file.end(buffer, ar -> vertx.close());
}
 
Example 26
Source Project: vertx-in-action   Source File: Jukebox.java    License: MIT License 5 votes vote down vote up
private void openNextFile() {
  logger.info("Opening {}", playlist.peek());
  OpenOptions opts = new OpenOptions().setRead(true);
  currentFile = vertx.fileSystem()
    .openBlocking("tracks/" + playlist.poll(), opts);
  positionInFile = 0;
}
 
Example 27
Source Project: servicecomb-java-chassis   Source File: ReadStreamPart.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param fileName
 * @return future of save to file, future complete means write to file finished
 */
public CompletableFuture<File> saveToFile(String fileName) {
  File file = new File(fileName);
  file.getParentFile().mkdirs();
  OpenOptions openOptions = new OpenOptions().setCreateNew(true);
  return saveToFile(file, openOptions);
}
 
Example 28
Source Project: servicecomb-java-chassis   Source File: ReadStreamPart.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param file
 * @param openOptions
 * @return future of save to file, future complete means write to file finished
 */
public CompletableFuture<File> saveToFile(File file, OpenOptions openOptions) {
  CompletableFuture<File> future = new CompletableFuture<>();

  context.runOnContext((v) -> {
    Vertx vertx = context.owner();
    vertx.fileSystem().open(file.getAbsolutePath(), openOptions, ar -> {
      onFileOpened(file, ar, future);
    });
  });

  return future;
}
 
Example 29
@Test
public void saveToFile_notExist_notCreate() throws InterruptedException, ExecutionException, IOException {
  File dir = new File("target/notExist-" + UUID.randomUUID().toString());
  File file = new File(dir, "a.txt");

  Assert.assertFalse(dir.exists());

  expectedException.expect(ExecutionException.class);
  expectedException.expectCause(Matchers.instanceOf(FileSystemException.class));

  OpenOptions openOptions = new OpenOptions().setCreateNew(false);
  part.saveToFile(file, openOptions).get();
}
 
Example 30
Source Project: sfs   Source File: JournalFileTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMetadataAndReadStream(TestContext context) throws IOException {

    byte[] data = new byte[256 * 1024 * 1024];
    getCurrentInstance().nextBytesBlocking(data);

    Path dataFile = path.resolve(".data");
    write(dataFile, data, CREATE_NEW);

    long size = size(dataFile);
    final byte[] expectedDataSha512 = hash(dataFile.toFile(), sha512()).asBytes();
    final AsyncFile bigFile = sfsVertx.fileSystem().openBlocking(dataFile.toString(), new OpenOptions());

    Path journalPath = path.resolve(".journal");
    JournalFile journalFile = new JournalFile(journalPath);

    Async async = context.async();

    aVoid()
            .flatMap(aVoid -> journalFile.open(sfsVertx))
            .flatMap(aVoid -> journalFile.enableWrites(sfsVertx))
            .flatMap(aVoid -> journalFile.append(sfsVertx, buffer("metadata0", UTF_8.toString()), size, EndableReadStream.from(bigFile)))
            .doOnNext(aVoid -> bigFile.setReadPos(0))
            .flatMap(aVoid -> journalFile.append(sfsVertx, buffer("metadata1", UTF_8.toString()), size, EndableReadStream.from(bigFile)))
            .doOnNext(aVoid -> bigFile.setReadPos(0))
            .flatMap(aVoid -> journalFile.append(sfsVertx, buffer("metadata2", UTF_8.toString()), size, EndableReadStream.from(bigFile)))
            .doOnNext(aVoid -> bigFile.setReadPos(0))
            .flatMap(aVoid -> journalFile.append(sfsVertx, buffer("metadata3", UTF_8.toString()), size, EndableReadStream.from(bigFile)))
            .doOnNext(aVoid -> bigFile.setReadPos(0))
            .flatMap(aVoid -> journalFile.append(sfsVertx, buffer("metadata4", UTF_8.toString()), size, EndableReadStream.from(bigFile)))
            // assert stuff before closing
            .flatMap(aVoid -> assertScanDataReadStream(context, sfsVertx, journalFile, 5, "metadata", expectedDataSha512))
            .flatMap(aVoid -> journalFile.disableWrites(sfsVertx))
            .flatMap(aVoid -> journalFile.force(sfsVertx, true))
            .flatMap(aVoid -> journalFile.close(sfsVertx))
            // assert stuff can be read closing and opening
            .flatMap(aVoid -> journalFile.open(sfsVertx))
            .flatMap(aVoid -> assertScanDataReadStream(context, sfsVertx, journalFile, 5, "metadata", expectedDataSha512))
            .subscribe(new TestSubscriber(context, async));
}