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.wisdom.framework.vertx.ServerTest.java

@Test
public void testDeny() throws InterruptedException, IOException, KeyStoreException, CertificateException,
        NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException {
    FakeConfiguration s1 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0)
            .put("ssl", false).put("authentication", false).put("deny", ImmutableList.of("/bar*")).build());

    FakeConfiguration s2 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0)
            .put("ssl", false).put("authentication", false).put("deny", ImmutableList.of("/foo*")).build());

    when(application.getConfiguration("vertx.servers"))
            .thenReturn(new FakeConfiguration(ImmutableMap.<String, Object>of("s1", s1, "s2", s2)));

    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok("Alright");
        }//from w w  w  . jav  a2 s.  c o m
    };
    final Route route1 = new RouteBuilder().route(HttpMethod.GET).on("/foo").to(controller, "index");
    final Route route2 = new RouteBuilder().route(HttpMethod.GET).on("/bar").to(controller, "index");
    doAnswer(new Answer<Route>() {
        @Override
        public Route answer(InvocationOnMock mock) throws Throwable {
            String url = (String) mock.getArguments()[1];
            if (url.equals("/foo")) {
                return route1;
            }
            if (url.equals("/bar")) {
                return route2;
            }
            return null;
        }
    }).when(router).getRouteFor(anyString(), anyString(), any(Request.class));

    wisdom.start();
    waitForStart(wisdom);

    assertThat(wisdom.servers).hasSize(2);
    for (Server server : wisdom.servers) {
        if (server.name().equalsIgnoreCase("s1")) {
            // Accept /foo, Deny /bar
            HttpResponse r = org.apache.http.client.fluent.Request
                    .Get("http://localhost:" + server.port() + "/foo").execute().returnResponse();
            assertThat(r.getStatusLine().getStatusCode()).isEqualTo(Status.OK);
            EntityUtils.consumeQuietly(r.getEntity());
            r = org.apache.http.client.fluent.Request.Get("http://localhost:" + server.port() + "/bar")
                    .execute().returnResponse();
            assertThat(r.getStatusLine().getStatusCode()).isEqualTo(Status.FORBIDDEN);
            EntityUtils.consumeQuietly(r.getEntity());
        } else {
            // Accept /foo, Deny /bar
            HttpResponse r = org.apache.http.client.fluent.Request
                    .Get("http://localhost:" + server.port() + "/bar").execute().returnResponse();
            assertThat(r.getStatusLine().getStatusCode()).isEqualTo(Status.OK);
            EntityUtils.consumeQuietly(r.getEntity());
            r = org.apache.http.client.fluent.Request.Get("http://localhost:" + server.port() + "/foo")
                    .execute().returnResponse();
            assertThat(r.getStatusLine().getStatusCode()).isEqualTo(Status.FORBIDDEN);
            EntityUtils.consumeQuietly(r.getEntity());
        }
    }
}

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

@Override
public UpdateTriggerResult updateTrigger(BrianTrigger trigger)
        throws BrianClientException, BrianServerException {
    logger.debug("update trigger: {}/{}", trigger.getGroup(), trigger.getName());
    HttpResponse httpResponse = null;//from   w ww. j av a 2  s  .  c om
    try {
        BrianTriggerRequest request = trigger.toBrianTriggerRequest();
        String requestBody = mapper.writeValueAsString(request);
        logger.trace("update: requestBody = {}", requestBody);
        HttpEntity entity = new StringEntity(requestBody);

        String path = String.format("/triggers/%s/%s", trigger.getGroup(), trigger.getName());
        URI uri = new URI(scheme, null, hostname, port, path, null, null);
        HttpUriRequest httpRequest = RequestBuilder.put().setUri(uri).setEntity(entity).build();
        httpResponse = httpClientExecute(httpRequest);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        logger.debug("statusCode: {}", statusCode);
        JsonNode tree = mapper.readTree(httpResponse.getEntity().getContent());
        if (statusCode == HttpStatus.SC_OK) {
            String nextFireTime = tree.path("content").path("nextFireTime").asText();
            logger.info("trigger updated: nextFireTime = {}", nextFireTime);
            return new UpdateTriggerResult(Instant.parse(nextFireTime));
        } else if (statusCode >= 500) {
            throw new BrianServerException(String.format("status = %d; message = %s",
                    new Object[] { statusCode, tree.get("message").textValue() }));
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            throw new BrianClientException(String.format("triggerKey (%s/%s) is not found",
                    new Object[] { trigger.getGroup(), trigger.getName() }));
        } else if (statusCode >= 400) {
            throw new BrianClientException(String.format("status = %d; message = %s",
                    new Object[] { statusCode, tree.get("message").textValue() }));
        } else {
            throw new Error(String.format("status = %d; message = %s",
                    new Object[] { statusCode, tree.get("message").textValue() }));
        }
    } 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());
        }
    }
}

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

@Test
public void testDeleteStream() throws Exception {
    // treating update and create as same for now, as there is details about
    // how entity payload and media payload can be sent at same time in request's body
    String editUrl = baseURL + "/Airlines('AA')/Picture";
    HttpDelete request = new HttpDelete(editUrl);
    HttpResponse response = httpSend(request, 204);
    EntityUtils.consumeQuietly(response.getEntity());
}

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

protected void verifyPOSTStatusOnly(URI url, int expected, StringEntity content, boolean authenticate)
        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 ww.  j  a  va 2 s.c  om
    }
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(expected, status);
}

From source file:pl.psnc.synat.wrdz.zmkd.plan.MigrationPlanProcessorBean.java

/**
 * Creates a new object in ZMD./*from   www  .ja v a  2 s  . c om*/
 * 
 * @param client
 *            http client instance
 * @param files
 *            map of the new object's files; keys contain the file names/paths inside the new object's structure
 * @param fileSequence
 *            map of the new object's file sequence values; keys contain the file names/paths inside the new
 *            object's structure
 * @param originIdentifier
 *            identifier of the object the new object was migrated from
 * @param originType
 *            the type of migration performed
 * @return creation request identifier
 * @throws IOException
 *             if object upload fails
 */
private String saveObject(HttpClient client, Map<String, File> files, Map<String, Integer> fileSequence,
        String originIdentifier, MigrationType originType) throws IOException {

    DateFormat format = new SimpleDateFormat(ORIGIN_DATE_FORMAT);

    HttpPost post = new HttpPost(zmkdConfiguration.getZmdObjectUrl());
    MultipartEntity entity = new MultipartEntity();

    try {

        entity.addPart(ORIGIN_ID, new StringBody(originIdentifier, ENCODING));
        entity.addPart(ORIGIN_TYPE, new StringBody(originType.name(), ENCODING));
        entity.addPart(ORIGIN_DATE, new StringBody(format.format(new Date()), ENCODING));

        int i = 0;
        for (Entry<String, File> dataFile : files.entrySet()) {
            FileBody file = new FileBody(dataFile.getValue());
            StringBody path = new StringBody(dataFile.getKey(), ENCODING);

            entity.addPart(String.format(FILE_SRC, i), file);
            entity.addPart(String.format(FILE_DEST, i), path);

            if (fileSequence.containsKey(dataFile.getKey())) {
                StringBody seq = new StringBody(fileSequence.get(dataFile.getKey()).toString(), ENCODING);
                entity.addPart(String.format(FILE_SEQ, i), seq);
            }

            i++;
        }
    } catch (UnsupportedEncodingException e) {
        throw new WrdzRuntimeException("The encoding " + ENCODING + " is not supported");
    }

    post.setEntity(entity);

    HttpResponse response = client.execute(post);
    EntityUtils.consumeQuietly(response.getEntity());
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
        String location = response.getFirstHeader("location").getValue();
        return location.substring(location.lastIndexOf('/') + 1);
    } else {
        throw new IOException("Unexpected response: " + response.getStatusLine());
    }
}

From source file:org.bonitasoft.connectors.rest.RESTConnector.java

/**
 * Extracts the response of the HTTP transaction
 * //from w w  w .  ja va  2s . com
 * @param response The response of the sent request
 * @param request
 * @throws
 *         @throws IOException
 */
private void setOutputs(final HttpResponse response, Request request) throws IOException {
    if (response != null) {
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            if (request.isIgnore()) {
                EntityUtils.consumeQuietly(entity);
            } else {
                try (InputStream inputStream = entity.getContent()) {
                    final StringWriter stringWriter = new StringWriter();
                    IOUtils.copy(inputStream, stringWriter);
                    final String stringContent = stringWriter.toString();
                    if (stringContent != null) {
                        setBody(stringContent.trim());
                    }
                }
            }
        }
        if (response.getAllHeaders() != null) {
            setHeaders(Arrays.asList(response.getAllHeaders()));
        }
        setStatusCode(response.getStatusLine().getStatusCode());
        setStatusMessage(response.getStatusLine().getReasonPhrase());
        LOGGER.fine("All outputs have been set.");
    } else {
        LOGGER.fine("Response is null.");
    }
}

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

@Test
public void testReadStream() throws Exception {
    // treating update and create as same for now, as there is details about
    // how entity payload and media payload can be sent at same time in request's body
    String editUrl = baseURL + "/Airlines('AA')/Picture";
    HttpResponse response = httpGET(editUrl, 200);
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:de.tudarmstadt.ukp.shibhttpclient.ShibHttpClient.java

/**
 * Extracts the SOAP message from the HttpResponse
 * @param entity the HttpEntity to retrieve the SOAP message from
 * @return soapEnvelope the SOAP message 
 * @throws IOException //  ww  w. ja  v a2 s  .  c o m
 * @throws IllegalStateException 
 * @throws ClientProtocolException 
 */
protected org.opensaml.ws.soap.soap11.Envelope getSoapMessage(HttpEntity entity)
        throws ClientProtocolException, IllegalStateException, IOException {
    Envelope soapEnvelope = (Envelope) unmarshallMessage(parserPool, entity.getContent());
    EntityUtils.consumeQuietly(entity);
    return soapEnvelope;
}

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

@Test
public void testLambdaAny() throws Exception {
    // this is just testing to see the lamda expressions are going through the
    // framework, none of the system options are not implemented in example service
    String query = "Friends/any(d%3Ad/UserName%20eq%20'foo')";
    HttpResponse response = httpGET(baseURL + "/People?$filter=" + query, 200);
    EntityUtils.consumeQuietly(response.getEntity());
}