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

The following examples show how to use com.google.common.io.ByteStreams#exhaust() . 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: ExhaustRequestFilter.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@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 2
Source File: ApacheHttpClientPluginIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: ApacheHttpClientPluginIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@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
Source File: FirebaseInstanceId.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
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 5
Source File: ConsumingInputStream.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws IOException {
  if (!closed && in != null) {
    try {
      ByteStreams.exhaust(this);
      super.in.close();
    } finally {
      this.closed = true;
    }
  }
}
 
Example 6
Source File: ApacheHttpClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@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
Source File: ApacheHttpClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@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 File: HttpURLConnectionIT.java    From glowroot with 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 File: HttpURLConnectionIT.java    From glowroot with 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 File: HttpURLConnectionIT.java    From glowroot with 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 File: WebDriverSetup.java    From glowroot with 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 File: WebDriverIT.java    From glowroot with 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 File: HttpConnector.java    From bazel with 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 File: HttpStreamTest.java    From bazel with 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
Source File: FileServiceTest.java    From armeria with 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 16
Source File: GoogleGuavaUtils.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public long getInputStreamSize(InputStream is) throws IOException {
	return ByteStreams.exhaust(is);
}
 
Example 17
Source File: JarDumper.java    From buck with 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()));
  }
}