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.cloudbees.tomcat.valves.PrivateAppValveIntegratedTest.java

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

    privateAppValve.setAuthenticationEntryPoint(PrivateAppValve.AuthenticationEntryPoint.BASIC_AUTH);

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

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

    dumpHttpResponse(response);//from  www . j a  v  a 2  s. c  om

    EntityUtils.consumeQuietly(response.getEntity());

}

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

/**
 * Handles an authentication request.// w  w w .ja va  2  s  . co  m
 * @param request HTTP request
 * @param response HTTP response
 * @return an authentication object that contains the principal object if successful.
 * @throws IOException ex
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    final String requestURI = request.getRequestURI();
    UserAuthentication userAuth = null;

    if (requestURI.endsWith(GOOGLE_ACTION)) {
        String authCode = request.getParameter("code");
        if (!StringUtils.isBlank(authCode)) {
            String entity = Utils.formatMessage(PAYLOAD, URLEncoder.encode(authCode, "UTF-8"),
                    URLEncoder.encode(request.getRequestURL().toString(), "UTF-8"), Config.GPLUS_APP_ID,
                    Config.GPLUS_SECRET);

            HttpPost tokenPost = new HttpPost(TOKEN_URL);
            tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
            tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
            CloseableHttpResponse resp1 = httpclient.execute(tokenPost);

            if (resp1 != null && resp1.getEntity() != null) {
                Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
                if (token != null && token.containsKey("access_token")) {
                    userAuth = getOrCreateUser(null, (String) token.get("access_token"));
                }
                EntityUtils.consumeQuietly(resp1.getEntity());
            }
        }
    }

    User user = SecurityUtils.getAuthenticatedUser(userAuth);

    if (userAuth == null || user == null || user.getIdentifier() == null) {
        throw new BadCredentialsException("Bad credentials.");
    } else if (!user.getActive()) {
        throw new LockedException("Account is locked.");
    }
    return userAuth;
}

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

/**
 * Handles an authentication request.//from   w  w w .j  ava 2s. c o m
 * @param request HTTP request
 * @param response HTTP response
 * @return an authentication object that contains the principal object if successful.
 * @throws IOException ex
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    final String requestURI = request.getRequestURI();
    UserAuthentication userAuth = null;

    if (requestURI.endsWith(GITHUB_ACTION)) {
        String authCode = request.getParameter("code");
        if (!StringUtils.isBlank(authCode)) {
            String entity = Utils.formatMessage(PAYLOAD, URLEncoder.encode(authCode, "UTF-8"),
                    URLEncoder.encode(request.getRequestURL().toString(), "UTF-8"), Config.GITHUB_APP_ID,
                    Config.GITHUB_SECRET);

            HttpPost tokenPost = new HttpPost(TOKEN_URL);
            tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
            tokenPost.setHeader(HttpHeaders.ACCEPT, "application/json");
            tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
            CloseableHttpResponse resp1 = httpclient.execute(tokenPost);

            if (resp1 != null && resp1.getEntity() != null) {
                Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
                if (token != null && token.containsKey("access_token")) {
                    userAuth = getOrCreateUser(null, (String) token.get("access_token"));
                }
                EntityUtils.consumeQuietly(resp1.getEntity());
            }
        }
    }

    User user = SecurityUtils.getAuthenticatedUser(userAuth);

    if (userAuth == null || user == null || user.getIdentifier() == null) {
        throw new BadCredentialsException("Bad credentials.");
    } else if (!user.getActive()) {
        throw new LockedException("Account is locked.");
    }
    return userAuth;
}

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

/**
 * Now send a request which creates a session
 *//*  w  w  w.  j  a  va 2 s  .  co m*/
@Test
@RunAsClient
@InSequence(3)
public void sendRequestToCreateSession(@ArquillianResource URL contextPath) throws Exception {
    String url = new URL(contextPath, "create-session").toString();
    HttpResponse response = client.execute(new HttpGet(url));
    assertEquals(200, response.getStatusLine().getStatusCode());
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:net.ychron.unirestinst.http.HttpResponse.java

@SuppressWarnings("unchecked")
public HttpResponse(Options options, org.apache.http.HttpResponse response, Class<T> responseClass) {
    HttpEntity responseEntity = response.getEntity();
    ObjectMapper objectMapper = (ObjectMapper) options.getOption(Option.OBJECT_MAPPER);

    Header[] allHeaders = response.getAllHeaders();
    for (Header header : allHeaders) {
        String headerName = header.getName();
        List<String> list = headers.get(headerName);
        if (list == null)
            list = new ArrayList<String>();
        list.add(header.getValue());//from  ww  w  .ja v  a 2s  .  c om
        headers.put(headerName, list);
    }
    StatusLine statusLine = response.getStatusLine();
    this.statusCode = statusLine.getStatusCode();
    this.statusText = statusLine.getReasonPhrase();

    if (responseEntity != null) {
        String charset = "UTF-8";

        Header contentType = responseEntity.getContentType();
        if (contentType != null) {
            String responseCharset = ResponseUtils.getCharsetFromContentType(contentType.getValue());
            if (responseCharset != null && !responseCharset.trim().equals("")) {
                charset = responseCharset;
            }
        }

        try {
            byte[] rawBody;
            try {
                InputStream responseInputStream = responseEntity.getContent();
                if (ResponseUtils.isGzipped(responseEntity.getContentEncoding())) {
                    responseInputStream = new GZIPInputStream(responseEntity.getContent());
                }
                rawBody = ResponseUtils.getBytes(responseInputStream);
            } catch (IOException e2) {
                throw new RuntimeException(e2);
            }
            this.rawBody = new ByteArrayInputStream(rawBody);

            if (JsonNode.class.equals(responseClass)) {
                String jsonString = new String(rawBody, charset).trim();
                this.body = (T) new JsonNode(jsonString);
            } else if (String.class.equals(responseClass)) {
                this.body = (T) new String(rawBody, charset);
            } else if (InputStream.class.equals(responseClass)) {
                this.body = (T) this.rawBody;
            } else if (objectMapper != null) {
                this.body = objectMapper.readValue(new String(rawBody, charset), responseClass);
            } else {
                throw new Exception(
                        "Only String, JsonNode and InputStream are supported, or an ObjectMapper implementation is required.");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    EntityUtils.consumeQuietly(responseEntity);
}

From source file:org.sonatype.nexus.apachehttpclient.page.Page.java

/**
 * Returns a page for given HTTP request.
 *///  w w  w.  ja  v  a 2s.c  om
public static Page buildPageFor(final PageContext context, final HttpUriRequest httpUriRequest)
        throws IOException {
    checkNotNull(context);
    checkNotNull(httpUriRequest);
    // TODO: detect redirects
    LOG.debug("Executing HTTP {} request against {}", httpUriRequest.getMethod(), httpUriRequest.getURI());
    final HttpResponse response = context.executeHttpRequest(httpUriRequest);
    try {
        if (context.isExpectedResponse(response)) {
            if (response.getEntity() != null) {
                return new Page(httpUriRequest, response, Jsoup.parse(response.getEntity().getContent(), null,
                        httpUriRequest.getURI().toString()));
            } else {
                // no body
                return new Page(httpUriRequest, response, null);
            }
        } else {
            throw new UnexpectedPageResponse(httpUriRequest.getURI().toString(), response.getStatusLine());
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

From source file:org.olat.core.commons.services.webdav.WebDAVConnection.java

public int propfindTry(URI uri, int depth) throws IOException, URISyntaxException {
    HttpPropFind propfind = new HttpPropFind(uri);
    propfind.addHeader("Depth", Integer.toString(depth));
    HttpResponse response = execute(propfind);
    EntityUtils.consumeQuietly(response.getEntity());
    return response.getStatusLine().getStatusCode();
}

From source file:tds.itemscoringengine.web.server.ItemScoringEngineHttpWebHelper.java

public void sendXml(String url, ItemScoreResponse inputData, OutputStream outputData) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type", "text/xml");
    HttpResponse response = null;//from   ww w. j av a 2s .c  om
    try {
        inputData.writeXML(out);
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        post.setEntity(entity);
        response = _client.execute(post, _contextPool.get());
    } catch (IOException | XMLStreamException e) {
        try {
            outputData.write(String.format("HTTP client through exception: %s", e.getMessage()).getBytes());
        } catch (IOException e1) {
            // Our IOExceptioin through an IOException--bad news!!!
            _logger.error("Output stream encountered an error while attempting to process an error message",
                    e1);
            _logger.error(String.format("Original drror message was \"\"", e.getMessage()));
        }
    }
    if (response != null) {
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            String responseString = "";
            try {
                responseString = EntityUtils.toString(responseEntity);
                outputData.write(responseString.getBytes());
            } catch (IOException e) {
                // Our IOExceptioin through an IOException--bad news!!!
                _logger.error("Output stream encountered an error while attempting to process a reply", e);
                _logger.error(String.format("Original reply content was \"\"", responseString));
            }
            EntityUtils.consumeQuietly(responseEntity);
        }
    }
}

From source file:cf.randers.scd.CommandLineInterface.java

private void run() {
    if (params == null)
        return;//  ww  w .j a v a 2s . c  o  m
    LOGGER.info("Making temp dir...");
    File tmpDir = new File("tmp/");
    File outDir = new File(outputDirectory);
    //noinspection ResultOfMethodCallIgnored
    tmpDir.mkdirs();
    //noinspection ResultOfMethodCallIgnored
    outDir.mkdirs();
    BlockingQueue<Runnable> tasks = new ArrayBlockingQueue<>(params.size());
    maximumConcurrentConnections = Math.min(params.size(),
            maximumConcurrentConnections > params.size() ? params.size() : maximumConcurrentConnections);
    ThreadPoolExecutor executor = new ThreadPoolExecutor(maximumConcurrentConnections,
            maximumConcurrentConnections, 0, TimeUnit.NANOSECONDS, tasks);
    LOGGER.info("Starting to execute " + params.size() + " thread(s)...");
    for (String param : params) {
        executor.execute(() -> {
            LOGGER.info("Started thread for " + param);
            Map json;
            byte[] artworkBytes = new byte[0];
            List<Track> toProcess = new ArrayList<>();
            LOGGER.info("Resolving and querying track info...");
            try (CloseableHttpClient client = HttpClients.createDefault();
                    CloseableHttpResponse response = client.execute(new HttpGet(new URIBuilder()
                            .setScheme("https").setHost("api.soundcloud.com").setPath("/resolve")
                            .addParameter("url", param).addParameter("client_id", clientID).build()));
                    InputStreamReader inputStreamReader = new InputStreamReader(
                            response.getEntity().getContent())) {

                final int bufferSize = 1024;
                final char[] buffer = new char[bufferSize];
                final StringBuilder out = new StringBuilder();
                for (;;) {
                    int rsz = inputStreamReader.read(buffer, 0, buffer.length);
                    if (rsz < 0)
                        break;
                    out.append(buffer, 0, rsz);
                }
                String rawJson = out.toString();
                Album a = new Gson().fromJson(rawJson, Album.class);

                if (a.getTrackCount() == null) {
                    Track tr = new Gson().fromJson(rawJson, Track.class);
                    toProcess.add(tr);
                }
                toProcess.addAll(a.getTracks());
                EntityUtils.consumeQuietly(response.getEntity());
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            for (Track track : toProcess) {
                System.out.println(track.getId());
                System.out.println(track.getTitle());
            }
            for (Track track : toProcess) {
                LOGGER.info("Downloading mp3 to file...");
                File tmpFile = new File("tmp/" + String.format("%d", track.getId()) + ".mp3");

                try (CloseableHttpClient client = HttpClients.createDefault();
                        CloseableHttpResponse response = client
                                .execute(new HttpGet(track.getStreamUrl() + "?client_id=" + clientID))) {
                    IOUtils.copy(response.getEntity().getContent(), new FileOutputStream(tmpFile));
                    EntityUtils.consumeQuietly(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }

                boolean hasArtwork = track.getArtworkUrl() != null;

                if (hasArtwork) {
                    LOGGER.info("Downloading artwork jpg into memory...");
                    try (CloseableHttpClient client = HttpClients.createDefault();
                            CloseableHttpResponse response = client.execute(
                                    new HttpGet(track.getArtworkUrl().replace("-large.jpg", "-t500x500.jpg")
                                            + "?client_id=" + clientID))) {
                        artworkBytes = IOUtils.toByteArray(response.getEntity().getContent());
                        EntityUtils.consumeQuietly(response.getEntity());
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                }

                try {
                    LOGGER.info("Reading temp file into AudioFile object...");
                    // Read audio file from tmp directory
                    AudioFile audioFile = AudioFileIO.read(tmpFile);

                    // Set Artwork
                    Tag tag = audioFile.getTagAndConvertOrCreateAndSetDefault();
                    if (hasArtwork) {
                        StandardArtwork artwork = new StandardArtwork();
                        artwork.setBinaryData(artworkBytes);
                        artwork.setImageFromData();
                        tag.addField(artwork);
                    }
                    tag.addField(FieldKey.TITLE, track.getTitle());
                    tag.addField(FieldKey.ARTIST, track.getUser().getUsername());
                    LOGGER.info("Saving audio file...");
                    System.out.println(
                            outDir.getAbsolutePath() + "/" + String.format(outputformat, track.getId()));
                    new AudioFileIO().writeFile(audioFile,
                            outDir.getAbsolutePath() + "/" + String.format(outputformat, track.getId()));
                    tmpFile.deleteOnExit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            File[] listFiles = tmpDir.listFiles();
            if (listFiles == null) {
                return;
            }
            for (File file : listFiles) {
                file.delete();
            }
        });
    }
    executor.shutdown();
}

From source file:com.cloudbees.servlet.filters.PrivateAppFilterIntegratedTest.java

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

    privateAppFilter.setAuthenticationEntryPoint(PrivateAppFilter.AuthenticationEntryPoint.BASIC_AUTH);

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

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

    dumpHttpResponse(response);//from   ww  w .j a  va 2 s . c om

    EntityUtils.consumeQuietly(response.getEntity());

}