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:com.vaushell.superpipes.tools.HTTPhelper.java

/**
 * Is a URI exist (HTTP response code between 200 and 299).
 *
 * @param client HTTP client./*from w w w .  jav a 2s  .  c  o  m*/
 * @param uri the URI.
 * @param timeout how many ms to wait ? (could be null)
 * @return true if it exists.
 * @throws IOException
 */
public static boolean isURIvalid(final CloseableHttpClient client, final URI uri, final Duration timeout)
        throws IOException {
    if (client == null || uri == null) {
        throw new IllegalArgumentException();
    }

    HttpEntity responseEntity = null;
    try {
        // Exec request
        final HttpGet get = new HttpGet(uri);

        if (timeout != null && timeout.getMillis() > 0L) {
            get.setConfig(RequestConfig.custom().setConnectTimeout((int) timeout.getMillis())
                    .setConnectionRequestTimeout((int) timeout.getMillis())
                    .setSocketTimeout((int) timeout.getMillis()).build());
        }

        try (final CloseableHttpResponse response = client.execute(get)) {
            final StatusLine sl = response.getStatusLine();
            responseEntity = response.getEntity();

            return sl.getStatusCode() >= 200 && sl.getStatusCode() < 300;
        }
    } finally {
        if (responseEntity != null) {
            EntityUtils.consumeQuietly(responseEntity);
        }
    }
}

From source file:org.jutge.joc.porra.service.EmailService.java

/**
 * Mighty delicate a process it is to send an email through the Raco webmail frontend. Let me break it down:
 * You need to log in as you'd normally do in the Raco. After a couple of redirects to the CAS server, you should be inside.
 * Then you issue a GET for the mail compose form. The response contains a form token to be used in the actual multipart POST that should send the mail.
 * The minute they change the login system or the webmail styles, this'll probably break down LOL: Let's hope they keep it this way til the Joc d'EDA is over
 * @param userAccount user to send the mail to
 * @param message the message body//from   w w w.j  a  v a  2  s . c  o m
 * @throws Exception should anything crash
 */
private void sendMail(final Account userAccount, final String message) throws Exception {
    // Enviar mail pel Raco
    // Authenticate
    final List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("service", "https://raco.fib.upc.edu/oauth/gestio-api/api.jsp"));
    params.add(new BasicNameValuePair("loginDirecte", "true"));
    params.add(new BasicNameValuePair("username", "XXXXXXXX"));
    params.add(new BasicNameValuePair("password", "XXXXXXXX"));
    HttpPost post = new HttpPost("https://raco.fib.upc.edu/cas/login");
    post.setEntity(new UrlEncodedFormEntity(params));
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
        public boolean isRedirected(final HttpRequest request, final HttpResponse response,
                final HttpContext context) {
            boolean isRedirect = false;
            try {
                isRedirect = super.isRedirected(request, response, context);
            } catch (ProtocolException e) {
                EmailService.this.logger.error(e.getMessage());
            }
            if (!isRedirect) {
                final int responseCode = response.getStatusLine().getStatusCode();
                isRedirect = responseCode == 301 || responseCode == 302;
            }
            return isRedirect;
        }
    });
    HttpResponse response = httpClient.execute(post);
    HttpEntity entity = response.getEntity();
    EntityUtils.consumeQuietly(entity);
    // get form page
    final HttpGet get = new HttpGet("https://webmail.fib.upc.es/horde/imp/compose.php?thismailbox=INBOX&uniq="
            + System.currentTimeMillis());
    response = httpClient.execute(get);
    entity = response.getEntity();
    String responseBody = EntityUtils.toString(entity);
    // Find form action with uniq parameter 
    Pattern pattern = Pattern.compile(RacoUtils.RACO_MAIL_ACTION_PATTERN);
    Matcher matcher = pattern.matcher(responseBody);
    matcher.find();
    final String action = matcher.group();
    // formtoken
    responseBody = responseBody.substring(matcher.end(), responseBody.length());
    pattern = Pattern.compile(RacoUtils.RACO_FORMTOKEN_PATTERN);
    matcher = pattern.matcher(responseBody);
    matcher.find();
    String formToken = matcher.group();
    formToken = formToken.substring(28, formToken.length());
    // to
    final String email = userAccount.getEmail();
    // Send mail - it's a multipart post
    final MultipartEntity multipart = new MultipartEntity();
    multipart.addPart("MAX_FILE_SIZE", new StringBody("1038090240"));
    multipart.addPart("actionID", new StringBody("send_message"));
    multipart.addPart("__formToken_compose", new StringBody(formToken));
    multipart.addPart("messageCache", new StringBody(""));
    multipart.addPart("spellcheck", new StringBody(""));
    multipart.addPart("page", new StringBody(""));
    multipart.addPart("start", new StringBody(""));
    multipart.addPart("thismailbox", new StringBody("INBOX"));
    multipart.addPart("attachmentAction", new StringBody(""));
    multipart.addPart("reloaded", new StringBody("1"));
    multipart.addPart("oldrtemode", new StringBody(""));
    multipart.addPart("rtemode", new StringBody("1"));
    multipart.addPart("last_identity", new StringBody("0"));
    multipart.addPart("from", new StringBody("porra-joc-eda@est.fib.upc.edu"));
    multipart.addPart("to", new StringBody(email));
    multipart.addPart("cc", new StringBody(""));
    multipart.addPart("bcc", new StringBody(""));
    multipart.addPart("subject", new StringBody("Activacio Porra Joc EDA"));
    multipart.addPart("charset", new StringBody("UTF-8"));
    multipart.addPart("save_sent_mail", new StringBody("on"));
    multipart.addPart("message", new StringBody(message));
    multipart.addPart("upload_1", new StringBody(""));
    multipart.addPart("upload_disposition_1", new StringBody("attachment"));
    multipart.addPart("save_attachments_select", new StringBody("0"));
    multipart.addPart("link_attachments", new StringBody("0"));
    post = new HttpPost("https://webmail.fib.upc.es/horde/imp/" + action);
    post.setEntity(multipart);
    response = httpClient.execute(post);
    EntityUtils.consumeQuietly(entity);
    this.logger.info("EmailService.sendMail done");
}

From source file:com.github.parisoft.resty.entity.EntityReaderImpl.java

@Override
protected void finalize() throws Throwable {
    EntityUtils.consumeQuietly(httpResponse.getEntity());
    super.finalize();
}

From source file:org.olat.modules.tu.TunnelMapper.java

@Override
public MediaResource handle(String relPath, HttpServletRequest hreq) {
    String method = hreq.getMethod();
    String uri = relPath;//from  w w  w  .jav  a2  s .  c  om
    HttpUriRequest meth = null;

    try {
        URIBuilder builder = new URIBuilder();
        builder.setScheme(proto).setHost(host).setPort(port.intValue());
        if (uri == null) {
            uri = (startUri == null) ? "" : startUri;
        }
        if (uri.length() > 0 && uri.charAt(0) != '/') {
            uri = "/" + uri;
        }
        if (StringHelper.containsNonWhitespace(uri)) {
            builder.setPath(uri);
        }

        if (method.equals("GET")) {
            String queryString = hreq.getQueryString();
            if (StringHelper.containsNonWhitespace(queryString)) {
                builder.setCustomQuery(queryString);
            }
            meth = new HttpGet(builder.build());
        } else if (method.equals("POST")) {
            Map<String, String[]> params = hreq.getParameterMap();
            HttpPost pmeth = new HttpPost(builder.build());
            List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
            for (String key : params.keySet()) {
                String vals[] = params.get(key);
                for (String val : vals) {
                    pairs.add(new BasicNameValuePair(key, val));
                }
            }

            HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
            pmeth.setEntity(entity);
            meth = pmeth;
        }

        // Add olat specific headers to the request, can be used by external
        // applications to identify user and to get other params
        // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py
        if ("enabled".equals(
                CoreSpringFactory.getImpl(BaseSecurityModule.class).getUserInfosTunnelCourseBuildingBlock())) {
            User u = ident.getUser();
            meth.addHeader("X-OLAT-USERNAME", ident.getName());
            meth.addHeader("X-OLAT-LASTNAME", u.getProperty(UserConstants.LASTNAME, null));
            meth.addHeader("X-OLAT-FIRSTNAME", u.getProperty(UserConstants.FIRSTNAME, null));
            meth.addHeader("X-OLAT-EMAIL", u.getProperty(UserConstants.EMAIL, null));
            meth.addHeader("X-OLAT-USERIP", ipAddress);
        }

        HttpResponse response = httpClient.execute(meth);
        if (response == null) {
            // error
            return new NotFoundMediaResource(relPath);
        }

        // get or post successfully
        Header responseHeader = response.getFirstHeader("Content-Type");
        if (responseHeader == null) {
            // error
            EntityUtils.consumeQuietly(response.getEntity());
            return new NotFoundMediaResource(relPath);
        }
        return new HttpRequestMediaResource(response);
    } catch (ClientProtocolException e) {
        log.error("", e);
        return null;
    } catch (URISyntaxException e) {
        log.error("", e);
        return null;
    } catch (IOException e) {
        log.error("Error loading URI: " + (meth == null ? "???" : meth.getURI()), e);
        return null;
    }
}

From source file:org.callimachusproject.server.helpers.Exchange.java

synchronized void closeRequest() {
    if (consumer != null) {
        consumer.close();/*from w ww.  j a  v a2  s  .c  o  m*/
    }
    EntityUtils.consumeQuietly(request.getEntity());
    if (queue != null) {
        synchronized (queue) {
            queue.remove(this);
        }
    }
}

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

private Map getAsMap(String uri) throws Exception {
    HttpGet get = new HttpGet(uri);
    HttpEntity entity = null;//from w  w w. j  av  a  2s.  co m
    try {
        entity = cloudClient.getLbClient().getHttpClient().execute(get).getEntity();
        String response = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        return (Map) ObjectBuilder.getVal(new JSONParser(new StringReader(response)));
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
}

From source file:com.cloudbees.tomcat.valves.PrivateAppValveIntegratedTest.java

@Test
public void form_authentication_scenario() throws Exception {
    System.out.println("form_authentication_scenario");

    privateAppValve.setAuthenticationEntryPoint(PrivateAppValve.AuthenticationEntryPoint.FORM_AUTH);

    {/* w  ww.j  ava  2 s. co  m*/
        // ANONYMOUS REQUEST RENDERS LOGIN FORM
        HttpGet request = new HttpGet("/");
        HttpResponse response = httpClient.execute(httpHost, request);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK));
        assertThat(response.containsHeader("WWW-Form-Authenticate"), is(true));

        dumpHttpResponse(response);

        EntityUtils.consumeQuietly(response.getEntity());
    }
    {
        // AUTHENTICATION REQUEST
        HttpPost request = new HttpPost(privateAppValve.getAuthenticationUri());
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", accessKey));
        nvps.add(new BasicNameValuePair("password", secretKey));
        request.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        HttpResponse response = httpClient.execute(httpHost, request);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_MOVED_TEMPORARILY));

        dumpHttpResponse(response);

        EntityUtils.consumeQuietly(response.getEntity());
    }
    {
        // ALREADY AUTHENTICATED REQUEST

        HttpGet request = new HttpGet("/");
        HttpResponse response = httpClient.execute(httpHost, request);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK));
        assertThat(response.containsHeader("x-response"), is(true));

        dumpHttpResponse(response);

        EntityUtils.consumeQuietly(response.getEntity());
    }
}

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

public Collection<String> extract(String url) {
    CSWCapabilitiesAnalyzer capabilitiesAnalyzer = caps(url);

    CSWAdapter adapter = new CSWAdapter(url);
    adapter.initialize(httpClient, httpClient);

    CSW.VERSION version = CSW.VERSION.fromString("2.0.2");
    adapter.setVersion(version.toString());
    adapter.getNsStore().addNamespace(CSW.getPR(version), CSW.getNS(version));

    CSWOperationGetRecords getRecords = createGetRecords(capabilitiesAnalyzer);

    //getRecords.toKvp(adapter.getNsStore(), version);
    //getRecords.toXml(adapter.getNsStore(), version);

    //adapter.setHttpMethod("POST");

    CSWRequest request = new CSWRequest(adapter, getRecords);

    ExtractWfsUrlsCSWRecordsAnalyzer analyzer = new ExtractWfsUrlsCSWRecordsAnalyzer();
    LoggingCSWRecordsAnalyzer loggingCSWRecordsAnalyzer = new LoggingCSWRecordsAnalyzer();
    MultiCSWRecordsAnalyzer multiCSWRecordsAnalyzer = new MultiCSWRecordsAnalyzer(loggingCSWRecordsAnalyzer,
            analyzer);//from  w w  w . j  a v  a 2s  .c om

    CSWRecordsParser recordParser = new CSWRecordsParser(multiCSWRecordsAnalyzer, staxFactory);

    HttpEntity entity = null;
    int nextRecord = 1;

    while (nextRecord > 0 && analyzer.hasMore()) {
        getRecords.setStartPosition(nextRecord);

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

            recordParser.parse(entity);

            // TODO: loop over nextRecord

            System.out.println();
            System.out.println();
            System.out.println(
                    analyzer.getNumberParsed() + " records of " + analyzer.getNumberMatched() + " parsed");
            System.out.println(analyzer.getUrls().size() + " WFS found:");
            System.out.println(analyzer.getUrls().toString());
            System.out.println();

            nextRecord = analyzer.getNextRecord();

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

    return analyzer.getUrls();
}

From source file:pl.psnc.synat.wrdz.common.https.HttpsClientHelper.java

/**
 * Stores the response entity in the specified folder.
 * /*from   w ww.java 2  s .c o  m*/
 * @param folder
 *            folder where to save entity
 * @param entity
 *            entity
 * @param contentDisposition
 *            Content-Disposition header
 * @return file reference to the saved file
 * @throws IOException
 *             when some IO problem occurred
 */
public File storeResponseEntity(File folder, HttpEntity entity, Header contentDisposition) throws IOException {
    String filename = contentDisposition.getValue().replaceFirst("filename=", "");
    File file = new File(folder, filename);
    try {
        FileOutputStream stream = new FileOutputStream(file);
        try {
            entity.writeTo(stream);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    } catch (IOException e) {
        file.delete();
        throw e;
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
    return file;
}

From source file:org.sonatype.nexus.proxy.maven.routing.internal.AbstractHttpRemoteStrategy.java

/**
 * Returns {@code true} if remote server (proxies by {@link MavenProxyRepository}) is recognized as server that MUST
 * NOT be trusted for any automatic routing feature.
 * // w  w  w.ja  v  a2  s .  com
 * @throws StrategyFailedException if server is recognized as blacklisted.
 */
protected void checkIsBlacklistedRemoteServer(final MavenProxyRepository mavenProxyRepository)
        throws StrategyFailedException, IOException {
    // check URL first, we currently test HTTP and HTTPS only for blacklist, if not, just skip this
    // but do not report blacklist at all (nor attempt)
    final String remoteUrl;
    try {
        remoteUrl = getRemoteUrlOf(mavenProxyRepository);
    } catch (MalformedURLException e) {
        // non HTTP/HTTPS, just return
        return;
    }
    final HttpClient httpClient = createHttpClientFor(mavenProxyRepository);
    {
        // NEXUS-5849: Artifactory will happily serve Central prefixes, effectively shading all the other artifacts from
        // it's group
        final HttpGet get = new HttpGet(remoteUrl);
        final BasicHttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(HttpClientFactory.HTTP_CTX_KEY_REPOSITORY, mavenProxyRepository);
        final HttpResponse response = httpClient.execute(get, httpContext);

        try {
            if (response.containsHeader("X-Artifactory-Id")) {
                log.debug("Remote server of proxy {} recognized as ARTF by response header",
                        mavenProxyRepository);
                throw new StrategyFailedException("Server proxied by " + mavenProxyRepository
                        + " proxy repository is not supported by automatic routing discovery");
            }
            if (response.getStatusLine().getStatusCode() >= 200
                    && response.getStatusLine().getStatusCode() <= 499) {
                if (response.getEntity() != null) {
                    final Document document = Jsoup.parse(response.getEntity().getContent(), null, remoteUrl);
                    final Elements addressElements = document.getElementsByTag("address");
                    if (!addressElements.isEmpty()) {
                        final String addressText = addressElements.get(0).text();
                        if (addressText != null
                                && addressText.toLowerCase(Locale.ENGLISH).startsWith("artifactory")) {
                            log.debug("Remote server of proxy {} recognized as ARTF by address element in body",
                                    mavenProxyRepository);
                            throw new StrategyFailedException("Server proxied by " + mavenProxyRepository
                                    + " proxy repository is not supported by automatic routing discovery");
                        }
                    }
                }
            }
        } finally {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}