Java Code Examples for io.vertx.core.buffer.Buffer#appendString()

The following examples show how to use io.vertx.core.buffer.Buffer#appendString() . 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: FormParametersTest.java    From nubes with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormBoolean(TestContext context) {
  Boolean myBoolean = true;
  Buffer data = Buffer.buffer();
  data.appendString("value=" + myBoolean);
  Async async = context.async();
  client().post("/params/form/boolean").handler(response -> {
    Buffer buff = Buffer.buffer();
    response.handler(buffer -> {
      buff.appendBuffer(buffer);
    });
    response.endHandler(handler -> {
      context.assertEquals(myBoolean, Boolean.valueOf(buff.toString()));
      async.complete();
    });
  }).putHeader(CONTENT_TYPE, "application/x-www-form-urlencoded").end(data);
}
 
Example 2
Source File: PojoEventBusCodec.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
@Override
public void encodeToWire(Buffer buffer, Object pojo) {

  try {
    String value = MAPPER.writeValueAsString(pojo);
    String clazz = pojo.getClass().getName();
    int clazzLength = clazz.getBytes().length;
    buffer.appendInt(clazzLength);
    buffer.appendString(clazz);
    if(value != null){
      int dataLength = value.getBytes().length;
      // Write data into given buffer
      buffer.appendInt(dataLength);
      buffer.appendString(value);
    }
  } catch (JsonProcessingException e) {
    log.error(e.getMessage(), e);
  }
}
 
Example 3
Source File: TestStandardHttpServletRequestEx.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void setBodyBuffer() {
  Buffer bodyBuffer = Buffer.buffer();
  bodyBuffer.appendString("abc");

  requestEx.setBodyBuffer(bodyBuffer);
  Assert.assertSame(bodyBuffer, requestEx.getBodyBuffer());
  Assert.assertArrayEquals("abc".getBytes(), Arrays.copyOf(requestEx.getBodyBytes(), requestEx.getBodyBytesLength()));
}
 
Example 4
Source File: TestStandardHttpServletResponseEx.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@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 5
Source File: FormParametersTest.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Test
public void testBackingParamsWithBoolean(TestContext context) {
  Dog dog = TestVerticle.dogService.someDog();
  dog.setPuppy(true);
  Buffer data = Buffer.buffer();
  data.appendString("name=" + dog.getName() + "&breed=" + dog.getBreed() + "&puppy=" + dog.isPuppy());
  Async async = context.async();
  client().post("/params/form/dog").handler(response -> {
    response.bodyHandler(buff -> {
      context.assertEquals(dog.toString(), buff.toString("UTF-8"));
      async.complete();
    });
  }).putHeader(CONTENT_TYPE, "application/x-www-form-urlencoded").end(data);
}
 
Example 6
Source File: TestStandardHttpServletResponseEx.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void getBodyBytesLength() {
  Buffer bodyBuffer = Buffer.buffer();
  bodyBuffer.appendString("abc");
  responseEx.setBodyBuffer(bodyBuffer);
  Assert.assertEquals(3, responseEx.getBodyBytesLength());
}
 
Example 7
Source File: TestServiceRegistryClientImpl.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegisterSchemaErrorResponse() {
  new MockUp<ServiceRegistryClientImpl>() {
    @Mock
    Handler<RestResponse> syncHandlerEx(CountDownLatch countDownLatch, Holder<ResponseWrapper> holder) {
      return restResponse -> {
        HttpClientResponse response = Mockito.mock(HttpClientResponse.class);
        Mockito.when(response.statusCode()).thenReturn(400);
        Mockito.when(response.statusMessage()).thenReturn("client error");

        Buffer bodyBuffer = Buffer.buffer();
        bodyBuffer.appendString("too big");

        ResponseWrapper responseWrapper = new ResponseWrapper();
        responseWrapper.response = response;
        responseWrapper.bodyBuffer = bodyBuffer;
        holder.value = responseWrapper;
      };
    }
  };
  new MockUp<RestClientUtil>() {
    @Mock
    void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) {
      responseHandler.handle(null);
    }
  };

  new RegisterSchemaTester() {
    void doRun(java.util.List<LoggingEvent> events) {
      oClient.registerSchema("msid", "schemaId", "content");
      Assert.assertEquals(
          "Register schema msid/schemaId failed, statusCode: 400, statusMessage: client error, description: too big.",
          events.get(0).getMessage());
    }
  }.run();
}
 
Example 8
Source File: FormParametersTest.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Test
public void testBackingParams(TestContext context) {
  Dog dog = TestVerticle.dogService.someDog();
  Buffer data = Buffer.buffer();
  data.appendString("name=" + dog.getName() + "&breed=" + dog.getBreed());
  Async async = context.async();
  client().post("/params/form/dog").handler(response -> {
    response.bodyHandler(buff -> {
      context.assertEquals(dog.toString(), buff.toString("UTF-8"));
      async.complete();
    });
  }).putHeader(CONTENT_TYPE, "application/x-www-form-urlencoded").end(data);
}
 
Example 9
Source File: FormParametersTest.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Test
public void testBooleanParams(TestContext context) {
  Boolean value = true;
  Buffer data = Buffer.buffer();
  data.appendString("value=" + value);
  Async async = context.async();
  client().post("/params/form/boolean").handler(response -> {
    response.bodyHandler(buff -> {
      context.assertEquals(value, Boolean.valueOf(buff.toString()));
      async.complete();
    });
  }).putHeader(CONTENT_TYPE, "application/x-www-form-urlencoded").end(data);
}
 
Example 10
Source File: SampleDatabaseWriter.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().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 = "foo@bar";
  value = "Foo Bar Baz";
  buffer
    .appendInt(key.length())
    .appendString(key)
    .appendInt(value.length())
    .appendString(value);

  file.end(buffer, ar -> vertx.close());
}
 
Example 11
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 12
Source File: Serializer.java    From jgossip with Apache License 2.0 5 votes vote down vote up
public Buffer encode(Serializable obj) {
    Buffer buffer = Buffer.buffer();
    try {
        buffer.appendString(JsonObject.mapFrom(obj).encode());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return buffer;
}
 
Example 13
Source File: FormParametersTest.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrongBackingParams(TestContext context) {
  Dog dog = TestVerticle.dogService.someDog();
  String invalidValue = "invalidLong";
  Buffer data = Buffer.buffer();
  data.appendString("name=" + dog.getName() + "&breed=" + dog.getBreed() + "&age=" + invalidValue);
  Async async = context.async();
  client().post("/params/form/dog").handler(response -> {
    context.assertEquals(400, response.statusCode());
    response.bodyHandler(buff -> {
      context.assertEquals("Some request of form parameter has an invalid value", buff.toString("UTF-8"));
      async.complete();
    });
  }).putHeader(CONTENT_TYPE, "application/x-www-form-urlencoded").end(data);
}
 
Example 14
Source File: BodyHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileUploadFileRemovalOnClientClosesConnection() throws Exception {

  String uploadsDirectory = tempUploads.newFolder().getPath();
  router.clear();
  router.route().handler(BodyHandler.create()
    .setUploadsDirectory(uploadsDirectory));

  assertEquals(0, vertx.fileSystem().readDirBlocking(uploadsDirectory).size());
  io.vertx.core.http.HttpClientRequest req = client.request(HttpMethod.POST, "/");

  String name = "somename";
  String fileName = "somefile.dat";
  String contentType = "application/octet-stream";
  String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";
  Buffer buffer = Buffer.buffer();
  String header =
    "--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n" +
      "Content-Type: " + contentType + "\r\n" +
      "Content-Transfer-Encoding: binary\r\n" +
      "\r\n";
  buffer.appendString(header);
  buffer.appendBuffer(TestUtils.randomBuffer(50));
  req.headers().set("content-length", String.valueOf(buffer.length() + 50)); //partial upload
  req.headers().set("content-type", "multipart/form-data; boundary=" + boundary);
  req.write(buffer);

  for (int i = 100; i > 0 && vertx.fileSystem().readDirBlocking(uploadsDirectory).size() == 0; i--) {
    Thread.sleep(100); //wait for upload beginning
  }
  assertEquals(1, vertx.fileSystem().readDirBlocking(uploadsDirectory).size());

  req.connection().close();

  for (int i = 100; i > 0 && vertx.fileSystem().readDirBlocking(uploadsDirectory).size() != 0; i--) {
    Thread.sleep(100); //wait for upload being deleted
  }
  assertEquals(0, vertx.fileSystem().readDirBlocking(uploadsDirectory).size());
}
 
Example 15
Source File: JWK.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
private int parsePEM(KeyFactory kf, String pem) throws CertificateException, InvalidKeySpecException {
  // extract the information from the pem
  String[] lines = pem.split("\r?\n");
  // A PEM PKCS#8 formatted string shall contain on the first line the kind of content
  if (lines.length <= 2) {
    throw new IllegalArgumentException("PEM contains not enough lines");
  }
  // there must be more than 2 lines
  Pattern begin = Pattern.compile("-----BEGIN (.+?)-----");
  Pattern end = Pattern.compile("-----END (.+?)-----");

  Matcher beginMatcher = begin.matcher(lines[0]);
  if (!beginMatcher.matches()) {
    throw new IllegalArgumentException("PEM first line does not match a BEGIN line");
  }
  String kind = beginMatcher.group(1);
  Buffer buffer = Buffer.buffer();
  boolean endSeen = false;
  for (int i = 1; i < lines.length; i++) {
    if ("".equals(lines[i])) {
      continue;
    }
    Matcher endMatcher = end.matcher(lines[i]);
    if (endMatcher.matches()) {
      endSeen = true;
      if (!kind.equals(endMatcher.group(1))) {
        throw new IllegalArgumentException("PEM END line does not match start");
      }
      break;
    }
    buffer.appendString(lines[i]);
  }

  if (!endSeen) {
    throw new IllegalArgumentException("PEM END line not found");
  }

  switch (kind) {
    case "CERTIFICATE":
      final CertificateFactory cf = CertificateFactory.getInstance("X.509");
      publicKey = cf.generateCertificate(new ByteArrayInputStream(pem.getBytes())).getPublicKey();
      return USE_ENC;
    case "PUBLIC KEY":
      publicKey = kf.generatePublic(new X509EncodedKeySpec(Base64.getMimeDecoder().decode(buffer.getBytes())));
      return USE_ENC;
    case "PRIVATE KEY":
      privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(buffer.getBytes())));
      return USE_SIG;
    default:
      throw new IllegalStateException("Invalid PEM content: " + kind);
  }
}
 
Example 16
Source File: DemoRamlRestTest.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
private void testStream(TestContext context, boolean chunk) {
  int chunkSize = 1024;
  int numberChunks = 50;
  Async async = context.async();
  HttpClient httpClient = vertx.createHttpClient();
  HttpClientRequest req = httpClient.post(port, "localhost", "/rmbtests/testStream", res -> {
    Buffer resBuf = Buffer.buffer();
    res.handler(resBuf::appendBuffer);
    res.endHandler(x -> {
      context.assertEquals(200, res.statusCode());
      JsonObject jo = new JsonObject(resBuf);
      context.assertTrue(jo.getBoolean("complete"));
      async.complete();
    });
    res.exceptionHandler(x -> {
      if (!async.isCompleted()) {
        context.assertTrue(false, "exceptionHandler res: " + x.getLocalizedMessage());
        async.complete();
      }
    });
  });
  req.exceptionHandler(x -> {
    if (!async.isCompleted()) {
      context.assertTrue(false, "exceptionHandler req: " + x.getLocalizedMessage());
      async.complete();
    }
  });
  if (chunk) {
    req.setChunked(true);
  } else {
    req.putHeader("Content-Length", Integer.toString(chunkSize * numberChunks));
  }
  req.putHeader("Accept", "application/json,text/plain");
  req.putHeader("Content-type", "application/octet-stream");
  req.putHeader("x-okapi-tenant", TENANT);
  Buffer buf = Buffer.buffer(chunkSize);
  for (int i = 0; i < chunkSize; i++) {
    buf.appendString("X");
  }
  for (int i = 0; i < numberChunks; i++) {
    req.write(buf);
  }
  req.end();
}
 
Example 17
Source File: PersonCodec.java    From vertx-camel-bridge with Apache License 2.0 4 votes vote down vote up
@Override
public void encodeToWire(Buffer buffer, Person person) {
  String encoded = Json.encode(person);
  buffer.appendInt(encoded.length());
  buffer.appendString(encoded);
}
 
Example 18
Source File: GossipManager.java    From jgossip with Apache License 2.0 4 votes vote down vote up
private Buffer encodeShutdownMessage() {
    Buffer buffer = Buffer.buffer();
    JsonObject self = JsonObject.mapFrom(getSelf());
    buffer.appendString(GossipMessageFactory.getInstance().makeMessage(MessageType.SHUTDOWN, self.encode(), getCluster(), getSelf().ipAndPort()).encode());
    return buffer;
}
 
Example 19
Source File: GossipManager.java    From jgossip with Apache License 2.0 4 votes vote down vote up
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 20
Source File: Frame.java    From vertx-stomp with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a buffer for the current frame. This buffer may contain an empty line if the {@code trailingLine} is set
 * to {@code true}
 *
 * @param trailingLine whether or not a trailing line should be added to the buffer
 * @return a {@link Buffer} containing the STOMP frame. It follows strictly the STOMP specification (including
 * header encoding).
 */
public Buffer toBuffer(boolean trailingLine) {
  Buffer buffer = toBuffer();
  if (trailingLine) {
    buffer.appendString("\n");
  }
  return buffer;
}