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.callimachusproject.auth.AuthorizationManager.java

public HttpResponse authorize(ResourceOperation request, Set<Group> groups, CalliContext ctx)
        throws OpenRDFException, IOException {
    InetAddress clientAddr = ctx.getClientAddr();
    long now = ctx.getReceivedOn();
    String m = request.getMethod();
    RDFObject target = request.getRequestedResource();
    String or = request.getVaryHeader("Origin");
    Map<String, String[]> map = getAuthorizationMap(request, now, clientAddr, groups);
    List<String> from = getAgentFrom(map.get("via"));
    if (isAnonymousAllowed(from, groups))
        return null;
    // loop through first to see if further authorisation is needed
    DetachedRealm realm = getRealm(request);
    HttpResponse unauth = null;// www.j  a  va  2s .c  om
    boolean validOrigin = false;
    boolean noRealm = true;
    if (realm != null) {
        String cred = null;
        Collection<String> allowed = realm.allowOrigin();
        try {
            if (or == null || isOriginAllowed(allowed, or)) {
                ObjectConnection con = ctx.getObjectConnection();
                cred = realm.authenticateRequest(m, target, map, con);
                if (cred != null && isMember(cred, from, groups)) {
                    ctx.setCredential(cred);
                    return null; // this request is good
                }
            }
        } catch (TooManyRequests e) {
            StringEntity body = new StringEntity(e.getDetailMessage(), Charset.forName("UTF-8"));
            body.setContentType("text/plain");
            BasicStatusLine line = new BasicStatusLine(HttpVersion.HTTP_1_1, e.getStatusCode(),
                    e.getShortMessage());
            HttpResponse resp = new BasicHttpResponse(line);
            resp.setHeader("Content-Type", "text/plain;charset=UTF-8");
            for (Header hd : e.getResponseHeaders()) {
                resp.addHeader(hd);
            }
            resp.setEntity(body);
            return resp;
        }
        noRealm = false;
        validOrigin = or == null || isOriginAllowed(allowed, or);
        try {
            if (cred == null) {
                unauth = choose(unauth, realm.unauthorized(m, target, map, request.getEntity()));
            } else {
                unauth = choose(unauth, realm.forbidden(m, target, map));
            }
        } catch (ResponseException exc) {
            if (unauth != null) {
                EntityUtils.consumeQuietly(unauth.getEntity());
            }
            throw exc;
        } catch (Exception exc) {
            logger.error(exc.toString(), exc);
        }
    }
    if (unauth != null)
        return unauth;
    if (noRealm) {
        logger.info("No active realm for {}", request);
    } else if (!validOrigin) {
        logger.info("Origin {} not allowed for {}", or, request);
    }
    StringEntity body = new StringEntity("Forbidden", Charset.forName("UTF-8"));
    body.setContentType("text/plain");
    HttpResponse resp = new BasicHttpResponse(_403);
    resp.setHeader("Content-Type", "text/plain;charset=UTF-8");
    resp.setEntity(body);
    return resp;
}

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

private Observable<Response> getHttpObservable(String serviceName, String urlPrefix, Request request) {
    return Observable.<Response>create(new Observable.OnSubscribe<Response>() {

        @Override/*from w  w w  .ja  v a 2s  .  co  m*/
        public void call(final Subscriber<? super Response> subscriber) {
            HttpUriRequest httpRequest = RequestUtil.buildHttpRequest(urlPrefix, request);

            if (log.isDebugEnabled()) {
                log.debug("Execute: " + httpRequest.getURI() + "\n" + request.toString());
            }

            HttpAsyncClient httpClient = httpClientFactory.getAsync(httpRequest.getURI());
            httpClient.execute(httpRequest, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(HttpResponse result) {
                    StatusLine status = result.getStatusLine();
                    HttpEntity entity = result.getEntity();
                    try {
                        if (status.getStatusCode() >= 500) {
                            subscriber.onError(new IllegalResponseRuntimeException(serviceName, request,
                                    httpRequest.getURI().toString(), status.getStatusCode(),
                                    EntityUtils.toString(entity), "Executing '" + httpRequest.getURI()
                                            + "' failed: " + result.getStatusLine()));
                            EntityUtils.consumeQuietly(entity);
                        } else {
                            Response response = Response.create(status.getStatusCode(),
                                    status.getReasonPhrase(), RequestUtil.toHeadersMap(result.getAllHeaders()),
                                    entity.getContent(),
                                    entity.getContentLength() > 0 ? (int) entity.getContentLength() : null);
                            subscriber.onNext(response);
                            subscriber.onCompleted();
                        }
                    } catch (Throwable ex) {
                        subscriber.onError(new IOException(
                                "Reading response of '" + httpRequest.getURI() + "' failed.", ex));
                        EntityUtils.consumeQuietly(entity);
                    }
                }

                @Override
                public void failed(Exception ex) {
                    if (ex instanceof SocketTimeoutException) {
                        subscriber.onError(new IOException(
                                "Socket timeout executing '" + httpRequest.getURI() + "'.", ex));
                    } else {
                        subscriber.onError(
                                new IOException("Executing '" + httpRequest.getURI() + "' failed.", ex));
                    }
                }

                @Override
                public void cancelled() {
                    subscriber.onError(new IOException("Getting " + httpRequest.getURI() + " was cancelled."));
                }

            });
        }

    });
}

From source file:org.phenotips.data.internal.MonarchPatientScorer.java

@Override
public double getScore(Patient patient) {
    String key = getCacheKey(patient);
    PatientSpecificity specificity = this.cache.get(key);
    if (specificity != null) {
        return specificity.getScore();
    }//from ww  w . ja  v a  2  s.  c om
    if (patient.getFeatures().isEmpty()) {
        this.cache.set(key, new PatientSpecificity(0, now(), SCORER_NAME));
        return 0;
    }
    CloseableHttpResponse response = null;
    try {
        JSONObject data = new JSONObject();
        JSONArray features = new JSONArray();
        for (Feature f : patient.getFeatures()) {
            if (StringUtils.isNotEmpty(f.getId())) {
                JSONObject featureObj = new JSONObject(Collections.singletonMap("id", f.getId()));
                if (!f.isPresent()) {
                    featureObj.put("isPresent", false);
                }
                features.put(featureObj);
            }
        }
        data.put("features", features);

        HttpPost method = new HttpPost(this.scorerURL);
        method.setEntity(new StringEntity("annotation_profile=" + URLEncoder.encode(data.toString(), "UTF-8"),
                ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));

        RequestConfig config = RequestConfig.custom().setSocketTimeout(2000).build();
        method.setConfig(config);
        response = this.client.execute(method);
        JSONObject score = new JSONObject(
                IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
        specificity = new PatientSpecificity(score.getDouble("scaled_score"), now(), SCORER_NAME);
        this.cache.set(key, specificity);
        return specificity.getScore();
    } catch (Exception ex) {
        // Just return failure below
        this.logger.error(
                "Failed to compute specificity score for patient [{}] using the monarch server [{}]: {}",
                patient.getDocumentReference(), this.scorerURL, ex.getMessage());
    } finally {
        if (response != null) {
            try {
                EntityUtils.consumeQuietly(response.getEntity());
                response.close();
            } catch (IOException ex) {
                // Not dangerous
            }
        }
    }
    return -1;
}

From source file:com.erudika.para.security.FacebookAuthFilter.java

/**
 * Calls the Facebook API to get the user profile using a given access token.
 * @param appid app identifier of the parent app, use null for root app
 * @param accessToken access token/*  w ww  . j  a  v  a  2s  .co m*/
 * @return {@link UserAuthentication} object or null if something went wrong
 * @throws IOException ex
 */
@SuppressWarnings("unchecked")
public UserAuthentication getOrCreateUser(String appid, String accessToken) throws IOException {
    UserAuthentication userAuth = null;
    if (accessToken != null) {
        User user = new User();
        user.setAppid(appid);
        HttpGet profileGet = new HttpGet(PROFILE_URL + accessToken);
        CloseableHttpResponse resp2 = httpclient.execute(profileGet);
        HttpEntity respEntity = resp2.getEntity();
        String ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();

        if (respEntity != null && Utils.isJsonType(ctype)) {
            Map<String, Object> profile = jreader.readValue(resp2.getEntity().getContent());

            if (profile != null && profile.containsKey("id")) {
                String fbId = (String) profile.get("id");
                Map<String, Object> pic = (Map<String, Object>) profile.get("picture");
                String email = (String) profile.get("email");
                String name = (String) profile.get("name");

                user.setIdentifier(Config.FB_PREFIX.concat(fbId));
                user = User.readUserForIdentifier(user);
                if (user == null) {
                    //user is new
                    user = new User();
                    user.setActive(true);
                    user.setEmail(StringUtils.isBlank(email) ? fbId + "@facebook.com" : email);
                    user.setName(StringUtils.isBlank(name) ? "No Name" : name);
                    user.setPassword(new UUID().toString());
                    user.setPicture(getPicture(fbId, pic));
                    user.setIdentifier(Config.FB_PREFIX.concat(fbId));
                    String id = user.create();
                    if (id == null) {
                        throw new AuthenticationServiceException(
                                "Authentication failed: cannot create new user.");
                    }
                } else {
                    String picture = getPicture(fbId, pic);
                    if (!StringUtils.equals(user.getPicture(), picture)) {
                        user.setPicture(picture);
                        user.update();
                    }
                }
                userAuth = new UserAuthentication(new AuthenticatedUserDetails(user));
            }
            EntityUtils.consumeQuietly(resp2.getEntity());
        }
    }
    return userAuth;
}

From source file:io.wcm.maven.plugins.contentpackage.DownloadMojo.java

/**
 * Download content package from CRX instance
 */// ww w . ja  v a2  s  .co m
private File downloadFile(File file, String ouputFilePath) throws MojoExecutionException {
    try (CloseableHttpClient httpClient = getHttpClient()) {
        getLog().info("Download " + file.getName() + " from " + getCrxPackageManagerUrl());

        // 1st: try upload to get path of package - or otherwise make sure package def exists (no install!)
        HttpPost post = new HttpPost(getCrxPackageManagerUrl() + "/.json?cmd=upload");
        MultipartEntityBuilder entity = MultipartEntityBuilder.create().addBinaryBody("package", file)
                .addTextBody("force", "true");
        post.setEntity(entity.build());
        JSONObject jsonResponse = executePackageManagerMethodJson(httpClient, post);
        boolean success = jsonResponse.optBoolean("success", false);
        String msg = jsonResponse.optString("msg", null);
        String path = jsonResponse.optString("path", null);

        // package already exists - get path from error message and continue
        if (!success && StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX)
                && StringUtils.isEmpty(path)) {
            path = StringUtils.substringAfter(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX);
            success = true;
        }
        if (!success) {
            throw new MojoExecutionException("Package path detection failed: " + msg);
        }

        getLog().info("Package path is: " + path + " - now rebuilding package...");

        // 2nd: build package
        HttpPost buildMethod = new HttpPost(getCrxPackageManagerUrl() + "/console.html" + path + "?cmd=build");
        executePackageManagerMethodHtml(httpClient, buildMethod, 0);

        // 3rd: download package
        String crxUrl = StringUtils.removeEnd(getCrxPackageManagerUrl(), "/crx/packmgr/service");
        HttpGet downloadMethod = new HttpGet(crxUrl + path);

        // execute download
        CloseableHttpResponse response = httpClient.execute(downloadMethod);
        try {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                // get response stream
                InputStream responseStream = response.getEntity().getContent();

                // delete existing file
                File outputFileObject = new File(ouputFilePath);
                if (outputFileObject.exists()) {
                    outputFileObject.delete();
                }

                // write response file
                FileOutputStream fos = new FileOutputStream(outputFileObject);
                IOUtil.copy(responseStream, fos);
                fos.flush();
                responseStream.close();
                fos.close();

                getLog().info("Package downloaded to " + outputFileObject.getAbsolutePath());

                return outputFileObject;
            } else {
                throw new MojoExecutionException(
                        "Package download failed:\n" + EntityUtils.toString(response.getEntity()));
            }
        } finally {
            if (response != null) {
                EntityUtils.consumeQuietly(response.getEntity());
                try {
                    response.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    } catch (FileNotFoundException ex) {
        throw new MojoExecutionException("File not found: " + file.getAbsolutePath(), ex);
    } catch (IOException ex) {
        throw new MojoExecutionException("Download operation failed.", ex);
    }
}

From source file:com.erudika.para.security.LinkedInAuthFilter.java

/**
 * Calls the LinkedIn API to get the user profile using a given access token.
 * @param appid app identifier of the parent app, use null for root app
 * @param accessToken access token/*from ww  w. j  a v a2  s.  co  m*/
 * @return {@link UserAuthentication} object or null if something went wrong
 * @throws IOException ex
 */
public UserAuthentication getOrCreateUser(String appid, String accessToken) throws IOException {
    UserAuthentication userAuth = null;
    if (accessToken != null) {
        User user = new User();
        user.setAppid(appid);
        HttpGet profileGet = new HttpGet(PROFILE_URL + accessToken);
        CloseableHttpResponse resp2 = httpclient.execute(profileGet);
        HttpEntity respEntity = resp2.getEntity();
        String ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();

        if (respEntity != null && Utils.isJsonType(ctype)) {
            Map<String, Object> profile = jreader.readValue(resp2.getEntity().getContent());

            if (profile != null && profile.containsKey("id")) {
                String linkedInID = (String) profile.get("id");
                String email = (String) profile.get("emailAddress");
                String pic = (String) profile.get("pictureUrl");
                String fName = (String) profile.get("firstName");
                String lName = (String) profile.get("lastName");
                String name = fName + " " + lName;

                user.setIdentifier(Config.LINKEDIN_PREFIX.concat(linkedInID));
                user = User.readUserForIdentifier(user);
                if (user == null) {
                    //user is new
                    user = new User();
                    user.setActive(true);
                    user.setEmail(StringUtils.isBlank(email) ? linkedInID + "@linkedin.com" : email);
                    user.setName(StringUtils.isBlank(name) ? "No Name" : name);
                    user.setPassword(new UUID().toString());
                    user.setPicture(pic);
                    user.setIdentifier(Config.LINKEDIN_PREFIX.concat(linkedInID));
                    String id = user.create();
                    if (id == null) {
                        throw new AuthenticationServiceException(
                                "Authentication failed: cannot create new user.");
                    }
                } else {
                    if (!StringUtils.equals(user.getPicture(), pic)) {
                        user.setPicture(pic);
                        user.update();
                    }
                }
                userAuth = new UserAuthentication(new AuthenticatedUserDetails(user));
            }
            EntityUtils.consumeQuietly(resp2.getEntity());
        }
    }
    return userAuth;
}

From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java

private JsonElement getResponseJson(HttpRequestBase req, int expectCode) throws RestApiException, IOException {
    logger.trace("{} {}", req.getMethod(), req.getURI());

    CloseableHttpResponse res = cli.execute(req);
    try {//from   w ww.j a  v a 2  s .  c  o m
        return extractResponse(res, req, expectCode);
    } finally {
        if (res.getEntity() != null) {
            // Ensure the content is completely removed from the stream,
            // so we can re-use the connection
            EntityUtils.consumeQuietly(res.getEntity());
        }
    }
}

From source file:com.turn.ttorrent.tracker.client.HTTPTrackerClient.java

@CheckForNull
public static HTTPTrackerMessage toMessage(@Nonnull HttpResponse response,
        @CheckForSigned long maxContentLength) throws IOException {
    HttpEntity entity = response.getEntity();
    if (entity == null) // Usually 204-no-content, etc.
        return null;
    try {//from w ww .  j av a  2s .c o m
        if (maxContentLength >= 0) {
            long contentLength = entity.getContentLength();
            if (contentLength >= 0)
                if (contentLength > maxContentLength)
                    throw new IllegalArgumentException(
                            "ContentLength was too big: " + contentLength + ": " + response);
        }

        InputStream in = entity.getContent();
        if (in == null)
            return null;
        try {
            StreamBDecoder decoder = new StreamBDecoder(in);
            BEValue value = decoder.bdecodeMap();
            Map<String, BEValue> params = value.getMap();
            // TODO: "warning message"
            if (params.containsKey("failure reason"))
                return HTTPTrackerErrorMessage.fromBEValue(params);
            else
                return HTTPAnnounceResponseMessage.fromBEValue(params);
        } finally {
            Closeables.close(in, true);
        }
    } catch (InvalidBEncodingException e) {
        throw new IOException("Failed to parse response " + response, e);
    } catch (TrackerMessage.MessageValidationException e) {
        throw new IOException("Failed to parse response " + response, e);
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
}

From source file:org.apache.solr.handler.TestSolrConfigHandlerConcurrent.java

public static Map getAsMap(String uri, CloudSolrClient cloudClient) throws Exception {
    HttpGet get = new HttpGet(uri);
    HttpEntity entity = null;/*  w  w  w. j  ava2 s. co  m*/
    try {
        entity = cloudClient.getLbClient().getHttpClient().execute(get).getEntity();
        String response = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        try {
            return (Map) ObjectBuilder.getVal(new JSONParser(new StringReader(response)));
        } catch (JSONParser.ParseException e) {
            log.error(response, e);
            throw e;
        }
    } finally {
        EntityUtils.consumeQuietly(entity);
        get.releaseConnection();
    }
}