io.vertx.core.buffer.Buffer Java Examples

The following examples show how to use io.vertx.core.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: Utils.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public static Buffer readResourceToBuffer(String resource) {
  ClassLoader cl = getClassLoader();
  try {
    Buffer buffer = Buffer.buffer();
    try (InputStream in = cl.getResourceAsStream(resource)) {
      if (in == null) {
        return null;
      }
      int read;
      byte[] data = new byte[4096];
      while ((read = in.read(data, 0, data.length)) != -1) {
        if (read == data.length) {
          buffer.appendBytes(data);
        } else {
          byte[] slice = new byte[read];
          System.arraycopy(data, 0, slice, 0, slice.length);
          buffer.appendBytes(slice);
        }
      }
    }
    return buffer;
  } catch (IOException ioe) {
    throw new RuntimeException(ioe);
  }
}
 
Example #2
Source File: MockUtil.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public void mockHighwayCodec() {

    new MockUp<HighwayCodec>() {
      @Mock
      RequestHeader readRequestHeader(Buffer headerBuffer) throws Exception {
        return requestHeader;
      }

      @Mock
      public Invocation decodeRequest(RequestHeader header, OperationProtobuf operationProtobuf, Buffer bodyBuffer)
          throws Exception {
        if (decodeRequestSucc) {
          return Mockito.mock(Invocation.class);
        }

        throw new Error("decode failed");
      }
    };
  }
 
Example #3
Source File: VendorListService.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
/**
 * Saves given vendor list on file system.
 */
private Future<VendorListResult<T>> saveToFile(VendorListResult<T> vendorListResult) {
    final Promise<VendorListResult<T>> promise = Promise.promise();
    final int version = vendorListResult.getVersion();
    final String filepath = new File(cacheDir, version + JSON_SUFFIX).getPath();

    fileSystem.writeFile(filepath, Buffer.buffer(vendorListResult.getVendorListAsString()), result -> {
        if (result.succeeded()) {
            promise.complete(vendorListResult);
        } else {
            logger.error("Could not create new vendor list for version {0}, file: {1}", result.cause(), version,
                    filepath);
            promise.fail(result.cause());
        }
    });

    return promise.future();
}
 
Example #4
Source File: SettingsCacheNotificationHandler.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
/**
 * Propagates invalidating settings cache
 */
private void doInvalidate(RoutingContext context) {
    final Buffer body = context.getBody();
    if (body == null) {
        HttpUtil.respondWith(context, HttpResponseStatus.BAD_REQUEST, "Missing invalidation data.");
        return;
    }

    final InvalidateSettingsCacheRequest request;
    try {
        request = mapper.decodeValue(body, InvalidateSettingsCacheRequest.class);
    } catch (DecodeException e) {
        HttpUtil.respondWith(context, HttpResponseStatus.BAD_REQUEST, "Invalid invalidation.");
        return;
    }

    cacheNotificationListener.invalidate(request.getRequests(), request.getImps());
    HttpUtil.respondWith(context, HttpResponseStatus.OK, null);
}
 
Example #5
Source File: FileBasedTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the tenant service successfully starts up even if
 * the file to read tenants from contains malformed JSON.
 *
 * @param ctx The vert.x context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testDoStartIgnoresMalformedJson(final VertxTestContext ctx) {

    // GIVEN a tenant service configured to read data from a file
    // that contains malformed JSON
    props.setFilename(FILE_NAME);
    when(fileSystem.existsBlocking(FILE_NAME)).thenReturn(Boolean.TRUE);
    doAnswer(invocation -> {
        final Buffer data = mock(Buffer.class);
        when(data.getBytes()).thenReturn("NO JSON".getBytes(StandardCharsets.UTF_8));
        final Handler handler = invocation.getArgument(1);
        handler.handle(Future.succeededFuture(data));
        return null;
    }).when(fileSystem).readFile(eq(props.getFilename()), any(Handler.class));

    // WHEN starting the service
    final Promise<Void> startupTracker = Promise.promise();
    startupTracker.future().onComplete(ctx.completing(
        // THEN startup succeeds
    ));
    svc.start().onComplete(startupTracker);
}
 
Example #6
Source File: VaultConfigStore.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
private Future<Buffer> extract(JsonObject json) {
  Promise<Buffer> promise = Promise.promise();
  if (json == null) {
    promise.complete(new JsonObject().toBuffer());
  } else if (config.getString("key") != null) {
    Object value = json.getValue(config.getString("key"));
    if (value == null) {
      promise.complete(new JsonObject().toBuffer());
    } else if (value instanceof String) {
      promise.complete(Buffer.buffer((String) value));
    } else if (value instanceof JsonObject) {
      promise.complete(((JsonObject) value).toBuffer());
    }
  } else {
    promise.complete(json.toBuffer());
  }
  return promise.future();
}
 
Example #7
Source File: RedirectAuthHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private Consumer<HttpClientRequest> sendLoginRequestConsumer() {
  return req -> {
    String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";
    Buffer buffer = Buffer.buffer();
    String str =
      "--" + boundary + "\r\n" +
        "Content-Disposition: form-data; name=\"" + usernameParam + "\"\r\n\r\ntim\r\n" +
        "--" + boundary + "\r\n" +
        "Content-Disposition: form-data; name=\"" + passwordParam + "\"\r\n\r\ndelicious:sausages\r\n" +
        "--" + boundary + "--\r\n";
    buffer.appendString(str);
    req.putHeader("content-length", String.valueOf(buffer.length()));
    req.putHeader("content-type", "multipart/form-data; boundary=" + boundary);
    if (sessionCookie.get() != null) {
      req.putHeader("cookie", sessionCookie.get());
    }
    req.write(buffer);
  };
}
 
Example #8
Source File: WebSocketServiceTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void websocketServiceCloseConnectionOnUnrecoverableError(final TestContext context) {
  final Async async = context.async();

  final byte[] bigMessage = new byte[HttpServerOptions.DEFAULT_MAX_WEBSOCKET_MESSAGE_SIZE + 1];
  Arrays.fill(bigMessage, (byte) 1);

  httpClient.websocket(
      "/",
      webSocket -> {
        webSocket.write(Buffer.buffer(bigMessage));
        webSocket.closeHandler(v -> async.complete());
      });

  async.awaitSuccess(VERTX_AWAIT_TIMEOUT_MILLIS);
}
 
Example #9
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 #10
Source File: VertxWebSocketSessionTest.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSendBinaryMessage() {
    TestPublisher<WebSocketMessage> source = TestPublisher.create();
    Mono<Void> result = session.send(source);

    StepVerifier.create(result)
        .expectSubscription()
        .then(() -> source.assertMinRequested(1))
        .then(() -> source.next(getWebSocketMessage(WebSocketMessage.Type.BINARY, "test1")))
        .then(() -> source.assertMinRequested(1))
        .then(() -> source.next(getWebSocketMessage(WebSocketMessage.Type.BINARY, "test2")))
        .then(() -> source.assertMinRequested(1))
        .then(source::complete)
        .verifyComplete();

    verify(mockServerWebSocket).writeBinaryMessage(Buffer.buffer("test1"));
    verify(mockServerWebSocket).writeBinaryMessage(Buffer.buffer("test2"));
}
 
Example #11
Source File: JournalFile.java    From sfs with Apache License 2.0 6 votes vote down vote up
private Observable<Void> setSuperBlock(SfsVertx vertx, BlobFile internalBlobFile, Super superBlock) {
    Buffer buffer = buffer(superBlock.toByteArray());
    Block.Frame<Buffer> frame = encodeFrame(buffer);
    Buffer frameBuffer = frame.getData();
    int frameSize = frameBuffer.length();

    checkState(frameSize <= SUPER_BLOCK_SIZE, "Super block frame size was %s, which is greater block size of %s", frameSize, SUPER_BLOCK_SIZE);

    // write the super block twice so that we can recover from a failed
    // write
    return aVoid()
            .flatMap(aVoid -> internalBlobFile.consume(vertx, SUPER_BLOCK_POSITION_0, frameBuffer))
            .flatMap(aVoid -> internalBlobFile.force(vertx, true))
            .flatMap(aVoid -> internalBlobFile.consume(vertx, SUPER_BLOCK_POSITION_1, frameBuffer))
            .flatMap(aVoid -> internalBlobFile.force(vertx, true));
}
 
Example #12
Source File: KeepAliveHttpServerResponse.java    From sfs with Apache License 2.0 6 votes vote down vote up
@Override
public HttpServerResponse write(Buffer chunk) {
    ObservableFuture<Void> handler = RxHelper.observableFuture();
    stopKeepAlive(handler);
    handler.subscribe(new Subscriber<Void>() {
        @Override
        public void onCompleted() {
            delegate.write(chunk);
        }

        @Override
        public void onError(Throwable e) {
            handleThrowable(e);
        }

        @Override
        public void onNext(Void aVoid) {

        }
    });
    return this;
}
 
Example #13
Source File: WSConsumesTest.java    From vert.x-microservice with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleObjectByBinarySerialisation() throws InterruptedException {
    final PersonOne message = new PersonOne("Andy","M");

    getClient().websocket(8080, "localhost", SERVICE_REST_GET + "/testSimpleObjectByBinarySerialisation", ws -> {
        long startTime = System.currentTimeMillis();
        ws.handler((data) -> {
            System.out.println("testSimpleObjectBySerialisation :" + new String(data.getBytes()));
            assertNotNull(data.getString(0, data.length()));
            assertTrue(new String(data.getBytes()).equals(message.getName()));

            ws.close();
            long endTime = System.currentTimeMillis();
            System.out.println("Total execution time testSimpleObjectByBinarySerialisation: " + (endTime - startTime) + "ms");
            testComplete();
        });

        try {
            byte[] tmp = Serializer.serialize(message);
            ws.writeBinaryMessage(Buffer.buffer(tmp));
        } catch (IOException e) {
            e.printStackTrace();
        }
    });


    await();

}
 
Example #14
Source File: CustomMessageCodec.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void encodeToWire(Buffer buffer, CustomMessage customMessage) {
    String jsonStr = Json.encode(customMessage);
    int length = jsonStr.getBytes().length;
    buffer.appendInt(length);
    buffer.appendString(jsonStr);
}
 
Example #15
Source File: BusTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testBusSendHex(TestContext context) {
  Async consumerAsync = context.async();
  assertBusSend(context, "bus-send --type HEX the_address 001FFF", msg -> {
    context.assertEquals(Buffer.buffer(new byte[]{0,31,-1}), msg.body());
    consumerAsync.complete();
  });
}
 
Example #16
Source File: MqttEndpointImpl.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Override
public MqttEndpointImpl publish(String topic, Buffer payload, MqttQoS qosLevel, boolean isDup, boolean isRetain, int messageId, Handler<AsyncResult<Integer>> publishSentHandler) {
  Future<Integer> fut = publish(topic, payload, qosLevel, isDup, isRetain, messageId);
  if (publishSentHandler != null) {
    fut.onComplete(publishSentHandler);
  }
  return this;
}
 
Example #17
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 #18
Source File: FrameParserTest.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Test
public void testFrameWithWrongContentLength() {
  String content = "this is my \n content.";
  Buffer buffer = Buffer.buffer("SEND\n" +
      "header:hello\n" +
      "content-length:" + (content.length() - 2) + "\n" +
      "\n" +
      content)
      .appendString(FrameParser.NULL);

  Frame frame = parse(buffer);
  assertThat(frame.getCommand()).isEqualTo(Frame.Command.SEND);
  assertThat(frame.getHeader("header")).isEqualTo("hello");
  assertThat(frame.getBodyAsString(StompOptions.UTF_8)).isEqualTo("this is my \n conten");
}
 
Example #19
Source File: RestVerticle.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * @param method2Run
 * @param rc
 * @param request
 * @param okapiHeaders
 * @param tenantId
 * @param instance
 * @param uploadParamPosition
 * @param paramArray
 * @param validRequest
 * @param start
 */
private void handleInputStreamUpload(Method method2Run, RoutingContext rc, HttpServerRequest request,
    Object instance, String[] tenantId, Map<String, String> okapiHeaders,
    int[] uploadParamPosition, Object[] paramArray, boolean[] validRequest, long start) {

  final Buffer content = Buffer.buffer();

  request.handler(new Handler<Buffer>() {
    @Override
    public void handle(Buffer buff) {
      content.appendBuffer(buff);
    }
  });
  request.endHandler( e -> {
    paramArray[uploadParamPosition[0]] = new ByteArrayInputStream(content.getBytes());
    try {
      invoke(method2Run, paramArray, instance, rc, tenantId, okapiHeaders, new StreamStatus(), v -> {
        LogUtil.formatLogMessage(className, "start", " invoking " + method2Run);
        sendResponse(rc, v, start, tenantId[0]);
      });
    } catch (Exception e1) {
      log.error(e1.getMessage(), e1);
      rc.response().end();
    }
  });

  request.exceptionHandler(new Handler<Throwable>(){
    @Override
    public void handle(Throwable event) {
      endRequestWithError(rc, 400, true, event.getMessage(), validRequest);
    }
  });

}
 
Example #20
Source File: TypeScriptVerticleTest.java    From vertx-lang-typescript with Apache License 2.0 5 votes vote down vote up
private void makeRequest(HttpClient client, int port, int retries, int delay,
    Handler<AsyncResult<Buffer>> handler) {
  Vertx vertx = runTestOnContext.vertx();
  HttpClientRequest request = client.get(port, "localhost", "/", response ->
    response.bodyHandler(buffer -> handler.handle(Future.succeededFuture(buffer))));
  request.exceptionHandler(t -> {
    if (retries > 0 && t instanceof ConnectException) {
      vertx.setTimer(delay, l -> makeRequest(client, port, retries - 1, delay, handler));
    } else {
      handler.handle(Future.failedFuture(t));
    }
  });
  request.end();
}
 
Example #21
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testMailRelaxedRelaxedHtmlWithAttachment(TestContext testContext) {
  this.testContext = testContext;
  Buffer img = vertx.fileSystem().readFileBlocking("logo-white-big.png");
  testContext.assertTrue(img.length() > 0);
  MailAttachment attachment = MailAttachment.create().setName("logo-white-big.png").setData(img);
  MailAttachment inLineAttachment = MailAttachment.create().setName("logo-inline").setData(img);
  MailMessage message = exampleMessage()
    .setText(TEXT_BODY)
    .setHtml(HTML_BODY)
    .setInlineAttachment(inLineAttachment)
    .setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.RELAXED).setBodyCanonAlgo(CanonicalizationAlgorithm.RELAXED);
  testSuccess(dkimMailClient(dkimOps), message, () -> {

    // 1. alternative multi part
    //    1.1: text part
    //    1.2: html multi part with inline attachment
    //       1.2.1: html body part
    //       1.2.2: inline attachment
    // 2. attachment part
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    MimeMultipart alternative = (MimeMultipart)multiPart.getBodyPart(0).getContent();
    testContext.assertEquals(2, alternative.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(alternative.getBodyPart(0).getInputStream())));
    MimeMultipart htmlPart = (MimeMultipart)alternative.getBodyPart(1).getContent();
    testContext.assertEquals(2, htmlPart.getCount());
    testContext.assertEquals(HTML_BODY, conv2nl(inputStreamToString(htmlPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(htmlPart.getBodyPart(1).getInputStream())));

    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));

    testDKIMSign(dkimOps, testContext);
  });
}
 
Example #22
Source File: RabbitMQClientImpl.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> basicPublish(String exchange, String routingKey, BasicProperties properties, Buffer body) {
  return forChannel(channel -> {
    channel.basicPublish(exchange, routingKey, (AMQP.BasicProperties) properties, body.getBytes());
    return null;
  });
}
 
Example #23
Source File: PreBidRequestContextFactoryTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailIfRequestBodyCouldNotBeParsed() {
    // given
    given(routingContext.getBody()).willReturn(Buffer.buffer("{"));

    // when
    final Future<PreBidRequestContext> preBidRequestContextFuture = factory.fromRequest(routingContext);

    // then
    assertThat(preBidRequestContextFuture.failed()).isTrue();
    assertThat(preBidRequestContextFuture.cause())
            .isInstanceOf(PreBidException.class)
            .hasMessageStartingWith("Failed to decode")
            .hasCauseInstanceOf(JsonParseException.class);
}
 
Example #24
Source File: CertificateAuthorityNodeClientTest.java    From orion with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void setUp(@TempDirectory final Path tempDir) throws Exception {
  final SelfSignedCertificate clientCert = SelfSignedCertificate.create("localhost");
  final Config config = generateAndLoadConfiguration(tempDir, writer -> {
    writer.write("tlsclienttrust='ca'\n");
    writeClientCertToConfig(writer, clientCert);
  });

  final Path knownServersFile = config.tlsKnownServers();

  final SelfSignedCertificate serverCert = SelfSignedCertificate.create("localhost");
  TestUtils.configureJDKTrustStore(serverCert, tempDir);
  Files.write(knownServersFile, Collections.singletonList("#First line"));

  final Router dummyRouter = Router.router(vertx);
  final ReadOnlyNetworkNodes payload =
      new ReadOnlyNetworkNodes(URI.create("http://www.example.com"), Collections.emptyMap());
  dummyRouter.post("/partyinfo").handler(routingContext -> {
    routingContext.response().end(Buffer.buffer(Serializer.serialize(HttpContentType.CBOR, payload)));
  });

  client = NodeHttpClientBuilder.build(vertx, config, 100);
  caValidServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(serverCert.keyCertOptions()))
      .requestHandler(dummyRouter::accept);
  startServer(caValidServer);
  unknownServer = vertx
      .createHttpServer(
          new HttpServerOptions().setSsl(true).setPemKeyCertOptions(SelfSignedCertificate.create().keyCertOptions()))
      .requestHandler(dummyRouter::accept);
  startServer(unknownServer);
}
 
Example #25
Source File: PublishEncoder.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(PublishMessage message, ByteBuf out) {
    if (message.getQos() == AbstractMessage.QOSType.RESERVED) {
        throw new IllegalArgumentException("Found a message with RESERVED Qos");
    }
    if (message.getTopicName() == null || message.getTopicName().isEmpty()) {
        throw new IllegalArgumentException("Found a message with empty or null topic name");
    }
    
    ByteBuf variableHeaderBuff = Buffer.buffer(2).getByteBuf();
    try {
        variableHeaderBuff.writeBytes(Utils.encodeString(message.getTopicName()));
        if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE ||
            message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE ) {
            if (message.getMessageID() == null) {
                throw new IllegalArgumentException("Found a message with QOS 1 or 2 and not MessageID setted");
            }
            variableHeaderBuff.writeShort(message.getMessageID());
        }

        variableHeaderBuff.writeBytes(message.getPayload().array());
        int variableHeaderSize = variableHeaderBuff.readableBytes();

        byte flags = Utils.encodeFlags(message);
        ByteBuf buff = Buffer.buffer(2 + variableHeaderSize).getByteBuf();
        buff.writeByte(AbstractMessage.PUBLISH << 4 | flags);
        buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
        buff.writeBytes(variableHeaderBuff);
        out.writeBytes(buff);
    } finally {
        variableHeaderBuff.release();
    }
}
 
Example #26
Source File: RoutingContextImplTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void test_null_literal_array_as_json_array_yields_null_json_array() throws Exception {
  router.route().handler(event -> {
    assertEquals(null, event.getBodyAsJsonArray());
    event.response().end();
  });
  testRequest(HttpMethod.POST, "/", req -> {
    req.setChunked(true);
    req.write(Buffer.buffer("null"));
  }, HttpResponseStatus.OK.code(), HttpResponseStatus.OK.reasonPhrase(), null);
}
 
Example #27
Source File: MessageSendTester.java    From enmasse with Apache License 2.0 5 votes vote down vote up
/**
 * Fill up the message with extra payload to get an exact payload size (in bytes).
 * <p>
 * If the payload size if greater than zero, it will always requires {@link #FIXED_JSON_EXTRA_SIZE}
 * of bytes remaining for an empty object and {@link #FIXED_JSON_EXTRA_SIZE} plus one for an object
 * which already contains a field.
 *
 * @param payload The payload to modify.
 * @param payloadSize The target payload size. If this is zero or less, this operation is a no-op.
 * @throws IllegalArgumentException if the target payload size is lower than the already provided
 *         payload.
 */
static Buffer fillWithPayload(final JsonObject payload, final int payloadSize) {

    final Buffer buffer = payload.toBuffer();

    if (payloadSize <= 0) {
        return buffer;
    }

    // if the object is empty, there will be no extra comma
    final int extraComma = payload.isEmpty() ? 0 : 1;
    final int actualSize = buffer.length();
    final int fixed = FIXED_JSON_EXTRA_SIZE + extraComma;

    if (actualSize + fixed > payloadSize) {
        // we are already "too big"
        throw new IllegalArgumentException(String.format("Provided payload size already exceeds maximum (actual: %d + %d, target: %d)",
                actualSize, fixed, payloadSize));
    }

    final int diff = payloadSize - actualSize - fixed;
    final char[] fill = new char[diff];
    Arrays.fill(fill, 'a');
    payload.put("extra", String.valueOf(fill));

    return payload.toBuffer();
}
 
Example #28
Source File: SockJSHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Buffer combineReplies(List<Buffer> receivedMessages) {
  Buffer combinedReply = Buffer.buffer();
  for (Buffer receivedMessage : receivedMessages) {
    combinedReply.appendBuffer(receivedMessage);
  }
  return combinedReply;
}
 
Example #29
Source File: PipePayloadParser.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void handle(Buffer buffer) {
    if (recordParser == null && directMapper == null) {
        log.error("record parser not init");
        return;
    }
    if (recordParser != null) {
        recordParser.handle(buffer);
        return;
    }
    Buffer buf = directMapper.apply(buffer);
    if (null != buf) {
        sink.next(buf);
    }
}
 
Example #30
Source File: ProtocolGateway.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void handleData(final NetSocket socket, final Map<String, Object> dictionary, final Buffer buffer) {

        final String data = buffer.toString();
        LOG.debug("received data from device: [{}]", data);
        // split up in command token [0] and args [1]
        final String[] command = data.split(" ", 2);
        executeCommand(command, socket, dictionary)
            .onSuccess(c -> {
                socket.write("OK\n");
            })
            .onFailure(t -> {
                LOG.debug("failed to process data provided by device");
                socket.write("FAILED: " + t.getMessage() + "\n");
            });
    }