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.apache.olingo.server.example.TripPinServiceTest.java

@Test
public void testDeleteProperty() throws Exception {
    String editUrl = baseURL + "/People('russellwhyte')/FirstName";
    HttpResponse response = httpGET(editUrl, 200);
    JsonNode node = getJSONNode(response);
    assertEquals("Russell", node.get("value").asText());

    HttpDelete deleteRequest = new HttpDelete(editUrl);
    response = httpSend(deleteRequest, 204);
    EntityUtils.consumeQuietly(response.getEntity());

    response = httpGET(editUrl, 204);//w w  w  .  j a  v  a2s .  co m
    EntityUtils.consumeQuietly(response.getEntity());
}

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

@Test
public void testGETMethodCustomUserArgBadDate() throws Exception {
    URI url = getURI("/objects/demo:14/methods/demo:12/getDocumentStyle1?width=50&asOfDateTime=badDate");
    verifyNoAuthFailOnAPIAAuth(url);//  w  w w. j  a va 2 s.com
    HttpGet get = new HttpGet(url);
    HttpResponse response;
    int status = 0;
    response = getOrDelete(get, getAuthAccess(), false);
    status = response.getStatusLine().getStatusCode();
    EntityUtils.consumeQuietly(response.getEntity());
    assertFalse(SC_OK == status);
}

From source file:org.openrdf.http.client.SparqlSession.java

/**
 * Parse the response in a background thread. HTTP connections are dealt with
 * in the {@link BackgroundTupleResult} or (in the error-case) in this
 * method./*from   w  ww.ja  v a  2  s  . c om*/
 */
protected BackgroundTupleResult getBackgroundTupleQueryResult(HttpUriRequest method)
        throws RepositoryException, QueryInterruptedException, MalformedQueryException, IOException {

    boolean submitted = false;

    // Specify which formats we support
    Set<TupleQueryResultFormat> tqrFormats = TupleQueryResultParserRegistry.getInstance().getKeys();
    if (tqrFormats.isEmpty()) {
        throw new RepositoryException("No tuple query result parsers have been registered");
    }

    // send the tuple query
    HttpResponse response = sendTupleQueryViaHttp(method, tqrFormats);
    try {

        // if we get here, HTTP code is 200
        String mimeType = getResponseMIMEType(response);
        try {
            TupleQueryResultFormat format = TupleQueryResultFormat.matchMIMEType(mimeType, tqrFormats);
            TupleQueryResultParser parser = QueryResultIO.createParser(format, getValueFactory());
            BackgroundTupleResult tRes = new BackgroundTupleResult(parser, response.getEntity().getContent());
            execute(tRes);
            submitted = true;
            return tRes;
        } catch (UnsupportedQueryResultFormatException e) {
            throw new RepositoryException("Server responded with an unsupported file format: " + mimeType);
        }
    } finally {
        if (!submitted)
            EntityUtils.consumeQuietly(response.getEntity());
    }
}

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

@Test
public void testGETMethodCustomUserArgEarlyDate() throws Exception {
    URI url = getURI(/*ww w  .  jav a2  s. c  o m*/
            "/objects/demo:14/methods/demo:12/getDocumentStyle1?width=50&asOfDateTime=1999-11-21T16:38:32.200Z");
    verifyNoAuthFailOnAPIAAuth(url);
    HttpGet get = new HttpGet(url);
    HttpResponse response;
    int status = 0;
    response = getOrDelete(get, getAuthAccess(), false);
    status = response.getStatusLine().getStatusCode();
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_NOT_FOUND, status);
}

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

/**
 * Updates every property of every active Session with the current status they
 * have in OpenVidu Server. After calling this method you can access the updated
 * list of active sessions by calling/*w w  w  .  ja va 2s . co m*/
 * {@link io.openvidu.java.client.OpenVidu#getActiveSessions()}
 * 
 * @return true if any Session status has changed with respect to the server,
 *         false if not. This applies to any property or sub-property of any of
 *         the sessions locally stored in OpenVidu Java Client
 * 
 * @throws OpenViduHttpException
 * @throws OpenViduJavaClientException
 */
@SuppressWarnings("unchecked")
public boolean fetch() throws OpenViduJavaClientException, OpenViduHttpException {
    HttpGet request = new HttpGet(OpenVidu.urlOpenViduServer + API_SESSIONS);

    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_OK)) {
            JSONObject jsonSessions = httpResponseToJson(response);
            JSONArray jsonArraySessions = (JSONArray) jsonSessions.get("content");

            // Set to store fetched sessionIds and later remove closed sessions
            Set<String> fetchedSessionIds = new HashSet<>();
            // Boolean to store if any Session has changed
            final boolean[] hasChanged = { false };
            jsonArraySessions.forEach(session -> {
                String sessionId = (String) ((JSONObject) session).get("sessionId");
                fetchedSessionIds.add(sessionId);
                OpenVidu.activeSessions.computeIfPresent(sessionId, (sId, s) -> {
                    String beforeJSON = s.toJson();
                    s = s.resetSessionWithJson((JSONObject) session);
                    String afterJSON = s.toJson();
                    boolean changed = !beforeJSON.equals(afterJSON);
                    hasChanged[0] = hasChanged[0] || changed;
                    log.info("Available session '{}' info fetched. Any change: {}", sessionId, changed);
                    return s;
                });
                OpenVidu.activeSessions.computeIfAbsent(sessionId, sId -> {
                    log.info("New session '{}' fetched", sessionId);
                    hasChanged[0] = true;
                    return new Session((JSONObject) session);
                });
            });

            // Remove closed sessions from activeSessions map
            OpenVidu.activeSessions = OpenVidu.activeSessions.entrySet().stream().filter(entry -> {
                if (fetchedSessionIds.contains(entry.getKey())) {
                    return true;
                } else {
                    log.info("Removing closed session {}", entry.getKey());
                    hasChanged[0] = true;
                    return false;
                }
            }).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
            log.info("Active sessions info fetched: {}", OpenVidu.activeSessions.keySet());
            return hasChanged[0];
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

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

@Test
public void testGETMethodCustomGoodDate() throws Exception {
    URI url = getURI("/objects/demo:14/methods/demo:12/getDocumentStyle1?asOfDateTime=" + datetime);
    verifyNoAuthFailOnAPIAAuth(url);/*from www .  j  a va  2  s.  co  m*/
    HttpGet get = new HttpGet(url);
    HttpResponse response;
    int status = 0;
    response = getOrDelete(get, getAuthAccess(), true);
    status = response.getStatusLine().getStatusCode();
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_OK, status);
}

From source file:org.codelibs.fess.crawler.client.http.HcHttpClient.java

protected ResponseData processHttpMethod(final String url, final HttpUriRequest httpRequest) {
    try {/*  w w w.ja  v  a2s . c  o m*/
        processRobotsTxt(url);
    } catch (final CrawlingAccessException e) {
        if (logger.isInfoEnabled()) {
            final StringBuilder buf = new StringBuilder(100);
            buf.append(e.getMessage());
            if (e.getCause() != null) {
                buf.append(e.getCause().getMessage());
            }
            logger.info(buf.toString());
        } else if (logger.isDebugEnabled()) {
            logger.debug("Crawling Access Exception at " + url, e);
        }
    }

    // request header
    for (final Header header : requestHeaderList) {
        httpRequest.addHeader(header);
    }

    ResponseData responseData = new ResponseData();
    HttpEntity httpEntity = null;
    try {
        // get a content
        final HttpResponse response = executeHttpClient(httpRequest);
        httpEntity = response.getEntity();

        final int httpStatusCode = response.getStatusLine().getStatusCode();
        // redirect
        if (isRedirectHttpStatus(httpStatusCode)) {
            final Header locationHeader = response.getFirstHeader("location");
            if (locationHeader == null) {
                logger.warn("Invalid redirect location at " + url);
            } else {
                responseData = new ResponseData();
                responseData.setRedirectLocation(locationHeader.getValue());
                return responseData;
            }
        }

        String contentType = null;
        final Header contentTypeHeader = response.getFirstHeader("Content-Type");
        if (contentTypeHeader != null) {
            contentType = contentTypeHeader.getValue();
            final int idx = contentType.indexOf(';');
            if (idx > 0) {
                contentType = contentType.substring(0, idx);
                if (APPLICATION_OCTET_STREAM.equals(contentType)) {
                    contentType = null;
                }
            }
        }

        long contentLength = 0;
        String contentEncoding = Constants.UTF_8;
        if (httpEntity == null) {
            responseData.setResponseBody(new byte[0]);
            if (contentType == null) {
                contentType = defaultMimeType;
            }
        } else {
            final InputStream responseBodyStream = httpEntity.getContent();
            final File outputFile = File.createTempFile("crawler-HcHttpClient-", ".out");
            DeferredFileOutputStream dfos = null;
            try {
                try {
                    dfos = new DeferredFileOutputStream((int) maxCachedContentSize, outputFile);
                    CopyUtil.copy(responseBodyStream, dfos);
                    dfos.flush();
                } finally {
                    IOUtils.closeQuietly(dfos);
                }
            } catch (final Exception e) {
                if (!outputFile.delete()) {
                    logger.warn("Could not delete " + outputFile.getAbsolutePath());
                }
                throw e;
            }

            if (dfos.isInMemory()) {
                responseData.setResponseBody(dfos.getData());
                contentLength = dfos.getData().length;
                if (!outputFile.delete()) {
                    logger.warn("Could not delete " + outputFile.getAbsolutePath());
                }
                if (contentType == null) {
                    try (InputStream is = new ByteArrayInputStream(dfos.getData())) {
                        contentType = mimeTypeHelper.getContentType(is, url);
                    } catch (Exception e) {
                        logger.debug("Failed to detect mime-type.", e);
                        contentType = defaultMimeType;
                    }
                }
            } else {
                responseData.setResponseBody(outputFile, true);
                contentLength = outputFile.length();
                if (contentType == null) {
                    try (InputStream is = new FileInputStream(outputFile)) {
                        contentType = mimeTypeHelper.getContentType(is, url);
                    } catch (Exception e) {
                        logger.debug("Failed to detect mime-type.", e);
                        contentType = defaultMimeType;
                    }
                }
            }

            final Header contentEncodingHeader = httpEntity.getContentEncoding();
            if (contentEncodingHeader != null) {
                contentEncoding = contentEncodingHeader.getValue();
            }
        }

        // check file size
        if (contentLengthHelper != null) {
            final long maxLength = contentLengthHelper.getMaxLength(contentType);
            if (contentLength > maxLength) {
                throw new MaxLengthExceededException("The content length (" + contentLength + " byte) is over "
                        + maxLength + " byte. The url is " + url);
            }
        }

        responseData.setUrl(url);
        responseData.setCharSet(contentEncoding);
        if (httpRequest instanceof HttpHead) {
            responseData.setMethod(Constants.HEAD_METHOD);
        } else {
            responseData.setMethod(Constants.GET_METHOD);
        }
        responseData.setHttpStatusCode(httpStatusCode);
        for (final Header header : response.getAllHeaders()) {
            responseData.addMetaData(header.getName(), header.getValue());
        }
        responseData.setMimeType(contentType);
        final Header contentLengthHeader = response.getFirstHeader("Content-Length");
        if (contentLengthHeader == null) {
            responseData.setContentLength(contentLength);
        } else {
            final String value = contentLengthHeader.getValue();
            try {
                responseData.setContentLength(Long.parseLong(value));
            } catch (final Exception e) {
                responseData.setContentLength(contentLength);
            }
        }
        checkMaxContentLength(responseData);
        final Header lastModifiedHeader = response.getFirstHeader("Last-Modified");
        if (lastModifiedHeader != null) {
            final String value = lastModifiedHeader.getValue();
            if (StringUtil.isNotBlank(value)) {
                final Date d = parseLastModified(value);
                if (d != null) {
                    responseData.setLastModified(d);
                }
            }
        }

        return responseData;
    } catch (final UnknownHostException e) {
        closeResources(httpRequest, responseData);
        throw new CrawlingAccessException("Unknown host(" + e.getMessage() + "): " + url, e);
    } catch (final NoRouteToHostException e) {
        closeResources(httpRequest, responseData);
        throw new CrawlingAccessException("No route to host(" + e.getMessage() + "): " + url, e);
    } catch (final ConnectException e) {
        closeResources(httpRequest, responseData);
        throw new CrawlingAccessException("Connection time out(" + e.getMessage() + "): " + url, e);
    } catch (final SocketException e) {
        closeResources(httpRequest, responseData);
        throw new CrawlingAccessException("Socket exception(" + e.getMessage() + "): " + url, e);
    } catch (final IOException e) {
        closeResources(httpRequest, responseData);
        throw new CrawlingAccessException("I/O exception(" + e.getMessage() + "): " + url, e);
    } catch (final CrawlerSystemException e) {
        closeResources(httpRequest, responseData);
        throw e;
    } catch (final Exception e) {
        closeResources(httpRequest, responseData);
        throw new CrawlerSystemException("Failed to access " + url, e);
    } finally {
        EntityUtils.consumeQuietly(httpEntity);
    }
}

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

@Test
public void testGETMethodCustomBadDate() throws Exception {
    URI url = getURI("/objects/demo:14/methods/demo:12/getDocumentStyle1?asOfDateTime=badDate");
    verifyNoAuthFailOnAPIAAuth(url);/*from   ww w. j  a v  a 2 s. co  m*/
    HttpGet get = new HttpGet(url);
    HttpResponse response;
    int status = 0;
    response = getOrDelete(get, getAuthAccess(), false);
    status = response.getStatusLine().getStatusCode();
    EntityUtils.consumeQuietly(response.getEntity());
    assertFalse(SC_OK == status);
}

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

@Test
public void testReadNavigationPropertyEntityNotExisting() throws Exception {
    String editUrl = baseURL + "/People('russellwhyte')/Trips(9999)";
    HttpResponse response = httpGET(editUrl, 204);
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:org.openrdf.http.client.SparqlSession.java

/**
 * Parse the response in this thread using the provided
 * {@link TupleQueryResultHandler}. All HTTP connections are closed and
 * released in this method/* ww  w.j a  v a2  s .  co m*/
 */
protected void getTupleQueryResult(HttpUriRequest method, TupleQueryResultHandler handler)
        throws IOException, TupleQueryResultHandlerException, RepositoryException, MalformedQueryException,
        UnauthorizedException, QueryInterruptedException {
    // Specify which formats we support
    Set<TupleQueryResultFormat> tqrFormats = TupleQueryResultParserRegistry.getInstance().getKeys();
    if (tqrFormats.isEmpty()) {
        throw new RepositoryException("No tuple query result parsers have been registered");
    }

    // send the tuple query
    HttpResponse response = sendTupleQueryViaHttp(method, tqrFormats);
    try {

        // if we get here, HTTP code is 200
        String mimeType = getResponseMIMEType(response);
        try {
            TupleQueryResultFormat format = TupleQueryResultFormat.matchMIMEType(mimeType, tqrFormats);
            TupleQueryResultParser parser = QueryResultIO.createParser(format, getValueFactory());
            parser.setQueryResultHandler(handler);
            parser.parseQueryResult(response.getEntity().getContent());
        } catch (UnsupportedQueryResultFormatException e) {
            throw new RepositoryException("Server responded with an unsupported file format: " + mimeType);
        } catch (QueryResultParseException e) {
            throw new RepositoryException("Malformed query result from server", e);
        } catch (QueryResultHandlerException e) {
            if (e instanceof TupleQueryResultHandlerException) {
                throw (TupleQueryResultHandlerException) e;
            } else {
                throw new TupleQueryResultHandlerException(e);
            }
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}