Java Code Examples for com.google.common.io.ByteStreams#exhaust()

The following examples show how to use com.google.common.io.ByteStreams#exhaust() . These examples are extracted from open source projects. 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
private CallableOperation<Void, FirebaseInstanceIdException> deleteInstanceIdOp(
    final String instanceId) {
  checkArgument(!Strings.isNullOrEmpty(instanceId), "instance ID must not be null or empty");
  return new CallableOperation<Void, FirebaseInstanceIdException>() {
    @Override
    protected Void execute() throws FirebaseInstanceIdException {
      String url = String.format(
          "%s/project/%s/instanceId/%s", IID_SERVICE_URL, projectId, instanceId);
      HttpResponse response = null;
      try {
        HttpRequest request = requestFactory.buildDeleteRequest(new GenericUrl(url));
        request.setParser(new JsonObjectParser(jsonFactory));
        request.setResponseInterceptor(interceptor);
        response = request.execute();
        ByteStreams.exhaust(response.getContent());
      } catch (Exception e) {
        handleError(instanceId, e);
      } finally {
        disconnectQuietly(response);
      }
      return null;
    }
  };
}
 
Example 2
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
    throws IOException, ServletException
{
  try {
    chain.doFilter(request, response);
  }
  finally {
    if (exhaustRequest(request, response)) {
      try (InputStream in = request.getInputStream()) {
        ByteStreams.exhaust(in);
      }
      catch (Exception e) {
        log.debug("Unable to exhaust request", e);
      }
    }
  }
}
 
Example 3
@Override
public void transactionMarker() throws Exception {
    HttpClient httpClient = createHttpClient();
    HttpHost httpHost = new HttpHost("localhost", getPort());
    HttpGet httpGet = new HttpGet("/hello2");
    HttpResponse response = httpClient.execute(httpHost, httpGet);
    int responseStatusCode = response.getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
    InputStream content = response.getEntity().getContent();
    ByteStreams.exhaust(content);
    content.close();
    closeHttpClient(httpClient);
}
 
Example 4
@Override
public void transactionMarker() throws Exception {
    HttpClient httpClient = createHttpClient();
    HttpHost httpHost = new HttpHost("localhost", getPort());
    HttpPost httpPost = new HttpPost("/hello4");
    HttpResponse response = httpClient.execute(httpHost, httpPost);
    int responseStatusCode = response.getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
    InputStream content = response.getEntity().getContent();
    ByteStreams.exhaust(content);
    content.close();
    closeHttpClient(httpClient);
}
 
Example 5
@Override
public void close() throws IOException {
  if (!closed && in != null) {
    try {
      ByteStreams.exhaust(this);
      super.in.close();
    } finally {
      this.closed = true;
    }
  }
}
 
Example 6
@Override
public void transactionMarker() throws Exception {
    HttpClient httpClient = createHttpClient();
    HttpGet httpGet = new HttpGet("http://localhost:" + getPort() + "/hello1");
    HttpResponse response = httpClient.execute(httpGet);
    int responseStatusCode = response.getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
    InputStream content = response.getEntity().getContent();
    ByteStreams.exhaust(content);
    content.close();
    closeHttpClient(httpClient);
}
 
Example 7
@Override
public void transactionMarker() throws Exception {
    HttpClient httpClient = createHttpClient();
    HttpPost httpPost = new HttpPost("http://localhost:" + getPort() + "/hello3");
    HttpResponse response = httpClient.execute(httpPost);
    int responseStatusCode = response.getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
    InputStream content = response.getEntity().getContent();
    ByteStreams.exhaust(content);
    content.close();
    closeHttpClient(httpClient);
}
 
Example 8
Source Project: glowroot   File: HttpURLConnectionIT.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    String protocol = getClass().getName().endsWith("HTTPS") ? "https" : "http";
    URL obj = new URL(protocol + "://localhost:" + getPort() + "/hello1/");
    HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
    InputStream content = connection.getInputStream();
    ByteStreams.exhaust(content);
    content.close();
}
 
Example 9
Source Project: glowroot   File: HttpURLConnectionIT.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    String protocol = getClass().getName().endsWith("HTTPS") ? "https" : "http";
    URL obj = new URL(protocol + "://localhost:" + getPort() + "/hello1?abc=xyz");
    HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
    InputStream content = connection.getInputStream();
    ByteStreams.exhaust(content);
    content.close();
}
 
Example 10
Source Project: glowroot   File: HttpURLConnectionIT.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    String protocol = getClass().getName().endsWith("HTTPS") ? "https" : "http";
    URL obj = new URL(protocol + "://localhost:" + getPort() + "/hello1/");
    HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
    connection.setDoOutput(true);
    connection.getOutputStream().write("some data".getBytes());
    connection.getOutputStream().close();
    InputStream content = connection.getInputStream();
    ByteStreams.exhaust(content);
    content.close();
}
 
Example 11
Source Project: glowroot   File: WebDriverSetup.java    License: Apache License 2.0 5 votes vote down vote up
private static Container createContainer(int uiPort, File testDir) throws Exception {
    File adminFile = new File(testDir, "admin.json");
    Files.asCharSink(adminFile, UTF_8).write("{\"web\":{\"port\":" + uiPort + "}}");
    Container container;
    if (Containers.useJavaagent()) {
        container = new JavaagentContainer(testDir, true, ImmutableList.of());
    } else {
        container = new LocalContainer(testDir, true, ImmutableMap.of());
    }
    // wait for UI to be available (UI starts asynchronously in order to not block startup)
    CloseableHttpClient httpClient = HttpClients.custom()
            .setRedirectStrategy(new DefaultRedirectStrategy())
            .build();
    Stopwatch stopwatch = Stopwatch.createStarted();
    Exception lastException = null;
    while (stopwatch.elapsed(SECONDS) < 10) {
        HttpGet request = new HttpGet("http://localhost:" + uiPort);
        try (CloseableHttpResponse response = httpClient.execute(request);
                InputStream content = response.getEntity().getContent()) {
            ByteStreams.exhaust(content);
            lastException = null;
            break;
        } catch (Exception e) {
            lastException = e;
        }
    }
    httpClient.close();
    if (lastException != null) {
        throw new IllegalStateException("Timed out waiting for Glowroot UI", lastException);
    }
    return container;
}
 
Example 12
Source Project: glowroot   File: WebDriverIT.java    License: Apache License 2.0 5 votes vote down vote up
static void httpPost(String url, String content) throws Exception {
    HttpPost request = new HttpPost(url);
    request.setEntity(new StringEntity(content));
    try (CloseableHttpResponse response = httpClient.execute(request);
            InputStream responseContent = response.getEntity().getContent()) {
        ByteStreams.exhaust(responseContent);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new AssertionError("Unexpected status code: " + statusCode);
        }
    }
}
 
Example 13
Source Project: bazel   File: HttpConnector.java    License: Apache License 2.0 5 votes vote down vote up
private static void readAllBytesAndClose(
    @WillClose @Nullable InputStream stream)
        throws IOException {
  if (stream != null) {
    ByteStreams.exhaust(stream);
    stream.close();
  }
}
 
Example 14
Source Project: bazel   File: HttpStreamTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void bigDataWithInvalidChecksum_throwsIOExceptionAfterCreateOnEof() throws Exception {
  // the probability of this test flaking is 8.6361686e-78
  byte[] bigData = new byte[HttpStream.PRECHECK_BYTES + 70001];
  randoCalrissian.nextBytes(bigData);
  when(connection.getInputStream()).thenReturn(new ByteArrayInputStream(bigData));
  try (HttpStream stream = streamFactory.create(connection, AURL, BAD_CHECKSUM, reconnector)) {
    thrown.expect(IOException.class);
    thrown.expectMessage("Checksum");
    ByteStreams.exhaust(stream);
    fail("Should have thrown error before close()");
  }
}
 
Example 15
@Override
public long getInputStreamSize(InputStream is) throws IOException {
	return ByteStreams.exhaust(is);
}
 
Example 16
Source Project: armeria   File: FileServiceTest.java    License: Apache License 2.0 4 votes vote down vote up
private static void assert304NotModified(
        CloseableHttpClient hc, String baseUri, String path,
        String expectedETag, String expectedLastModified) throws IOException {

    final String uri = baseUri + path;

    // Test if the 'If-None-Match' header works as expected. (a single etag)
    final HttpUriRequest req1 = new HttpGet(uri);
    req1.setHeader(HttpHeaders.IF_NONE_MATCH, expectedETag);

    try (CloseableHttpResponse res = hc.execute(req1)) {
        assert304NotModified(res, expectedETag, expectedLastModified);
    }

    // Test if the 'If-None-Match' header works as expected. (multiple etags)
    final HttpUriRequest req2 = new HttpGet(uri);
    req2.setHeader(HttpHeaders.IF_NONE_MATCH, "\"an-etag-that-never-matches\", " + expectedETag);

    try (CloseableHttpResponse res = hc.execute(req2)) {
        assert304NotModified(res, expectedETag, expectedLastModified);
    }

    // Test if the 'If-None-Match' header works as expected. (an asterisk)
    final HttpUriRequest req3 = new HttpGet(uri);
    req3.setHeader(HttpHeaders.IF_NONE_MATCH, "*");

    try (CloseableHttpResponse res = hc.execute(req3)) {
        assert304NotModified(res, expectedETag, expectedLastModified);
    }

    // Test if the 'If-Modified-Since' header works as expected.
    final HttpUriRequest req4 = new HttpGet(uri);
    req4.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate());

    try (CloseableHttpResponse res = hc.execute(req4)) {
        assert304NotModified(res, expectedETag, expectedLastModified);
    }

    // 'If-Modified-Since' should never be evaluated if 'If-None-Match' exists.
    final HttpUriRequest req5 = new HttpGet(uri);
    req5.setHeader(HttpHeaders.IF_NONE_MATCH, "\"an-etag-that-never-matches\"");
    req5.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate());

    try (CloseableHttpResponse res = hc.execute(req5)) {
        // Should not receive '304 Not Modified' because the etag did not match.
        assertStatusLine(res, "HTTP/1.1 200 OK");

        // Read the content fully so that Apache HC does not close the connection prematurely.
        ByteStreams.exhaust(res.getEntity().getContent());
    }
}
 
Example 17
Source Project: buck   File: JarDumper.java    License: Apache License 2.0 4 votes vote down vote up
private Stream<String> dumpBinaryFile(String name, InputStream inputStream) throws IOException {
  try (HashingInputStream is = new HashingInputStream(Hashing.murmur3_128(), inputStream)) {
    ByteStreams.exhaust(is);
    return Stream.of(String.format("Murmur3-128 of %s: %s", name, is.hash().toString()));
  }
}