io.vertx.core.streams.WriteStream Java Examples

The following examples show how to use io.vertx.core.streams.WriteStream. 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: FrameHelper.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 6 votes vote down vote up
public static void sendFrame(String type, String address, String replyAddress, JsonObject headers, Boolean send, JsonObject body, WriteStream<Buffer> handler) {
  final JsonObject payload = new JsonObject().put("type", type);

  if (address != null) {
    payload.put("address", address);
  }

  if (replyAddress != null) {
    payload.put("replyAddress", replyAddress);
  }

  if (headers != null) {
    payload.put("headers", headers);
  }

  if (body != null) {
    payload.put("body", body);
  }

  if (send != null) {
    payload.put("send", send);
  }

  writeFrame(payload, handler);
}
 
Example #2
Source File: WebClientTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testResponseBodyStreamError() throws Exception {
  CompletableFuture<Void> fail = new CompletableFuture<>();
  server.requestHandler(req -> {
    HttpServerResponse resp = req.response();
    resp.setChunked(true);
    resp.write(TestUtils.randomBuffer(2048));
    fail.thenAccept(v -> resp.close());
  });
  startServer();
  AtomicInteger received = new AtomicInteger();
  WriteStream<Buffer> stream = new WriteStreamBase() {
    @Override
    public void write(Buffer data, Handler<AsyncResult<Void>> handler) {
      received.addAndGet(data.length());
      super.write(data, handler);
    }
  };
  HttpRequest<Buffer> get = webClient.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
  get
    .as(BodyCodec.pipe(stream))
    .send(onFailure(err -> testComplete()));
  assertWaitUntil(() -> received.get() == 2048);
  fail.complete(null);
  await();
}
 
Example #3
Source File: TestReadStreamPart.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void saveToWrite_readException(@Mocked WriteStream<Buffer> writeStream)
    throws InterruptedException, ExecutionException {
  RuntimeException error = new RuntimeExceptionWithoutStackTrace();
  new MockUp<InputStream>(inputStream) {
    @Mock
    int read(byte b[]) throws IOException {
      throw error;
    }
  };

  expectedException.expect(ExecutionException.class);
  expectedException.expectCause(Matchers.sameInstance(error));

  part.saveToWriteStream(writeStream).get();
}
 
Example #4
Source File: TestReadStreamPart.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void saveToWriteStream_writeException() throws InterruptedException, ExecutionException {
  RuntimeException error = new RuntimeExceptionWithoutStackTrace();
  WriteStream<Buffer> writeStream = new MockUp<WriteStream<Buffer>>() {
    Handler<Throwable> exceptionHandler;

    @Mock
    WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
      this.exceptionHandler = handler;
      return null;
    }

    @Mock
    WriteStream<Buffer> write(Buffer data) {
      exceptionHandler.handle(error);
      return null;
    }
  }.getMockInstance();

  expectedException.expect(ExecutionException.class);
  expectedException.expectCause(Matchers.sameInstance(error));

  part.saveToWriteStream(writeStream).get();
}
 
Example #5
Source File: ClassTest.java    From vertx-codegen with Apache License 2.0 6 votes vote down vote up
@Test
public void testMethodWithTypeVarParamByGenericType() throws Exception {
  Runnable test = () -> {
    try {
      ClassModel model = new GeneratorHelper().generateClass(MethodWithTypeVarParamByGenericType.class);
      MethodInfo meth = model.getMethods().get(0);
      ParamInfo param = meth.getParam(0);
      ParameterizedTypeInfo handler = (ParameterizedTypeInfo) param.getType();
      assertEquals(Handler.class.getName(), handler.getRaw().getName());
      ParameterizedTypeInfo genericInt2 = (ParameterizedTypeInfo) handler.getArg(0);
      assertEquals(GenericInterface2.class.getName(), genericInt2.getRaw().getName());
      TypeVariableInfo k = (TypeVariableInfo) genericInt2.getArg(0);
      assertEquals("K", k.getName());
      TypeVariableInfo v = (TypeVariableInfo) genericInt2.getArg(1);
      assertEquals("V", v.getName());
    } catch (Exception e) {
      throw new AssertionError(e);
    }
  };
  blacklist(test, Stream.of(WriteStream.class));
  test.run();
}
 
Example #6
Source File: FrameHelper.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 5 votes vote down vote up
public static void sendErrFrame(String address, String replyAddress, ReplyException failure, WriteStream<Buffer> handler) {
  final JsonObject payload = new JsonObject()
      .put("type", "err")
      .put("address", replyAddress)
      .put("sourceAddress", address)
      .put("failureCode", failure.failureCode())
      .put("failureType", failure.failureType().name())
      .put("message", failure.getMessage());

  writeFrame(payload, handler);
}
 
Example #7
Source File: FileBackedBuffer.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public WriteStream<Buffer> write(Buffer data) {
    checkReadStreamNotOpen();
    size += data.length();
    BufferEndableWriteStream dst = maybeGetWriteStream();
    if (dst != null) {
        dst.write(data);
    } else {
        memory.appendBuffer(data);
        handleDrain();
    }
    return this;
}
 
Example #8
Source File: FileBackedBuffer.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
    this.exceptionHandler = handler;
    BufferEndableWriteStream dst = maybeGetWriteStream();
    if (dst != null) {
        dst.exceptionHandler(handler);
    }
    return this;
}
 
Example #9
Source File: AsyncIO.java    From sfs with Apache License 2.0 5 votes vote down vote up
public static Observable<Void> append(Buffer buffer, final WriteStream<Buffer> ws) {
    try {

        ObservableFuture<Void> drainHandler = RxHelper.observableFuture();
        ws.exceptionHandler(drainHandler::fail);
        if (ws.writeQueueFull()) {
            ws.drainHandler(drainHandler::complete);
        } else {
            drainHandler.complete(null);
        }

        return drainHandler.flatMap(aVoid -> {
            ObservableFuture<Void> writeHandler = RxHelper.observableFuture();
            ws.exceptionHandler(writeHandler::fail);
            ws.write(buffer);
            if (ws.writeQueueFull()) {
                ws.drainHandler(writeHandler::complete);
            } else {
                writeHandler.complete(null);
            }
            return writeHandler;
        });
    } catch (Throwable e) {
        return Observable.error(e);
    }

}
 
Example #10
Source File: MultipartUploadWriteStream.java    From vertx-s3-client with Apache License 2.0 5 votes vote down vote up
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
    checkArgument(maxSize >= 2, "maxSize must be bigger then 2");

    maxOutstandingBufferWrites = maxSize;
    return this;
}
 
Example #11
Source File: MultipartUploadWriteStream.java    From vertx-s3-client with Apache License 2.0 5 votes vote down vote up
@Override
public WriteStream<Buffer> write(Buffer data) {
    buffer.appendBuffer(data);
    if (buffer.length() >= bufferSize || endCalled) {
        final Integer currentPartNumber = nextPartNumber++;
        final Buffer currentBuffer = buffer;
        this.buffer = Buffer.buffer(bufferSize);
        outstandingBufferWrites++;
        s3Client.continueMultipartUpload(
                initMultipartUploadResponse.getBucket(),
                initMultipartUploadResponse.getKey(),
                new ContinueMultipartUploadRequest(currentBuffer, currentPartNumber, initMultipartUploadResponse.getUploadId()),
                response -> {
                    // Save nextPartNumber together with ETag required for the complete operation
                    partETagMap.put(currentPartNumber, response.getHeader().getETag());
                    decreaseOutstandingBufferWrites();
                    endIfAllPartsAreUploaded();
                },
                throwable -> {
                    if (abortOnFailure) {
                        if (!aborted) {
                            abort(aVoid -> exceptionHandler.handle(throwable));
                        }
                    } else {
                        exceptionHandler.handle(throwable);
                    }
                }
        );
    }
    return this;
}
 
Example #12
Source File: TestReadStreamPart.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void saveToWriteStream() throws InterruptedException, ExecutionException {
  Buffer buf = Buffer.buffer();
  WriteStream<Buffer> writeStream = new MockUp<WriteStream<Buffer>>() {
    @Mock
    WriteStream<Buffer> write(Buffer data) {
      buf.appendBuffer(data);
      return null;
    }
  }.getMockInstance();

  part.saveToWriteStream(writeStream).get();

  Assert.assertEquals(src, buf.toString());
}
 
Example #13
Source File: TestVertxServerResponseToHttpServletResponse.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void sendPart_ReadStreamPart(@Mocked ReadStreamPart part) {
  CompletableFuture<Void> future = new CompletableFuture<>();
  new MockUp<PumpFromPart>() {
    @Mock
    CompletableFuture<Void> toWriteStream(WriteStream<Buffer> writeStream, Handler<Throwable> throwableHandler) {
      return future;
    }
  };

  Assert.assertSame(future, response.sendPart(part));
}
 
Example #14
Source File: WebClientExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void receiveResponseAsWriteStream(WebClient client, WriteStream<Buffer> writeStream) {
  client
    .get(8080, "myserver.mycompany.com", "/some-uri")
    .as(BodyCodec.pipe(writeStream))
    .send()
    .onSuccess(res ->
      System.out.println("Received response with status code" + res.statusCode()))
    .onFailure(err ->
      System.out.println("Something went wrong " + err.getMessage()));
}
 
Example #15
Source File: MQTTSocket.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
protected void sendMessageToClient(Buffer bytes, WriteStream<Buffer> writer, ReadStream<Buffer> reader) {
    try {
        writer.write(bytes);
        if (writer.writeQueueFull()) {
            reader.pause();
            writer.drainHandler( done -> reader.resume() );
        }
    } catch(Throwable e) {
        logger.error(e.getMessage());
    }
}
 
Example #16
Source File: OutputStreamToWriteStream.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public WriteStream<Buffer> write(Buffer data, Handler<AsyncResult<Void>> handler) {
  currentBufferCount++;
  buffers.add(data);
  context.executeBlocking(this::writeInWorker,
      true,
      handler);
  return this;
}
 
Example #17
Source File: OutputStreamToWriteStream.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized WriteStream<Buffer> write(Buffer data) {
  return write(data, ar -> {
    if (ar.failed()) {
      handleException(ar.cause());
    }
  });
}
 
Example #18
Source File: FrameHelper.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 5 votes vote down vote up
public static void sendErrFrame(String message, WriteStream<Buffer> handler) {
  final JsonObject payload = new JsonObject()
      .put("type", "err")
      .put("message", message);

  writeFrame(payload, handler);
}
 
Example #19
Source File: SocketWrapper.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
public SocketWrapper(WriteStream<Buffer> w, ReadStream<Buffer> r) {
    if(w==null)
        throw new IllegalArgumentException("SocketWrapper: write stream cannot be null");
    if(r==null)
        throw new IllegalArgumentException("SocketWrapper: read stream cannot be null");
    this.w = w;
    this.r = r;
}
 
Example #20
Source File: BoundedWriteStream.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Override
public WriteStream<Buffer> write(Buffer data) {
  byte[] buffer = data.getBytes();
  buffers.addLast(buffer);
  size += buffer.length;
  return this;
}
 
Example #21
Source File: WriteStreamSubscriberTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyCompleteFlow() {
    TestWriteStream<String> writeStream = new TestWriteStream<>();
    TestPublisher<String> publisher = TestPublisher.create();

    Subscriber<String> subscriber = new WriteStreamSubscriber.Builder<WriteStream<String>, String>()
        .writeStream(writeStream)
        .nextHandler(WriteStream::write)
        .endHook(mockMonoSink)
        .build();

    writeStream.setWriteQueueMaxSize(2);

    publisher.subscribe(subscriber);
    publisher.assertMinRequested(1);

    publisher.next("first");
    publisher.assertMinRequested(1);

    publisher.next("second");
    publisher.assertMinRequested(0);
    assertThat(writeStream.getReceived()).containsOnly("first", "second");

    writeStream.clearReceived();
    publisher.assertMinRequested(1);

    publisher.next("third");
    assertThat(writeStream.getReceived()).containsOnly("third");

    publisher.complete();
    verify(mockMonoSink).success();
}
 
Example #22
Source File: WriteStreamSubscriberTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test(expected = NullPointerException.class)
public void shouldNotAllowNullEndHook() {
    new WriteStreamSubscriber.Builder<WriteStream<String>, String>()
        .writeStream(mockWriteStream)
        .nextHandler((stream, value) -> {})
        .build();
}
 
Example #23
Source File: WriteStreamSubscriberTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test(expected = NullPointerException.class)
public void shouldNotAllowNullNextHandler() {
    new WriteStreamSubscriber.Builder<WriteStream<String>, String>()
        .writeStream(mockWriteStream)
        .endHook(mockMonoSink)
        .build();
}
 
Example #24
Source File: WriteStreamSubscriberTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test(expected = NullPointerException.class)
public void shouldNotAllowNullWriteStream() {
    new WriteStreamSubscriber.Builder<WriteStream<String>, String>()
        .nextHandler((stream, value) -> {})
        .endHook(mockMonoSink)
        .build();
}
 
Example #25
Source File: WriteStreamSubscriberTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    subscriber = new WriteStreamSubscriber.Builder<WriteStream<String>, String>()
        .writeStream(mockWriteStream)
        .nextHandler(WriteStream::write)
        .endHook(mockMonoSink)
        .build();
}
 
Example #26
Source File: MongoGridFsClient.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
@Fluent
MongoGridFsClient downloadByFileNameWithOptions(WriteStream<Buffer> stream, String fileName, GridFsDownloadOptions options, Handler<AsyncResult<Long>> resultHandler);
 
Example #27
Source File: MongoGridFsClient.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
@Fluent
MongoGridFsClient downloadByFileName(WriteStream<Buffer> stream, String fileName, Handler<AsyncResult<Long>> resultHandler);
 
Example #28
Source File: MongoGridFsClientImpl.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
@Override
public MongoGridFsClient downloadById(WriteStream<Buffer> stream, String id, Handler<AsyncResult<Long>> resultHandler) {
  Future<Long> future = downloadById(stream, id);
  setHandler(future, resultHandler);
  return this;
}
 
Example #29
Source File: MongoGridFsClientImpl.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
@Override
public Future<Long> downloadByFileNameWithOptions(WriteStream<Buffer> stream, String fileName, GridFsDownloadOptions options) {
  GridFSDownloadOptions downloadOptions = new GridFSDownloadOptions();
  GridFSDownloadPublisher publisher = bucket.downloadToPublisher(fileName, downloadOptions);
  return handleDownload(publisher, stream);
}
 
Example #30
Source File: WriteStreamSubscriberImpl.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
public WriteStreamSubscriberImpl(WriteStream<T> writeStream, Function<R, T> mapping) {
  Objects.requireNonNull(writeStream, "writeStream");
  Objects.requireNonNull(mapping, "mapping");
  this.writeStream = writeStream;
  this.mapping = mapping;
}