public String greet(Person... people) {
   StringBuilder builder = new StringBuilder("Hello");
   for (Person p : people) {
     builder.append(" ").append(p.name).append("!");
   }
   return builder.toString();
 }
 private String readFully(Reader reader) throws IOException {
   StringBuilder buffer = new StringBuilder();
   int ch;
   while ((ch = reader.read()) != -1) {
     buffer.append((char) ch);
   }
   return buffer.toString();
 }
Example #3
0
 public String readResponseHeader() throws IOException {
   InputStreamReader isr = new InputStreamReader(in);
   BufferedReader reader = new BufferedReader(isr);
   StringBuilder header = new StringBuilder();
   // Read the response header
   String line = reader.readLine();
   Assert.assertNotNull(line);
   Assert.assertThat(line, startsWith("HTTP/1.1 "));
   header.append(line).append("\r\n");
   while ((line = reader.readLine()) != null) {
     if (line.trim().length() == 0) {
       break;
     }
     header.append(line).append("\r\n");
   }
   return header.toString();
 }
 private List<String> consume(HadoopDataSourceCore core, List<DirectInputFragment> fragments)
     throws IOException, InterruptedException {
   List<String> results = new ArrayList<String>();
   for (DirectInputFragment fragment : fragments) {
     ModelInput<StringBuilder> input =
         core.openInput(StringBuilder.class, format, fragment, counter);
     try {
       StringBuilder buf = new StringBuilder();
       while (input.readTo(buf)) {
         results.add(buf.toString());
       }
     } finally {
       input.close();
     }
   }
   return results;
 }
    @Override
    public void onWebSocketText(String message) {
      LOG.debug("onWebSocketText({})", message);
      calls.incrementAndGet();
      if (message.equalsIgnoreCase("openSessions")) {
        Collection<WebSocketSession> sessions = container.getOpenSessions();

        StringBuilder ret = new StringBuilder();
        ret.append("openSessions.size=").append(sessions.size()).append('\n');
        int idx = 0;
        for (WebSocketSession sess : sessions) {
          ret.append('[').append(idx++).append("] ").append(sess.toString()).append('\n');
        }
        session.getRemote().sendStringByFuture(ret.toString());
        session.close(StatusCode.NORMAL, "ContainerSocket");
      } else if (message.equalsIgnoreCase("calls")) {
        session.getRemote().sendStringByFuture(String.format("calls=%,d", calls.get()));
      }
    }
  @Test
  public void testAsync2() throws Exception {
    StringBuilder request = new StringBuilder(512);
    request
        .append("GET /ctx/path2/info HTTP/1.1\r\n")
        .append("Host: localhost\r\n")
        .append("Connection: close\r\n")
        .append("\r\n");

    int port = _port;
    List<String> list = new ArrayList<>();
    try (Socket socket = new Socket("localhost", port)) {
      socket.setSoTimeout(1000000);
      OutputStream out = socket.getOutputStream();
      out.write(request.toString().getBytes(StandardCharsets.ISO_8859_1));

      BufferedReader in =
          new BufferedReader(new InputStreamReader(socket.getInputStream()), 102400);

      // response line
      String line = in.readLine();
      LOG.debug("response-line: " + line);
      Assert.assertThat(line, startsWith("HTTP/1.1 200 OK"));

      // Skip headers
      while (line != null) {
        line = in.readLine();
        LOG.debug("header-line: " + line);
        if (line.length() == 0) break;
      }

      // Get body slowly
      while (true) {
        line = in.readLine();
        LOG.debug("body: " + line);
        if (line == null) break;
        list.add(line);
      }
    }

    Assert.assertEquals(list.get(0), "data");
    Assert.assertTrue(_servlet2.completed.await(5, TimeUnit.SECONDS));
  }
    @OnMessage
    public String getHeaders(Session session, String headerKey) {
      StringBuilder response = new StringBuilder();

      response.append("Request Header [").append(headerKey).append("]: ");
      @SuppressWarnings("unchecked")
      Map<String, List<String>> headers =
          (Map<String, List<String>>) session.getUserProperties().get("request-headers");
      if (headers == null) {
        response.append("<no headers found in session.getUserProperties()>");
      } else {
        List<String> values = headers.get(headerKey);
        if (values == null) {
          response.append("<header not found>");
        } else {
          response.append(QuoteUtil.join(values, ","));
        }
      }

      return response.toString();
    }
  @Test
  public void realtimeGetWithCompress() throws Exception {
    client.admin().indices().prepareDelete().execute().actionGet();

    client
        .admin()
        .indices()
        .prepareCreate("test")
        .setSettings(ImmutableSettings.settingsBuilder().put("index.refresh_interval", -1))
        .addMapping(
            "type",
            jsonBuilder()
                .startObject()
                .startObject("type")
                .startObject("_source")
                .field("compress", true)
                .endObject()
                .endObject()
                .endObject())
        .execute()
        .actionGet();

    ClusterHealthResponse clusterHealth =
        client.admin().cluster().health(clusterHealthRequest().waitForGreenStatus()).actionGet();
    assertThat(clusterHealth.isTimedOut(), equalTo(false));
    assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10000; i++) {
      sb.append((char) i);
    }
    String fieldValue = sb.toString();
    client.prepareIndex("test", "type", "1").setSource("field", fieldValue).execute().actionGet();

    // realtime get
    GetResponse getResponse = client.prepareGet("test", "type", "1").execute().actionGet();
    assertThat(getResponse.isExists(), equalTo(true));
    assertThat(getResponse.getSourceAsMap().get("field").toString(), equalTo(fieldValue));
  }
Example #9
0
  public void sendStandardRequest() throws IOException {
    StringBuilder req = new StringBuilder();
    req.append("GET /chat HTTP/1.1\r\n");
    req.append("Host: ").append(destHttpURI.getHost());
    if (destHttpURI.getPort() > 0) {
      req.append(':').append(destHttpURI.getPort());
    }
    req.append("\r\n");
    req.append("Upgrade: websocket\r\n");
    req.append("Connection: Upgrade\r\n");
    req.append("Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n");
    req.append("Sec-WebSocket-Origin: ").append(destWebsocketURI.toASCIIString()).append("\r\n");
    if (StringUtil.isNotBlank(protocols)) {
      req.append("Sec-WebSocket-Protocol: ").append(protocols).append("\r\n");
    }

    for (String xtension : extensions) {
      req.append("Sec-WebSocket-Extensions: ").append(xtension).append("\r\n");
    }
    req.append("Sec-WebSocket-Version: ").append(version).append("\r\n");
    req.append("\r\n");
    writeRaw(req.toString());
  }
    Properties loadProfile() throws IOException {
      Properties result = load("profile-template.properties");
      result.putAll(override);

      for (Map.Entry<Object, Object> entry : result.entrySet()) {
        String value = (String) entry.getValue();
        StringBuilder buf = new StringBuilder();
        int start = 0;
        Matcher matcher = PLACEHOLDER.matcher(value);
        while (matcher.find(start)) {
          buf.append(value.subSequence(start, matcher.start()));
          String rep = replacement.get(matcher.group(1));
          if (rep == null) {
            throw new AssertionError(matcher.group(1));
          }
          buf.append(rep);
          start = matcher.end();
        }
        buf.append(value.substring(start));
        entry.setValue(buf.toString());
      }

      return result;
    }
  public synchronized List<String> process(byte[] content, int... writes) throws Exception {
    StringBuilder request = new StringBuilder(512);
    request.append("GET /ctx/path/info");
    char s = '?';
    for (int w : writes) {
      request.append(s).append("w=").append(w);
      s = '&';
    }

    request.append(" HTTP/1.1\r\n").append("Host: localhost\r\n").append("Connection: close\r\n");

    if (content != null)
      request
          .append("Content-Length: ")
          .append(content.length)
          .append("\r\n")
          .append("Content-Type: text/plain\r\n");

    request.append("\r\n");

    int port = _port;
    List<String> list = new ArrayList<>();
    try (Socket socket = new Socket("localhost", port)) {
      socket.setSoTimeout(1000000);
      OutputStream out = socket.getOutputStream();
      out.write(request.toString().getBytes(StandardCharsets.ISO_8859_1));

      if (content != null && content.length > 0) {
        Thread.sleep(100);
        out.write(content[0]);
        Thread.sleep(100);
        int half = (content.length - 1) / 2;
        out.write(content, 1, half);
        Thread.sleep(100);
        out.write(content, 1 + half, content.length - half - 1);
      }

      BufferedReader in =
          new BufferedReader(new InputStreamReader(socket.getInputStream()), 102400);

      // response line
      String line = in.readLine();
      LOG.debug("response-line: " + line);
      Assert.assertThat(line, startsWith("HTTP/1.1 200 OK"));

      // Skip headers
      while (line != null) {
        line = in.readLine();
        LOG.debug("header-line:  " + line);
        if (line.length() == 0) break;
      }

      // Get body slowly
      while (true) {
        line = in.readLine();
        if (line == null) break;
        LOG.debug("body:  " + brief(line));
        list.add(line);
        Thread.sleep(50);
      }
    }

    // check lines
    int w = 0;
    for (String line : list) {
      LOG.debug("line:  " + brief(line));
      if ("-".equals(line)) continue;
      assertEquals("Line Length", writes[w], line.length());
      assertEquals("Line Contents", line.charAt(0), '0' + (w % 10));

      w++;
      if (w < writes.length && writes[w] <= 0) w++;
    }

    if (content != null) Assert.assertEquals("Content Length", content.length, _read.get());

    return list;
  }