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:org.jboss.as.test.integration.security.picketlink.SAML2KerberosAuthenticationTestCase.java

private static void consumeResponse(final HttpResponse response) {
    HttpEntity entity = response.getEntity();
    EntityUtils.consumeQuietly(entity);
}

From source file:com.terracotta.nrplugin.rest.nr.MetricReporter.java

private void doReportMetrics() {
    if (StateManager.TmcState.available.equals(stateManager.getTmcState())) {
        try {/*from w  ww .  ja va2 s  . c o  m*/
            NewRelicPayload newRelicPayload = metricProvider.assemblePayload();
            log.info("Attempting to report stats to NewRelic...");
            if (nrRequestLog.isDebugEnabled()) {
                try {
                    nrRequestLog.debug(new ObjectMapper().writeValueAsString(newRelicPayload));
                } catch (JsonProcessingException e) {
                    log.error("Error serializing payload.", e);
                }
            }

            String json = mapper.writeValueAsString(newRelicPayload);
            HttpHost target = new HttpHost(nrHost, nrPort, nrScheme);
            HttpPost httpPost = new HttpPost(nrPath);
            httpPost.setEntity(new StringEntity(json));
            httpPost.setHeader(X_LICENSE_KEY, licenseKey);
            httpPost.setHeader(org.apache.http.HttpHeaders.CONTENT_TYPE,
                    ContentType.APPLICATION_JSON.getMimeType());
            httpPost.setHeader(org.apache.http.HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
            CloseableHttpResponse response = httpClient.execute(target, httpPost);
            log.info("New Relic Response code: " + response.getStatusLine().getStatusCode());
            if (log.isDebugEnabled()) {
                log.debug("Received response: " + EntityUtils.toString(response.getEntity()));
            }
            EntityUtils.consumeQuietly(response.getEntity());
            log.info("Done reporting to NewRelic.");

            metricProvider.clearAllMetricData();
        } catch (Exception e) {
            log.error("Error while attempting to publish stats to NewRelic.", e);
        }
    } else {
        log.info("TMC State is '" + stateManager.getTmcState() + "', so disabling NR publication.");
    }
}

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

/**
 * Now send a request which creates a session
 *//*from   www.  j a  v  a 2s  .  com*/
@Test
@RunAsClient
@InSequence(5)
public void sendRequestToDestroySession(@ArquillianResource URL contextPath) throws Exception {
    String url = new URL(contextPath, "destroy-session").toString();
    HttpResponse response = client.execute(new HttpGet(url));
    assertEquals(200, response.getStatusLine().getStatusCode());
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:co.cask.tigon.test.SQLFlowTestBase.java

/**
 * This function is used to ingest data packets into multiple interfaces.
 * @param inputDataStreams {@link java.util.List} of {@link java.util.Map.Entry} that contains the name of the
 * interface as the key and the json encoded data packet as the value.
 *
 * Input Format ://from w w w.j  a v  a 2 s .c  om
 *            [ Map.Entry<InterfaceName, List<JsonEncodedDataPackets>>,
          Map.Entry<InterfaceName, List<JsonEncodedDataPackets>>,
          Map.Entry<InterfaceName, List<JsonEncodedDataPackets>>,
          .
          .
          Map.Entry<InterfaceName, List<JsonEncodedDataPackets>>]
 */
public static void ingestData(List<Map.Entry<String, List<String>>> inputDataStreams) {
    if (latch == null) {
        throw new RuntimeException("Expected output count not defined. Use setExpectedOutputCount()");
    } else if (service == null) {
        throw new RuntimeException("Flow not setup. Use setupFlow()");
    }
    final List<Map.Entry<String, List<String>>> finalInputDataStreams = inputDataStreams;
    Thread ingestData = new Thread(new Runnable() {
        @Override
        public void run() {
            HttpClient httpClient = new DefaultHttpClient();
            for (Map.Entry<String, List<String>> dataStreamEntry : finalInputDataStreams) {
                for (String dataPacket : dataStreamEntry.getValue()) {
                    try {
                        // TODO eliminate org.apache.http dependency TIGON-5
                        HttpPost httpPost = new HttpPost(
                                "http://localhost:" + httpPort + "/v1/tigon/" + dataStreamEntry.getKey());
                        httpPost.addHeader("Content-Type", "application/json");
                        httpPost.setEntity(new StringEntity(dataPacket, Charsets.UTF_8));
                        EntityUtils.consumeQuietly(httpClient.execute(httpPost).getEntity());
                    } catch (Exception e) {
                        Throwables.propagate(e);
                    }
                }
            }
        }
    });
    ingestionThreads.add(ingestData);
    ingestData.start();
    try {
        ingestData.join(60000);
    } catch (InterruptedException e) {
        Throwables.propagate(e);
    }
}

From source file:com.github.avarabyeu.restendpoint.http.DefaultErrorHandler.java

/**
 * Parses byte from entity/*from   w  w w .ja  v a2 s . c o m*/
 *
 * @param rs HTTP Response
 * @return Body as byte array
 * @throws RestEndpointIOException In case of request error
 */
private byte[] getErrorBody(HttpResponse rs) throws RestEndpointIOException {
    HttpEntity entity = null;
    try {
        entity = rs.getEntity();
        return EntityUtils.toByteArray(rs.getEntity());
    } catch (IOException e) {
        throw new RestEndpointIOException("Unable to read body from error", e);
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
}

From source file:com.vmware.content.samples.ImportOva.java

private void uploadOva(String ovaPath, String sessionId) throws Exception {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    IOUtil.print("Streaming OVF to update session " + sessionId);
    try (TarArchiveInputStream tar = new TarArchiveInputStream(new FileInputStream(ovaPath))) {
        TarArchiveEntry entry;/* w  ww  .  j  a v a 2  s .  c  om*/
        while ((entry = tar.getNextTarEntry()) != null) {
            long bytes = entry.getSize();
            IOUtil.print("Uploading " + entry.getName() + " (" + entry.getSize() + " bytes)");
            URI uploadUri = generateUploadUri(sessionId, entry.getName());
            HttpPut request = new HttpPut(uploadUri);
            HttpEntity content = new TarBasedInputStreamEntity(tar, bytes);
            request.setEntity(content);
            HttpResponse response = httpclient.execute(request);
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}

From source file:com.lonepulse.zombielink.response.EntityProcessor.java

/**
 * <p>Accepts the {@link InvocationContext} along with the {@link HttpResponse} and retrieves the 
 * {@link HttpEntity} form the response. This is then converted to an instance of the required request 
 * return type by consulting the @{@link Deserialize} metadata on the endpoint definition.</p>
 * /* w ww  . j  av  a 2 s .c  o m*/
 * <p>If the desired return type is {@link HttpResponse} or {@link HttpEntity} the response or entity 
 * is simply returned without any further processing.</p>
 * 
 * <p><b>Note</b> that this processor returns {@code null} for successful responses with the status 
 * codes {@code 205} or {@code 205}.</p>
 * 
 * @param context
 *          the {@link InvocationContext} which is used to discover deserializer metadata 
 * <br><br>
 * @param response
 *          the {@link HttpResponse} whose response content is deserialized to the desired output type
 * <br><br>
 * @return the deserialized response content which conforms to the expected type
 * <br><br> 
 * @throws ResponseProcessorException
 *          if deserializer instantiation or execution failed for the response entity
 * <br><br>
 * @since 1.3.0
 */
@Override
protected Object process(InvocationContext context, HttpResponse response, Object content) {

    if (response.getEntity() == null) {

        return content;
    }

    HttpEntity entity = response.getEntity();

    Method request = context.getRequest();
    Class<?> responseType = request.getReturnType();

    try {

        if (successful(response) && !status(response, 204, 205)) { //omit successful status codes without response content 

            if (HttpResponse.class.isAssignableFrom(responseType)) {

                return response;
            }

            if (HttpEntity.class.isAssignableFrom(responseType)) {

                return response.getEntity();
            }

            boolean responseExpected = !(responseType.equals(void.class) || responseType.equals(Void.class));
            boolean handleAsync = async(context);

            if (handleAsync || responseExpected) {

                Class<?> endpoint = context.getEndpoint();
                AbstractDeserializer<?> deserializer = null;

                Deserialize metadata = (metadata = request.getAnnotation(Deserialize.class)) == null
                        ? endpoint.getAnnotation(Deserialize.class)
                        : metadata;

                if (metadata != null & !isDetached(context, Deserialize.class)) {

                    deserializer = (metadata.value() == ContentType.UNDEFINED)
                            ? Deserializers.resolve(metadata.type())
                            : Deserializers.resolve(metadata.value());
                } else if (handleAsync || CharSequence.class.isAssignableFrom(responseType)) {

                    deserializer = Deserializers.resolve(ContentType.PLAIN);
                } else {

                    throw new DeserializerUndefinedException(endpoint, request);
                }

                return deserializer.run(context, response);
            }
        }
    } catch (Exception e) {

        throw (e instanceof ResponseProcessorException) ? (ResponseProcessorException) e
                : new ResponseProcessorException(getClass(), context, e);
    } finally {

        if (!(HttpResponse.class.isAssignableFrom(responseType)
                || HttpEntity.class.isAssignableFrom(responseType))) {

            EntityUtils.consumeQuietly(entity);
        }
    }

    return content;
}

From source file:pl.psnc.synat.wrdz.zmkd.plan.DeliveryPlanProcessorBean.java

@Override
@Asynchronous/*  w  w  w  .j  a v  a2 s .co m*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Future<Void> process(String planId) {

    DeliveryPlan plan = planDao.findById(planId);
    if (plan == null) {
        logger.error("No such plan: " + planId);
        return new AsyncResult<Void>(null);
    }

    planManager.changeStatus(planId, DeliveryPlanStatus.RUNNING);

    String objectIdentifier = plan.getObjectIdentifier();

    HttpClient client = httpsClientHelper.getHttpsClient(WrdzModule.ZMKD);

    HttpGet get = new HttpGet(zmkdConfiguration.getZmdObjectUrl(objectIdentifier));
    HttpResponse response = null;

    File digitalObjectFile;
    File workDir;

    try {

        planExecutor.setWait(planId, objectIdentifier);

        response = client.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
            planExecutor.confirmWait(planId);
            return new AsyncResult<Void>(null);
        }

        planExecutor.clearWait(planId);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
            logger.error("Unexpected response: " + response.getStatusLine());
            return new AsyncResult<Void>(null);
        }

        workDir = new File(zmkdConfiguration.getWorkingDirectory(uuidGenerator.generateCacheFolderName()));
        workDir.mkdir();

        digitalObjectFile = httpsClientHelper.storeResponseEntity(workDir, response.getEntity(),
                response.getFirstHeader("Content-Disposition"));

        ZipUtility.unzip(digitalObjectFile, workDir);

    } catch (IOException e) {
        planExecutor.clearWait(planId);
        planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
        logger.error(e.getMessage(), e);
        return new AsyncResult<Void>(null);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }

    DigitalObjectInfo objectInfo = reader.parseMets(workDir, METS_PATH);
    String clientLocation = null;

    try {
        for (ConversionPath conversion : plan.getConversionPaths()) {
            List<TransformationInfo> path = planExecutionParser.parseTransformationPath(conversion);
            planExecutionManager.transform(objectInfo, path);
        }
    } catch (InconsistentServiceDescriptionException e) {
        planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
        logger.error(e.getMessage(), e);
        return new AsyncResult<Void>(null);
    } catch (TransformationException e) {
        planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
        logger.error(e.getMessage(), e);
        return new AsyncResult<Void>(null);
    }
    try {
        DeliveryInfo deliveryInfo = planExecutionParser.parseDelivery(plan.getDelivery());
        clientLocation = planExecutionManager.deliver(objectInfo, deliveryInfo);
    } catch (InconsistentServiceDescriptionException e) {
        planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
        logger.error(e.getMessage(), e);
        return new AsyncResult<Void>(null);
    } catch (DeliveryException e) {
        planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
        logger.error(e.getMessage(), e);
        return new AsyncResult<Void>(null);
    }

    planManager.completePlan(planId, clientLocation);

    return new AsyncResult<Void>(null);
}