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

The following examples show how to use io.vertx.core.buffer.Buffer#toString() . 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: XhrTransport.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private void handleSendMessage(RoutingContext rc, SockJSSession session, Buffer body) {
  String msgs = body.toString();
  if (msgs.equals("")) {
    rc.response().setStatusCode(500);
    rc.response().end("Payload expected.");
    return;
  }
  if (!session.handleMessages(msgs)) {
    sendInvalidJSON(rc.response());
  } else {
    rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/plain; charset=UTF-8");
    setNoCacheHeaders(rc);
    setJSESSIONID(options, rc);
    setCORS(rc);
    rc.response().setStatusCode(204);
    rc.response().end();
  }
  if (log.isTraceEnabled()) log.trace("XHR send processed ok");
}
 
Example 2
Source File: ScuttlebuttLocalDiscoveryService.java    From cava with Apache License 2.0 6 votes vote down vote up
void listen(DatagramPacket datagramPacket) {
  logger.debug("Received new packet from {}", datagramPacket.sender());
  Buffer buffer = datagramPacket.data();
  if (buffer.length() > 100) {
    logger.debug("Packet too long, disregard");
    return;
  }
  String packetString = buffer.toString();
  try {
    LocalIdentity id = LocalIdentity.fromString(packetString);
    for (Consumer<LocalIdentity> listener : listeners) {
      listener.accept(id);
    }
  } catch (IllegalArgumentException e) {
    logger.debug("Invalid identity payload {}", packetString);
  }
}
 
Example 3
Source File: ErrorHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private void checkHtmlResponse(Buffer buff, HttpClientResponse resp, int statusCode, String statusMessage,
                               Exception e, boolean displayExceptionDetails) {
  assertEquals("text/html", resp.headers().get(HttpHeaders.CONTENT_TYPE));
  String page = buff.toString();
  assertTrue(page.startsWith("<html>"));
  assertTrue(page.contains(String.valueOf(statusCode)));
  assertTrue(page.contains(statusMessage));
  assertTrue(page.contains("An unexpected error occurred"));
  if (e != null) {
    if (displayExceptionDetails) {
      assertTrue(page.contains(e.getStackTrace()[0].toString()));
    } else {
      assertFalse(page.contains(e.getStackTrace()[0].toString()));
    }
  }
}
 
Example 4
Source File: EdgeSignatureResponseFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeSendResponse(Invocation invocation, HttpServletResponseEx responseEx) {
  if (invocation == null) {
    return;
  }

  EncryptContext encryptContext = (EncryptContext) invocation.getHandlerContext().get(EdgeConst.ENCRYPT_CONTEXT);
  if (encryptContext == null) {
    return;
  }
  Hcr hcr = encryptContext.getHcr();

  // bad practice: it's better to set signature in response header
  Buffer bodyBuffer = responseEx.getBodyBuffer();
  String body = bodyBuffer.toString();
  if (body.endsWith("}")) {
    Hasher hasher = Hashing.sha256().newHasher();
    hasher.putString(hcr.getSignatureKey(), StandardCharsets.UTF_8);
    hasher.putString(body, StandardCharsets.UTF_8);
    String signature = hasher.hash().toString();
    LOGGER.info("beforeSendResponse signature: {}", signature);

    body = body.substring(0, body.length() - 1) + ",\"signature\":\"" + signature + "\"}";
    responseEx.setBodyBuffer(Buffer.buffer(body));
  }
}
 
Example 5
Source File: EdgeSignatureResponseFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeSendResponse(Invocation invocation, HttpServletResponseEx responseEx) {
  if (invocation == null) {
    return;
  }

  EncryptContext encryptContext = (EncryptContext) invocation.getHandlerContext().get(EdgeConst.ENCRYPT_CONTEXT);
  if (encryptContext == null) {
    return;
  }
  Hcr hcr = encryptContext.getHcr();

  // bad practice: it's better to set signature in response header
  Buffer bodyBuffer = responseEx.getBodyBuffer();
  String body = bodyBuffer.toString();
  if (body.endsWith("}")) {
    Hasher hasher = Hashing.sha256().newHasher();
    hasher.putString(hcr.getSignatureKey(), StandardCharsets.UTF_8);
    hasher.putString(body, StandardCharsets.UTF_8);
    String signature = hasher.hash().toString();
    LOGGER.info("beforeSendResponse signature: {}", signature);

    body = body.substring(0, body.length() - 1) + ",\"signature\":\"" + signature + "\"}";
    responseEx.setBodyBuffer(Buffer.buffer(body));
  }
}
 
Example 6
Source File: SSEPacket.java    From vertx-sse with Apache License 2.0 6 votes vote down vote up
boolean append(Buffer buffer) {
	String response = buffer.toString();
	boolean willTerminate = response.endsWith(END_OF_PACKET);
	String[] lines = response.split(LINE_SEPARATOR);
	for (int i = 0; i < lines.length; i++) {
		final String line = lines[i];
		int idx = line.indexOf(FIELD_SEPARATOR);
		if (idx == -1) {
			continue; // ignore line
		}
		final String type = line.substring(0, idx);
		final String data = line.substring(idx + 2, line.length());
		if (i == 0 && headerName == null && !"data".equals(type)) {
			headerName = type;
			headerValue = data;
		} else {
			payload.append(data).append(LINE_SEPARATOR);
		}
	}
	return willTerminate;
}
 
Example 7
Source File: ScuttlebuttLocalDiscoveryService.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
void listen(DatagramPacket datagramPacket) {
  logger.debug("Received new packet from {}", datagramPacket.sender());
  Buffer buffer = datagramPacket.data();
  if (buffer.length() > 100) {
    logger.debug("Packet too long, disregard");
    return;
  }
  String packetString = buffer.toString();
  try {
    LocalIdentity id = LocalIdentity.fromString(packetString);
    for (Consumer<LocalIdentity> listener : listeners) {
      listener.accept(id);
    }
  } catch (IllegalArgumentException e) {
    logger.debug("Invalid identity payload {}", packetString);
  }
}
 
Example 8
Source File: KeyStoreHelper.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
private static <P> List<P> loadPems(Buffer data, BiFunction<String, byte[], Collection<P>> pemFact) throws IOException {
    String pem = data.toString();
    if (pem.contains("EC PARAMETERS")) {
        return new ArrayList<>(pemFact.apply("EC PRIVATE KEY", pem.getBytes()));
    }
    List<P> pems = new ArrayList<>();
    Matcher beginMatcher = BEGIN_PATTERN.matcher(pem);
    Matcher endMatcher = END_PATTERN.matcher(pem);
    while (true) {
        boolean begin = beginMatcher.find();
        if (!begin) {
            break;
        }
        String beginDelimiter = beginMatcher.group(1);
        boolean end = endMatcher.find();
        if (!end) {
            throw new RuntimeException("Missing -----END " + beginDelimiter + "----- delimiter");
        } else {
            String endDelimiter = endMatcher.group(1);
            if (!beginDelimiter.equals(endDelimiter)) {
                throw new RuntimeException("Missing -----END " + beginDelimiter + "----- delimiter");
            } else {
                String content = pem.substring(beginMatcher.end(), endMatcher.start());
                content = content.replaceAll("\\s", "");
                if (content.length() == 0) {
                    throw new RuntimeException("Empty pem file");
                }
                Collection<P> pemItems = pemFact.apply(endDelimiter, Base64.getDecoder().decode(content));
                pems.addAll(pemItems);
            }
        }
    }
    return pems;
}
 
Example 9
Source File: ProxyService.java    From okapi with Apache License 2.0 5 votes vote down vote up
private void proxyInternalBuffer(
    Iterator<ModuleInstance> it,
    ProxyContext pc, Buffer bcontent, List<HttpClientRequest> clientRequestList,
    ModuleInstance mi) {
  String req = bcontent.toString();
  pc.debug("proxyInternalBuffer " + req);
  RoutingContext ctx = pc.getCtx();

  for (HttpClientRequest r : clientRequestList) {
    r.end(bcontent);
  }
  internalModule.internalService(req, pc, res -> {
    if (res.failed()) {
      pc.responseError(res.getType(), res.cause());
      return;
    }
    String resp = res.result();
    int statusCode = pc.getCtx().response().getStatusCode();
    if (statusCode == 200 && resp.isEmpty()) {
      // Say "no content", if there isn't any
      statusCode = 204;
      pc.getCtx().response().setStatusCode(statusCode);
    }
    Buffer respBuf = Buffer.buffer(resp);
    pc.setHandlerRes(statusCode);
    makeTraceHeader(mi, statusCode, pc);
    if (it.hasNext()) { // carry on with the pipeline
      proxyR(it, pc, null, respBuf, new LinkedList<>());
    } else { // produce a result
      pc.closeTimer();
      ctx.response().end(respBuf);
    }
  });
}
 
Example 10
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");
            });
    }
 
Example 11
Source File: MultilineParser.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
boolean isFinalLine(final Buffer buffer) {
  String line = buffer.toString();
  if (line.contains("\n")) {
    String[] lines = line.split("\n");
    line = lines[lines.length - 1];
  }
  return !STATUS_LINE_CONTINUE.matcher(line).matches();
}
 
Example 12
Source File: BufferToJsonArray.java    From sfs with Apache License 2.0 4 votes vote down vote up
@Override
public JsonArray call(Buffer buffer) {
    return new JsonArray(buffer.toString(UTF_8.toString()));
}
 
Example 13
Source File: ReadStreamAdapterBackPressureTest.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
@Override
protected String string(Buffer buffer) {
  return buffer.toString("UTF-8");
}
 
Example 14
Source File: EventBusBridgeTestBase.java    From nubes with Apache License 2.0 4 votes vote down vote up
protected void assertAccessRefused(TestContext context, Buffer buffer) {
  JsonObject resp = new JsonObject(buffer.toString("UTF-8"));
  context.assertEquals("err", resp.getString("type"));
  context.assertEquals("access_denied", resp.getString("body"));
}
 
Example 15
Source File: ErrorHandlerTest.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private void checkJsonResponse(Buffer buff, HttpClientResponse resp, int statusCode, String statusMessage) {
  assertEquals("application/json", resp.headers().get(HttpHeaders.CONTENT_TYPE));
  String page = buff.toString();
  assertEquals("{\"error\":{\"code\":" + statusCode +",\"message\":\"" + statusMessage + "\"}}", page);
}
 
Example 16
Source File: ApiServiceImpl.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
private String fetchApiDefinitionContentFromURL(String apiDefinitionOrURL) {
    UrlSanitizerUtils.checkAllowed(apiDefinitionOrURL, importConfiguration.getImportWhitelist(), importConfiguration.isAllowImportFromPrivate());
    Buffer buffer = httpClientService.request(HttpMethod.GET, apiDefinitionOrURL, null, null, null);
    return buffer.toString();
}
 
Example 17
Source File: MethodReference.java    From vertx-codetrans with Apache License 2.0 4 votes vote down vote up
private void appendString(String s) {
  Buffer buffer = Buffer.buffer("hello");
  buffer.appendString(s);
  MethodExpressionTest.helloworld = buffer.toString("UTF-8");
}
 
Example 18
Source File: BufferToString.java    From sfs with Apache License 2.0 4 votes vote down vote up
@Override
public String call(Buffer buffer) {
    return buffer.toString(charset.toString());
}
 
Example 19
Source File: MethodReference.java    From vertx-codetrans with Apache License 2.0 4 votes vote down vote up
@CodeTranslate
public void methodReference() throws Exception {
  Buffer buffer = Buffer.buffer("hello");
  HandlerInvoker.invokeStringHandler(buffer::appendString);
  MethodExpressionTest.helloworld = buffer.toString("UTF-8");
}
 
Example 20
Source File: PemReader.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
private static List<Entry> readAllFromBuffer(final Buffer buffer) throws IOException {

        // read data as string

        final String string = buffer.toString(StandardCharsets.US_ASCII);

        // parse PEM

        return readAll(new StringReader(string));
    }