io.vertx.core.file.OpenOptions Java Examples

The following examples show how to use io.vertx.core.file.OpenOptions. 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 File: MailAttachmentStreamTest.java    From vertx-mail-client with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: InterceptorTest.java    From vertx-web with 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 #3
Source File: WebClientExamples.java    From vertx-web with 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 #4
Source File: MongoGridFsClientImpl.java    From vertx-mongo-client with 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 #5
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with 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 #6
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with 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 #7
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with 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 #8
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with 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 #9
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with 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 #10
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with 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 #11
Source File: MailAttachmentStreamTest.java    From vertx-mail-client with Apache License 2.0 6 votes vote down vote up
@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
Source File: AttachmentPart.java    From vertx-mail-client with 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 #13
Source File: AsyncIOTest.java    From sfs with 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 #14
Source File: HttpFileTransferIT.java    From vertx-spring-boot with 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 #15
Source File: AttachmentTest.java    From quarkus with 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 #16
Source File: Jukebox.java    From vertx-in-action with 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 #17
Source File: VertxStreams.java    From vertx-in-action with 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 #18
Source File: MutinyMailerImpl.java    From quarkus with 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 #19
Source File: AttachmentTest.java    From quarkus with 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 #20
Source File: AttachmentTest.java    From quarkus with 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 #21
Source File: AttachmentTest.java    From quarkus with 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 #22
Source File: CoreTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncFile() throws Exception {
  String fileName = "some-file.dat";
  int chunkSize = 1000;
  int chunks = 10;
  byte[] expected = TestUtils.randomAlphaString(chunkSize * chunks).getBytes();
  createFile(fileName, expected);
  vertx.fileSystem().open(testDir + pathSep + fileName, new OpenOptions(), onSuccess(file -> subscribe(expected, file, 3)));
  await();
}
 
Example #23
Source File: FetchDatabaseReader.java    From vertx-in-action with 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 #24
Source File: RxifiedExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void unmarshaller(FileSystem fileSystem) {
  fileSystem.open("/data.txt", new OpenOptions(), result -> {
    AsyncFile file = result.result();
    Observable<Buffer> observable = file.toObservable();
    observable.compose(ObservableHelper.unmarshaller((MyPojo.class))).subscribe(
      mypojo -> {
        // Process the object
      }
    );
  });
}
 
Example #25
Source File: MongoGridFsClientImpl.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Long> downloadFileAs(String fileName, String newFileName) {
  requireNonNull(fileName, "fileName cannot be null");
  requireNonNull(newFileName, "newFileName cannot be null");

  OpenOptions options = new OpenOptions().setWrite(true);

  return vertx.fileSystem().open(newFileName, options)
    .flatMap(file -> {
      GridFSDownloadPublisher publisher = bucket.downloadToPublisher(fileName);
      return handleDownload(publisher, file);
    });
}
 
Example #26
Source File: MongoGridFsClientImpl.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Long> downloadFileByID(String id, String fileName) {
  requireNonNull(fileName, "fileName cannot be null");

  OpenOptions options = new OpenOptions().setWrite(true);

  return vertx.fileSystem().open(fileName, options)
    .flatMap(file -> {
      ObjectId objectId = new ObjectId(id);
      GridFSDownloadPublisher publisher = bucket.downloadToPublisher(objectId);
      return handleDownload(publisher, file);
    });
}
 
Example #27
Source File: RxifiedExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void toFlowable(Vertx vertx) {
  FileSystem fs = vertx.fileSystem();
  fs.open("/data.txt", new OpenOptions(), result -> {
    AsyncFile file = result.result();
    Flowable<Buffer> observable = file.toFlowable();
    observable.forEach(data -> System.out.println("Read data: " + data.toString("UTF-8")));
  });
}
 
Example #28
Source File: NativeExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void unmarshaller(FileSystem fileSystem) {
  fileSystem.open("/data.txt", new OpenOptions(), result -> {
    AsyncFile file = result.result();
    Flowable<Buffer> observable = FlowableHelper.toFlowable(file);
    observable.compose(FlowableHelper.unmarshaller(MyPojo.class)).subscribe(
        mypojo -> {
          // Process the object
        }
    );
  });
}
 
Example #29
Source File: NativeExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void toFlowable(Vertx vertx) {
  FileSystem fileSystem = vertx.fileSystem();
  fileSystem.open("/data.txt", new OpenOptions(), result -> {
    AsyncFile file = result.result();
    Flowable<Buffer> observable = FlowableHelper.toFlowable(file);
    observable.forEach(data -> System.out.println("Read data: " + data.toString("UTF-8")));
  });
}
 
Example #30
Source File: GridFsTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamUpload() {
  String fileName = createTempFileWithContent(1024);

  AtomicReference<MongoGridFsClient> gridFsClient = new AtomicReference<>();

  Promise<MongoGridFsClient> gridFsClientPromise = Promise.promise();

  mongoClient.createGridFsBucketService("fs", gridFsClientPromise);

  gridFsClientPromise.future().compose(mongoGridFsClient -> {
    assertNotNull(mongoGridFsClient);
    gridFsClient.set(mongoGridFsClient);
    Promise<Void> dropPromise = Promise.promise();
    mongoGridFsClient.drop(dropPromise);
    return dropPromise.future();
  }).compose(dropped -> {
    Promise<AsyncFile> openPromise = Promise.promise();
    vertx.fileSystem().open(fileName, new OpenOptions(), openPromise);
    return openPromise.future();
  }).compose(asyncFile -> {
    Promise<String> uploadedPromise = Promise.promise();
    gridFsClient.get().uploadByFileName(asyncFile, fileName, uploadedPromise);
    return uploadedPromise.future();
  }).compose(id -> {
    assertNotNull(id);
    testComplete();
    return Future.succeededFuture();
  }).onComplete(event -> {
    if (event.failed()) {
      fail(event.cause());
    }
  });
  await();

}