Java Code Examples for io.vertx.core.buffer.Buffer#buffer()
The following examples show how to use
io.vertx.core.buffer.Buffer#buffer() .
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: VertxClientHttpRequestTest.java From vertx-spring-boot with Apache License 2.0 | 6 votes |
@Test public void shouldWriteFromPublisherAndFlush() { Buffer firstChunk = Buffer.buffer("chunk 1"); Buffer secondChunk = Buffer.buffer("chunk 2"); TestPublisher<DataBuffer> source = TestPublisher.create(); Mono<Void> result = request.writeAndFlushWith(Flux.just(source)); StepVerifier.create(result) .expectSubscription() .then(() -> source.assertMinRequested(1)) .then(() -> source.next(bufferConverter.toDataBuffer(firstChunk))) .then(() -> source.assertMinRequested(1)) .then(() -> source.next(bufferConverter.toDataBuffer(secondChunk))) .then(() -> source.assertMinRequested(1)) .then(source::complete) .verifyComplete(); verify(mockHttpClientRequest).write(firstChunk); verify(mockHttpClientRequest).write(secondChunk); verify(mockHttpClientRequest).end(); }
Example 2
Source File: BufferTest.java From vertx-redis-client with Apache License 2.0 | 6 votes |
@Test public void testAppendBuffer() { Request hmset = Request.cmd(Command.HMSET); Buffer key = Buffer.buffer("my-key"); for (int i = 0; i < iterations; i++) { hmset.arg(key).arg(i); } System.out.println(((RequestImpl) hmset).encode().length()); for (int j = 0; j < 5; j++) { final long t0 = System.nanoTime(); hmset = Request.cmd(Command.HMSET); for (int i = 0; i < iterations; i++) { hmset.arg(key).arg(i); } final long t1 = System.nanoTime(); System.out.println(((RequestImpl) hmset).encode().length() + "| t " + (t1 - t0)); } System.out.println("---"); }
Example 3
Source File: VertxServerHttpResponseTest.java From vertx-spring-boot with Apache License 2.0 | 6 votes |
@Test public void shouldWriteFromPublisher() { Buffer firstChunk = Buffer.buffer("chunk 1"); Buffer secondChunk = Buffer.buffer("chunk 2"); TestPublisher<DataBuffer> source = TestPublisher.create(); Mono<Void> result = response.writeWithInternal(source); StepVerifier.create(result) .expectSubscription() .then(() -> source.assertMinRequested(1)) .then(() -> source.next(bufferConverter.toDataBuffer(firstChunk))) .then(() -> source.assertMinRequested(1)) .then(() -> source.next(bufferConverter.toDataBuffer(secondChunk))) .then(() -> source.assertMinRequested(1)) .then(source::complete) .verifyComplete(); verify(mockHttpServerResponse).write(firstChunk); verify(mockHttpServerResponse).write(secondChunk); }
Example 4
Source File: ArrowBinaryInputAdapterTest.java From konduit-serving with Apache License 2.0 | 6 votes |
@Test(timeout = 60000) public void testArrowBinary() throws Exception { Schema irisInputSchema = TrainUtils.getIrisInputSchema(); ArrowRecordWriter arrowRecordWriter = new ArrowRecordWriter(irisInputSchema); CSVRecordReader reader = new CSVRecordReader(); reader.initialize(new FileSplit(new ClassPathResource("iris.txt").getFile())); List<List<Writable>> writables = reader.next(150); File tmpFile = new File(temporary.getRoot(), "tmp.arrow"); FileSplit fileSplit = new FileSplit(tmpFile); arrowRecordWriter.initialize(fileSplit, new NumberOfRecordsPartitioner()); arrowRecordWriter.writeBatch(writables); byte[] arrowBytes = FileUtils.readFileToByteArray(tmpFile); Buffer buffer = Buffer.buffer(arrowBytes); ArrowBinaryInputAdapter arrowBinaryInputAdapter = new ArrowBinaryInputAdapter(); ArrowWritableRecordBatch convert = arrowBinaryInputAdapter.convert(buffer, ConverterArgs.builder().schema(irisInputSchema).build(), null); assertEquals(writables.size(), convert.size()); }
Example 5
Source File: TestRestClientInvocation.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Test public void handleResponse() { HttpClientResponse httpClientResponse = mock(HttpClientResponse.class); doAnswer(a -> { bodyHandler = (Handler<Buffer>) a.getArguments()[0]; return httpClientResponse; }).when(httpClientResponse).bodyHandler(any()); Buffer buf = Buffer.buffer(); new MockUp<RestClientInvocation>(restClientInvocation) { @Mock void processResponseBody(Buffer responseBuf) { asyncResp.success(buf); } }; restClientInvocation.handleResponse(httpClientResponse); bodyHandler.handle(buf); Assert.assertSame(buf, response.getResult()); }
Example 6
Source File: TestStandardHttpServletResponseEx.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void flushBuffer() throws IOException { Buffer buffer = Buffer.buffer(); ServletOutputStream output = new ServletOutputStream() { @Override public boolean isReady() { return true; } @Override public void setWriteListener(WriteListener writeListener) { } @Override public void write(int b) throws IOException { buffer.appendByte((byte) b); } }; response = new MockUp<HttpServletResponse>() { @Mock ServletOutputStream getOutputStream() { return output; } }.getMockInstance(); responseEx = new StandardHttpServletResponseEx(response); // no body responseEx.flushBuffer(); Assert.assertEquals(0, buffer.length()); Buffer body = Buffer.buffer().appendString("body"); responseEx.setBodyBuffer(body); responseEx.flushBuffer(); Assert.assertEquals("body", buffer.toString()); }
Example 7
Source File: EchoServerVertx.java From apiman with Apache License 2.0 | 5 votes |
private Buffer getResource(String fPath) { ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource(fPath).getFile()); Buffer buff; try { buff = Buffer.buffer(Files.readAllBytes(file.toPath())); } catch (IOException e) { throw new RuntimeException(e); } return buff; }
Example 8
Source File: AbstractVertxBasedCoapAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Verifies that the adapter fails the upload of an event with a 4.00 result * if the request body is not empty but doesn't contain a content-format option. */ @Test public void testUploadTelemetryFailsForMissingContentFormat() { // GIVEN an adapter final DownstreamSender sender = givenATelemetrySender(Promise.promise()); final CoapServer server = getCoapServer(false); final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null); // WHEN a device publishes a non-empty message that lacks a content-format option final Buffer payload = Buffer.buffer("some payload"); final CoapExchange coapExchange = newCoapExchange(payload, Type.NON, (Integer) null); final Device authenticatedDevice = new Device("my-tenant", "the-device"); final CoapContext context = CoapContext.fromRequest(coapExchange); adapter.uploadTelemetryMessage(context, authenticatedDevice, authenticatedDevice); // THEN the device gets a response with code 4.00 verify(coapExchange).respond(argThat((Response res) -> ResponseCode.BAD_REQUEST.equals(res.getCode()))); // and the message has not been forwarded downstream verify(sender, never()).send(any(Message.class), any(SpanContext.class)); verify(metrics, never()).reportTelemetry( any(MetricsTags.EndpointType.class), anyString(), any(), any(MetricsTags.ProcessingOutcome.class), any(MetricsTags.QoS.class), anyInt(), any(TtdStatus.class), any()); }
Example 9
Source File: BsonCodecTest.java From mewbase with MIT License | 5 votes |
@Test public void testEncodeSize() { final BsonObject bsonObject = createBsonObject(); bsonObject.put("foo", "bar"); Buffer encoded = Buffer.buffer(BsonCodec.bsonObjectToBsonBytes(bsonObject)); int length = encoded.getIntLE(0); assertEquals(encoded.length(), length); }
Example 10
Source File: Frames.java From vertx-stomp with Apache License 2.0 | 5 votes |
static Frame createErrorFrame(String message, Map<String, String> headers, String body) { Objects.requireNonNull(message); Objects.requireNonNull(headers); Objects.requireNonNull(body); return new Frame(Frame.Command.ERROR, Headers.create(headers) .add(Frame.MESSAGE, message) .add(Frame.CONTENT_LENGTH, Integer.toString(body.length())) .add(Frame.CONTENT_TYPE, "text/plain"), Buffer.buffer(body)); }
Example 11
Source File: ProxyService.java From okapi with Apache License 2.0 | 5 votes |
private void proxyStreamToBuffer(ReadStream<Buffer> stream, Buffer bcontent, Handler<Buffer> handle) { if (bcontent != null) { handle.handle(bcontent); } else { final Buffer incoming = Buffer.buffer(); stream.handler(incoming::appendBuffer); stream.endHandler(v -> handle.handle(incoming)); stream.resume(); } }
Example 12
Source File: TestStandardHttpServletResponseEx.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void setBodyBuffer() { Assert.assertNull(responseEx.getBodyBuffer()); Buffer bodyBuffer = Buffer.buffer(); bodyBuffer.appendString("abc"); responseEx.setBodyBuffer(bodyBuffer); Assert.assertEquals("abc", responseEx.getBodyBuffer().toString()); }
Example 13
Source File: ConversionUtils.java From vertx-hazelcast with Apache License 2.0 | 5 votes |
@Override public void writeData(ObjectDataOutput objectDataOutput) throws IOException { objectDataOutput.writeUTF(clusterSerializable.getClass().getName()); Buffer buffer = Buffer.buffer(); clusterSerializable.writeToBuffer(buffer); byte[] bytes = buffer.getBytes(); objectDataOutput.writeInt(bytes.length); objectDataOutput.write(bytes); }
Example 14
Source File: Packet.java From besu with Apache License 2.0 | 5 votes |
public Buffer encode() { final Bytes encodedSignature = encodeSignature(signature); final BytesValueRLPOutput encodedData = new BytesValueRLPOutput(); data.writeTo(encodedData); final Buffer buffer = Buffer.buffer(hash.size() + encodedSignature.size() + 1 + encodedData.encodedSize()); hash.appendTo(buffer); encodedSignature.appendTo(buffer); buffer.appendByte(type.getValue()); appendEncoded(encodedData, buffer); return buffer; }
Example 15
Source File: AbstractVertxBasedHttpProtocolAdapterTest.java From hono with Eclipse Public License 2.0 | 4 votes |
/** * Verifies that the adapter waits for a command response being settled and accepted * by a downstream peer before responding with a 202 status to the device. */ @SuppressWarnings("unchecked") @Test public void testUploadCommandResponseWaitsForAcceptedOutcome() { // GIVEN an adapter with a downstream application attached final Promise<ProtonDelivery> outcome = Promise.promise(); givenACommandResponseSenderForOutcome(outcome.future()); final HttpServer server = getHttpServer(false); final AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null); // WHEN a device publishes a command response final Buffer payload = Buffer.buffer("some payload"); final HttpServerResponse response = mock(HttpServerResponse.class); final RoutingContext ctx = newRoutingContext(payload, "application/text", mock(HttpServerRequest.class), response); when(ctx.addBodyEndHandler(any(Handler.class))).thenAnswer(invocation -> { final Handler<Void> handler = invocation.getArgument(0); handler.handle(null); return 0; }); adapter.uploadCommandResponseMessage(ctx, "tenant", "device", CMD_REQ_ID, 200); // THEN the device does not get a response verify(response, never()).end(); // and the response has not been reported as forwarded verify(metrics, never()).reportCommand( eq(Direction.RESPONSE), eq("tenant"), any(), eq(ProcessingOutcome.FORWARDED), anyInt(), any()); // until the command response has been accepted by the application outcome.complete(mock(ProtonDelivery.class)); verify(response).setStatusCode(202); verify(response).end(); verify(metrics).reportCommand( eq(Direction.RESPONSE), eq("tenant"), any(), eq(ProcessingOutcome.FORWARDED), eq(payload.length()), any()); }
Example 16
Source File: GossipManager.java From jgossip with Apache License 2.0 | 4 votes |
public Buffer encodeAck2Message(Ack2Message ack2Message) { Buffer buffer = Buffer.buffer(); JsonObject ack2Json = JsonObject.mapFrom(ack2Message); buffer.appendString(GossipMessageFactory.getInstance().makeMessage(MessageType.ACK2_MESSAGE, ack2Json.encode(), getCluster(), getSelf().ipAndPort()).encode()); return buffer; }
Example 17
Source File: AbstractVertxBasedHttpProtocolAdapterTest.java From hono with Eclipse Public License 2.0 | 4 votes |
/** * Verifies that the adapter fails the upload of a message containing * a TTD value with a 404 result if the device is not registered. * Also verifies that the adapter does not open a command consumer for * the device in this case. */ @SuppressWarnings("unchecked") @Test public void testUploadTelemetryFailsForUnknownDevice() { // GIVEN an adapter final HttpServer server = getHttpServer(false); final DownstreamSender sender = givenATelemetrySenderForOutcome(Future.succeededFuture()); // with an enabled tenant final TenantObject myTenantConfig = TenantObject.from("my-tenant", true); when(tenantClient.get(eq("my-tenant"), any())).thenReturn(Future.succeededFuture(myTenantConfig)); final AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null); // WHEN an unknown device that supposedly belongs to that tenant publishes a telemetry message // with a TTD value set when(regClient.assertRegistration(eq("unknown-device"), any(), any(SpanContext.class))).thenReturn( Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND))); final Buffer payload = Buffer.buffer("some payload"); final HttpServerResponse response = mock(HttpServerResponse.class); final HttpServerRequest request = mock(HttpServerRequest.class); when(request.getHeader(eq(Constants.HEADER_TIME_TILL_DISCONNECT))).thenReturn("5"); final RoutingContext ctx = newRoutingContext(payload, "application/text", request, response); adapter.uploadTelemetryMessage(ctx, "my-tenant", "unknown-device", payload, "application/text"); // THEN the device gets a 404 assertContextFailedWithClientError(ctx, HttpURLConnection.HTTP_NOT_FOUND); verify(regClient).assertRegistration(eq("unknown-device"), any(), any(SpanContext.class)); // and the message has not been forwarded downstream verify(sender, never()).send(any(Message.class), any(SpanContext.class)); // and no Command consumer has been created for the device verify(commandConsumerFactory, never()).createCommandConsumer(anyString(), anyString(), any(Handler.class), any(), any()); // and has not been reported as processed verify(metrics, never()) .reportTelemetry( any(MetricsTags.EndpointType.class), anyString(), any(), eq(MetricsTags.ProcessingOutcome.FORWARDED), any(MetricsTags.QoS.class), anyInt(), any(MetricsTags.TtdStatus.class), any()); }
Example 18
Source File: KafkaHeaderImpl.java From vertx-kafka-client with Apache License 2.0 | 4 votes |
public KafkaHeaderImpl(String key, String value) { this(key, Buffer.buffer(value)); }
Example 19
Source File: FrameParserTest.java From vertx-stomp with Apache License 2.0 | 4 votes |
@Test public void testEmptyMessage() { Buffer buffer = Buffer.buffer(); Frame frame = parse(buffer); assertThat(frame).isNull(); }
Example 20
Source File: GeneratorTest.java From vertx-starter with Apache License 2.0 | 4 votes |
private void buildProject(Vertx vertx, BuildTool buildTool, Handler<AsyncResult<Void>> handler) { ProcessOptions processOptions = new ProcessOptions().setCwd(workdir.toString()); String command; List<String> args; if (buildTool == MAVEN) { command = "./mvnw"; args = Stream.<String>builder() .add("-Dmaven.repo.local=" + mavenRepository.toAbsolutePath().toString()) .add("-s") .add(settingsFile.toAbsolutePath().toString()) .add("-B") .add("verify") .build() .collect(toList()); } else if (buildTool == GRADLE) { command = "./gradlew"; args = Stream.<String>builder() .add("--no-build-cache") .add("--no-daemon") .add("assemble") .add("check") .build() .collect(toList()); } else { handler.handle(Future.failedFuture(unsupported(buildTool))); return; } Process process = Process.create(vertx, command, args, processOptions); cleanupTasks.add(() -> process.kill(true)); Buffer buffer = Buffer.buffer(); process.stdout().handler(buffer::appendBuffer); process.stderr().handler(buffer::appendBuffer); process.exitHandler(code -> { if (code == 0) { handler.handle(Future.succeededFuture()); } else { handler.handle(Future.failedFuture(String.format("Failed to build project%n%s", buffer.toString()))); } }); process.start(); }