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:eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader.java

/**
 * This method retrieves data using HTTP or HTTPS protocol and 'get' method.
 *
 * @param url/*  w w w .  j a  va 2s.  c o m*/
 * @return
 */
protected byte[] httpGet(String url) {

    HttpGet httpRequest = null;
    HttpResponse httpResponse = null;
    try {

        final URI uri = URI.create(url.trim());
        httpRequest = new HttpGet(uri);
        if (contentType != null) {
            httpRequest.setHeader(CONTENT_TYPE, contentType);
        }

        httpResponse = getHttpResponse(httpRequest, url);

        final byte[] returnedBytes = readHttpResponse(url, httpResponse);
        return returnedBytes;
    } finally {
        if (httpRequest != null) {
            httpRequest.releaseConnection();
        }
        if (httpResponse != null) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    }
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

protected void verifyPOSTStatusOnly(URI url, int expected, StringEntity content, boolean authenticate,
        boolean validate) throws Exception {
    HttpPost post = new HttpPost(url);
    HttpResponse response = putOrPost(post, content, authenticate);
    int status = response.getStatusLine().getStatusCode();
    if (status == SC_MOVED_TEMPORARILY) {
        String original = url.toString();
        url = URI.create(response.getFirstHeader(HttpHeaders.LOCATION).getValue());
        if (!original.equals(url.toString())) {
            EntityUtils.consumeQuietly(response.getEntity());
            post = new HttpPost(url);
            response = putOrPost(post, content, true);
            status = response.getStatusLine().getStatusCode();
        }/*from  w w  w . j a  v  a2s . co m*/
    }
    if (validate) {
        validateResponse(url, response);
    } else {
        EntityUtils.consumeQuietly(response.getEntity());
    }
    assertEquals(expected, status);
}

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

private OctaneResponse login(OctaneConfiguration config) throws IOException {
    OctaneResponse result;//from   w  w w . j  ava 2s.  c  o m
    HttpResponse response = null;

    try {
        HttpUriRequest loginRequest = buildLoginRequest(config);
        HttpClientContext context = createHttpContext(loginRequest.getURI().toString(), true);
        response = httpClient.execute(loginRequest, context);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            refreshSecurityToken(context, true);
        } else {
            logger.warn("failed to login to " + config + "; response status: "
                    + response.getStatusLine().getStatusCode());
        }
        result = createNGAResponse(response);
    } catch (IOException ioe) {
        logger.debug("failed to login to " + config, ioe);
        throw ioe;
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            HttpClientUtils.closeQuietly(response);
        }
    }

    return result;
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

private OAuthToken oauthAuthorize(String oauthAuthorizeURL) throws IOException, JDOMException {
    // get pag einfo 
    OAuthToken token = null;//w  w w  .  j a v  a  2s  . com
    WebResponse wr = this.getUrl(oauthAuthorizeURL, false);
    if (wr.statusCode == 200) {
        HashMap<String, ContentBody> formfields = BungeniServiceAccess.getInstance()
                .getAuthorizeFormFieldValues(wr.responseBody);
        if (!formfields.isEmpty()) {
            HttpContext context = new BasicHttpContext();
            // we use the form authorize URL here 
            final HttpPost post = new HttpPost(this.oauthAuthFormUrl);
            // we disable the automatic redirect of the URL since we want to grab 
            // the refresh token and anyway the redirect is to a dummy url
            final HttpParams params = new BasicHttpParams();
            params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
            post.setParams(params);
            post.setEntity(getMultiPartEntity(formfields));
            HttpResponse authResponse = getClient().execute(post, context);
            String redirectLocation = "";
            Header locationHeader = authResponse.getFirstHeader("location");
            //consume response
            //ResponseHandler<String> responseHandler = new BasicResponseHandler();
            //responseHandler.handleResponse(authResponse);

            if (locationHeader != null) {
                redirectLocation = locationHeader.getValue();
                EntityUtils.consumeQuietly(authResponse.getEntity());
                try {
                    token = getAuthToken(redirectLocation);
                    // do someting with the returned codes
                } catch (MalformedURLException ex) {
                    log.error("Error while getting oauthtoken", ex);
                } catch (URISyntaxException ex) {
                    log.error("Error while getting oauthtoken", ex);
                }

            } else {
                EntityUtils.consumeQuietly(authResponse.getEntity());
                throw new IOException(authResponse.getStatusLine().toString());
            }
        } else {
            throw new IOException("Authorization failed !");
        }
    }
    return token;
}

From source file:com.waitwha.nessus.server.Server.java

/**
 * Downloads a report by the given uuid and saves it to the path given.
 * /*  w w  w. j a v  a 2  s.c  om*/
 * @param uuid      String UUID of the Nessus report/scan results to download.
 * @param path      String path to save the document (XML).
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
public NessusClientData downloadReport(String uuid, String path)
        throws ParserConfigurationException, SAXException {
    String c = "/file/report/download";
    if (this.url.endsWith("/"))
        c = c.substring(1);

    NessusClientData scan = null;

    /*
     * Get a client, setup the POST, and execute.
     */
    HttpPost post = new HttpPost(String.format("%s%s", this.url, c));
    post.addHeader("User-Agent", DEFAULT_USER_AGENT);

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("seq", r() + ""));
    nvps.add(new BasicNameValuePair("report", uuid));
    post.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

    HttpClient client = this.getClient();

    try {
        log.finest(String.format("[%s] Executing POST.", post.getURI()));
        HttpResponse resp = client.execute(post);

        try {
            HttpEntity entity = resp.getEntity();

            if (resp.getStatusLine().getStatusCode() == 200) {
                InputStream in = entity.getContent();
                log.finest(String.format("[%s] Received HTTP code %d: %dbytes (%s)", post.getURI(),
                        resp.getStatusLine().getStatusCode(), entity.getContentLength(),
                        entity.getContentType().getValue()));

                File file = new File(path);
                BufferedWriter writer = new BufferedWriter(new FileWriter(file));
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    writer.write(line);
                    writer.flush();
                }
                writer.close();

                scan = NessusClientData.parse(file);
                EntityUtils.consumeQuietly(entity);

            } else {
                log.warning(String.format("[%s] Received HTTP code %d. Could not download report.",
                        post.getURI(), resp.getStatusLine().getStatusCode()));
            }

        } catch (IOException e) {
            log.warning(String.format("[%s] Could not download report: %s", post.getURI(), e.getMessage()));
        }

    } catch (IOException e) {
        log.warning(String.format("[%s] Could not download report: %s", post.getURI(), e.getMessage()));
    }

    return scan;
}

From source file:io.openvidu.java.client.Session.java

/**
 * Forces some user to unpublish a Stream. OpenVidu Browser will trigger the
 * proper events on the client-side (<code>streamDestroyed</code>) with reason
 * set to "forceUnpublishByServer". <br>
 * /*from  www  .j  a  v  a  2  s  .  c om*/
 * You can get <code>streamId</code> parameter with
 * {@link io.openvidu.java.client.Session#getActiveConnections()} and then for
 * each Connection you can call
 * {@link io.openvidu.java.client.Connection#getPublishers()}. Finally
 * {@link io.openvidu.java.client.Publisher#getStreamId()}) will give you the
 * <code>streamId</code>. Remember to call
 * {@link io.openvidu.java.client.Session#fetch()} before to fetch the current
 * actual properties of the Session from OpenVidu Server
 * 
 * @throws OpenViduJavaClientException
 * @throws OpenViduHttpException
 */
public void forceUnpublish(String streamId) throws OpenViduJavaClientException, OpenViduHttpException {
    HttpDelete request = new HttpDelete(
            OpenVidu.urlOpenViduServer + OpenVidu.API_SESSIONS + "/" + this.sessionId + "/stream/" + streamId);
    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

    HttpResponse response;
    try {
        response = OpenVidu.httpClient.execute(request);
    } catch (IOException e) {
        throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
    }

    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ((statusCode == org.apache.http.HttpStatus.SC_NO_CONTENT)) {
            for (Connection connection : this.activeConnections.values()) {
                // Try to remove the Publisher from the Connection publishers collection
                if (connection.publishers.remove(streamId) != null) {
                    continue;
                }
                // Try to remove the Publisher from the Connection subscribers collection
                connection.subscribers.remove(streamId);
            }
            log.info("Stream {} unpublished", streamId);
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

From source file:org.apache.olingo.server.example.TripPinServiceTest.java

@Test
public void testActionImportWithNoResponse() throws Exception {
    HttpPost request = new HttpPost(baseURL + "/ResetDataSource");
    HttpResponse response = httpSend(request, 204);
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

protected void verifyPUTStatusOnly(URI url, int expected, StringEntity content, boolean authenticate)
        throws Exception {
    HttpPut put = new HttpPut(url);
    HttpResponse response = putOrPost(put, content, authenticate);
    int status = response.getStatusLine().getStatusCode();
    if (status == SC_MOVED_TEMPORARILY) {
        String original = url.toString();
        url = URI.create(response.getFirstHeader(HttpHeaders.LOCATION).getValue());
        if (!original.equals(url.toString())) {
            EntityUtils.consumeQuietly(response.getEntity());
            put = new HttpPut(url);
            response = putOrPost(put, content, true);
            status = response.getStatusLine().getStatusCode();
        }/*from  w w w. j  a  va2s.com*/
    }
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(expected, status);
}

From source file:jp.classmethod.aws.brian.BrianClient.java

@Override
public Optional<BrianTrigger> describeTrigger(TriggerKey key)
        throws BrianClientException, BrianServerException {
    logger.debug("describe trigger: {}", key);
    HttpResponse httpResponse = null;/*from  ww  w . j  a v  a2s . co m*/
    try {
        String path = String.format("/triggers/%s/%s", key.getGroup(), key.getName());
        URI uri = new URI(scheme, null, hostname, port, path, null, null);
        HttpUriRequest httpRequest = RequestBuilder.get().setUri(uri).build();
        httpResponse = httpClientExecute(httpRequest);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        JsonNode tree = mapper.readTree(httpResponse.getEntity().getContent());
        if (statusCode == HttpStatus.SC_OK) {
            if (tree.path("cronExpression").isMissingNode() == false) {
                return Optional.of(mapper.readValue(new TreeTraversingParser(tree), BrianCronTrigger.class));
            } else if (tree.path("repeatCount").isMissingNode() == false) {
                return Optional.of(mapper.readValue(new TreeTraversingParser(tree), BrianSimpleTrigger.class));
            }
            // TODO deserialize
            throw new Error("unknown scheduleType");
        } else if (statusCode >= 500) {
            throw new BrianServerException("status = " + statusCode);
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return Optional.empty();
        } else if (statusCode >= 400) {
            throw new BrianClientException("status = " + statusCode);
        } else {
            throw new Error("status = " + statusCode);
        }
    } catch (JsonProcessingException e) {
        throw new BrianServerException(e);
    } catch (URISyntaxException e) {
        throw new IllegalStateException(e);
    } catch (IOException e) {
        throw new BrianServerException(e);
    } catch (IllegalStateException e) {
        throw new Error(e);
    } finally {
        if (httpResponse != null) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    }
}