Example usage for org.apache.http.util EntityUtils consumeQuietly

List of usage examples for org.apache.http.util EntityUtils consumeQuietly

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils consumeQuietly.

Prototype

public static void consumeQuietly(HttpEntity httpEntity) 

Source Link

Usage

From source file:outfox.dict.contest.util.HttpToolKit.java

public static void closeQuiet(HttpResponse response) {
    if (response != null) {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

From source file:org.apache.aurora.scheduler.events.Webhook.java

/**
 * Watches all TaskStateChanges and send them best effort to a configured endpoint.
 * <p>// ww w.  jav  a2s.c o  m
 * This is used to expose an external event bus.
 *
 * @param stateChange State change notification.
 */
@Subscribe
public void taskChangedState(TaskStateChange stateChange) {
    LOG.debug("Got an event: {}", stateChange.toString());
    // Old state is not present because a scheduler just failed over. In that case we do not want to
    // resend the entire state.
    if (stateChange.getOldState().isPresent()) {
        try {
            HttpPost post = createPostRequest(stateChange);
            // Using try-with-resources on closeable and following
            // https://hc.apache.org/httpcomponents-client-4.5.x/quickstart.html to make sure stream is
            // closed after we get back a response to not leak http connections.
            try (CloseableHttpResponse httpResponse = httpClient.execute(post)) {
                HttpEntity entity = httpResponse.getEntity();
                EntityUtils.consumeQuietly(entity);
            } catch (IOException exp) {
                LOG.error("Error sending a Webhook event", exp);
            }
        } catch (UnsupportedEncodingException exp) {
            LOG.error("HttpPost exception when creating an HTTP Post request", exp);
        }
    }
}

From source file:Control.SenderMsgToCentralServer.java

public void streamIsTerminatedOK(String idGephi, String jobStart, String app)
        throws URISyntaxException, IOException {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    URIBuilder builder = new URIBuilder();
    builder.setScheme("http")
            .setHost(Admin.ipServerDispatch() + "webresources/CommunicationServers/TerminatedOK")
            .setParameter("jobStart", jobStart).setParameter("idGephi", idGephi).setParameter("app", app);
    URI uri = builder.build();/*from   ww w.j a v a2s  .co m*/
    System.out.println("uri: " + uri);
    HttpGet httpget = new HttpGet(uri);

    HttpResponse response;
    HttpEntity entity;
    int codeStatus = 0;
    int attempts = 0;
    boolean success = false;

    while (!success && attempts < 4) {
        attempts++;

        response = httpclient.execute(httpget);
        entity = response.getEntity();
        EntityUtils.consumeQuietly(entity);
        codeStatus = response.getStatusLine().getStatusCode();
        success = (codeStatus == 200);
    }
    if (!success) {
        System.out.println(
                "server dispatcher could not be reached to tell about job termination - 3 failed attempts.");
    } else {
        System.out.println("message correctly sent to server dispatcherabout cloudbees job termination");

    }
}

From source file:org.esigate.cas.CasAuthenticationHandler.java

@Override
public boolean event(EventDefinition id, Event event) {
    if (EventManager.EVENT_FRAGMENT_POST.equals(id)) {
        FragmentEvent e = (FragmentEvent) event;
        IncomingRequest incomingRequest = e.getOriginalRequest();
        CloseableHttpResponse httpResponse = e.getHttpResponse();
        if (isRedirectToCasServer(httpResponse)) {
            if (getCasAuthentication(incomingRequest) != null) {
                LOG.debug("CAS authentication required for {}", e);
                EntityUtils.consumeQuietly(e.getHttpResponse().getEntity());
                e.setHttpResponse(null);
                addCasAuthentication(e.getHttpRequest(), e.getOriginalRequest());
                try {
                    LOG.debug("Sending new request {}", e);
                    e.setHttpResponse(this.driver.getRequestExecutor().execute(e.getHttpRequest()));
                } catch (HttpErrorPage e1) {
                    e.setHttpResponse(e1.getHttpResponse());
                }/*from   w w  w . j a  va  2 s.co  m*/
            } else {
                LOG.debug("CAS authentication required but we are not authenticated for {}", e);
                e.setHttpResponse(HttpErrorPage.generateHttpResponse(HttpStatus.SC_UNAUTHORIZED,
                        "CAS authentication required"));
            }
        }
    }
    return true;
}

From source file:org.hawkular.component.pinger.Pinger.java

/**
 * Performs a test request against the given {@link PingDestination}.
 *
 * @param destination the destination to ping
 * @return a {@link Future}//from ww w.ja va2 s. c o  m
 */
@Asynchronous
public Future<PingStatus> ping(final PingDestination destination) {
    Log.LOG.debugf("About to ping %s", destination.getUrl());
    HttpUriRequest request = RequestBuilder.create(destination.getMethod()).setUri(destination.getUrl())
            .build();

    try (CloseableHttpClient client = getHttpClient(destination.getUrl())) {
        long start = System.currentTimeMillis();
        HttpResponse httpResponse = client.execute(request);
        StatusLine statusLine = httpResponse.getStatusLine();
        EntityUtils.consumeQuietly(httpResponse.getEntity());
        long now = System.currentTimeMillis();

        final int code = statusLine.getStatusCode();
        final int duration = (int) (now - start);
        Traits traits = Traits.collect(httpResponse, now);
        PingStatus result = new PingStatus(destination, code, now, duration, traits);
        Log.LOG.debugf("Got status code %d from %s", code, destination.getUrl());
        return new AsyncResult<>(result);
    } catch (UnknownHostException e) {
        PingStatus result = PingStatus.error(destination, 404, System.currentTimeMillis());
        Log.LOG.debugf("Got UnknownHostException for %s", destination.getUrl());
        return new AsyncResult<>(result);
    } catch (IOException e) {
        Log.LOG.dCouldNotPingUrl(destination.getUrl(), e.getMessage());
        PingStatus result = PingStatus.error(destination, 500, System.currentTimeMillis());
        return new AsyncResult<>(result);
    }

}

From source file:io.wcm.caravan.io.http.impl.ApacheHttpClient.java

@Override
public Observable<CaravanHttpResponse> execute(CaravanHttpRequest request) {
    return Observable.create(new Observable.OnSubscribe<CaravanHttpResponse>() {

        @Override//from   w w  w. j  a  va2 s  .c om
        public void call(final Subscriber<? super CaravanHttpResponse> subscriber) {
            HttpUriRequest httpRequest = RequestUtil.buildHttpRequest(request);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Execute: {},\n{},\n{}", httpRequest.getURI(), request.toString(),
                        request.getCorrelationId());
            }

            CloseableHttpClient httpClient = (CloseableHttpClient) httpClientFactory.get(httpRequest.getURI());

            long start = System.currentTimeMillis();
            try (CloseableHttpResponse result = httpClient.execute(httpRequest)) {

                StatusLine status = result.getStatusLine();
                HttpEntity entity = new BufferedHttpEntity(result.getEntity());
                EntityUtils.consume(entity);

                boolean throwExceptionForStatus500 = CaravanHttpServiceConfigValidator
                        .throwExceptionForStatus500(request.getServiceId());
                if (status.getStatusCode() >= 500 && throwExceptionForStatus500) {
                    IllegalResponseRuntimeException illegalResponseRuntimeException = new IllegalResponseRuntimeException(
                            request, httpRequest.getURI().toString(), status.getStatusCode(),
                            EntityUtils.toString(entity),
                            "Executing '" + httpRequest.getURI() + "' failed: " + result.getStatusLine());

                    subscriber.onError(illegalResponseRuntimeException);
                    EntityUtils.consumeQuietly(entity);
                } else {

                    CaravanHttpResponse response = new CaravanHttpResponseBuilder()
                            .status(status.getStatusCode()).reason(status.getReasonPhrase())
                            .headers(RequestUtil.toHeadersMap(result.getAllHeaders()))
                            .body(entity.getContent(),
                                    entity.getContentLength() > 0 ? (int) entity.getContentLength() : null)
                            .build();

                    subscriber.onNext(response);
                    subscriber.onCompleted();
                }
            } catch (SocketTimeoutException ex) {
                subscriber.onError(new IOException("Socket timeout executing '" + httpRequest.getURI(), ex));
            } catch (IOException ex) {
                subscriber.onError(new IOException("Executing '" + httpRequest.getURI() + "' failed", ex));
            } catch (Throwable ex) {
                subscriber.onError(
                        new IOException("Reading response of '" + httpRequest.getURI() + "' failed", ex));
            } finally {
                LOG.debug("Took {} ms to load {},\n{}", (System.currentTimeMillis() - start),
                        httpRequest.getURI().toString(), request.getCorrelationId());
            }
        }
    });
}

From source file:com.vmware.photon.controller.model.adapters.vsphere.vapi.VapiClient.java

protected RpcResponse rpc(RpcRequest request) throws IOException {
    HttpPost post = new HttpPost(this.uri);

    post.setHeader(HttpHeaders.ACCEPT, "application/vnd.vmware.vapi.framed,application/json");
    post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

    post.setEntity(new StringEntity(request.toJsonString()));
    HttpResponse httpResponse = null;/*from   w  w  w  . ja  v a 2 s.  c o m*/

    try {
        httpResponse = this.client.execute(post);
        InputStream stream = httpResponse.getEntity().getContent();
        return MAPPER.readValue(stream, RpcResponse.class);
    } finally {
        if (httpResponse != null) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    }
}

From source file:de.ii.xtraplatform.ogc.csw.parser.ExtractWFSUrlsFromCSW.java

public CSWCapabilitiesAnalyzer caps(String url) {
    CSWAdapter adapter = new CSWAdapter(url);
    adapter.initialize(httpClient, httpClient);

    CSWOperation getCapabilities = new CSWOperationGetCapabilities();
    CSWCapabilitiesAnalyzer capabilitiesAnalyzer = new CSWCapabilitiesAnalyzer();
    LoggingWfsCapabilitiesAnalyzer capabilitiesAnalyzer1 = new LoggingWfsCapabilitiesAnalyzer();
    MultiWfsCapabilitiesAnalyzer capabilitiesAnalyzer2 = new MultiWfsCapabilitiesAnalyzer(capabilitiesAnalyzer,
            capabilitiesAnalyzer1);//from w  ww.j ava2s .com
    de.ii.xtraplatform.ogc.api.wfs.parser.WFSCapabilitiesParser wfsCapabilitiesParser = new WFSCapabilitiesParser(
            capabilitiesAnalyzer, staxFactory);

    CSWRequest request = new CSWRequest(adapter, getCapabilities);

    HttpEntity entity = null;

    try {
        entity = request.getResponse().get();

        /*String readLine;
        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
                
        while (((readLine = br.readLine()) != null)) {
        System.out.println(readLine);
                
                
        }*/

        wfsCapabilitiesParser.parse(entity);

        System.out.println();
        System.out.println();
        System.out.println(capabilitiesAnalyzer.title);
        System.out.println(capabilitiesAnalyzer.version);
        System.out.println(capabilitiesAnalyzer.url);
        System.out.println(capabilitiesAnalyzer.outputFormats.toString());
        System.out.println(capabilitiesAnalyzer.typeNames.toString());
        System.out.println(capabilitiesAnalyzer.constraintLanguages.toString());
        System.out.println(capabilitiesAnalyzer.isoQueryables.toString());
        System.out.println();

    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    } finally {
        EntityUtils.consumeQuietly(entity);
    }

    return capabilitiesAnalyzer;
}

From source file:io.wcm.devops.maven.nodejsproxy.resource.MavenProxyResource.java

/**
 * Maps POM requests simulating a Maven 2 directory structure.
 * @throws IOException/*ww w  . j  a v a  2 s  .co  m*/
 */
@GET
@Path("{groupIdPath:[a-zA-Z0-9\\-\\_]+(/[a-zA-Z0-9\\-\\_]+)*}" + "/{artifactId:[a-zA-Z0-9\\-\\_\\.]+}"
        + "/{version:\\d+(\\.\\d+)*}" + "/{artifactIdFilename:[a-zA-Z0-9\\-\\_\\.]+}"
        + "-{versionFilename:\\d+(\\.\\d+)*}" + ".{fileExtension:pom(\\.sha1)?}")
@Timed
public Response getPom(@PathParam("groupIdPath") String groupIdPath, @PathParam("artifactId") String artifactId,
        @PathParam("version") String version, @PathParam("artifactIdFilename") String artifactIdFilename,
        @PathParam("versionFilename") String versionFilename, @PathParam("fileExtension") String fileExtension)
        throws IOException {

    String groupId = mapGroupId(groupIdPath);
    if (!validateBasicParams(groupId, artifactId, version, artifactIdFilename, versionFilename)) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    ArtifactType artifactType = getArtifactType(artifactId);

    // validate that version exists
    String url = getPomValidateUrl(artifactType, version);
    log.info("Validate file: {}", url);
    HttpHead get = new HttpHead(url);
    HttpResponse response = httpClient.execute(get);
    try {
        if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }

    String xml = PomBuilder.build(groupId, artifactId, version, "pom");

    if (StringUtils.equals(fileExtension, "pom")) {
        return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
    }
    if (StringUtils.equals(fileExtension, "pom.sha1")) {
        return Response.ok(DigestUtils.sha1Hex(xml)).type(MediaType.TEXT_PLAIN).build();
    }
    return Response.status(Response.Status.NOT_FOUND).build();
}

From source file:org.apache.deltaspike.test.servlet.impl.event.session.SessionEventsTest.java

/**
 * First send a request to a standard resource which won't create a user session
 *//*from w  ww. ja  v a2s  .c o  m*/
@Test
@RunAsClient
@InSequence(1)
public void sendStatelessRequest(@ArquillianResource URL contextPath) throws Exception {
    String url = new URL(contextPath, "foobar.txt").toString();
    HttpResponse response = client.execute(new HttpGet(url));
    assertEquals(200, response.getStatusLine().getStatusCode());
    EntityUtils.consumeQuietly(response.getEntity());
}