Example usage for org.apache.http.client.methods CloseableHttpResponse getEntity

List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse getEntity.

Prototype

HttpEntity getEntity();

Source Link

Usage

From source file:org.wuspba.ctams.ws.ITJudgeController.java

private static void add(Judge j) throws Exception {
    CTAMSDocument doc = new CTAMSDocument();
    doc.getPeople().add(j.getPerson());//from  ww w  .j a  v a  2s .  com
    doc.getJudgeQualifications().addAll(j.getQualifications());
    doc.getJudges().add(j);
    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        j.setId(doc.getJudges().get(0).getId());

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}

From source file:utils.APIImporter.java

/**
 * Adding the API documents to the published API
 * @param folderPath folder path imported API folder
 * @param accessToken access token//from  w  ww. j a v  a  2  s .  c  om
 * @param uuid uuid of the created API
 */
private static void addAPIDocuments(String folderPath, String accessToken, String uuid) {
    String docSummaryLocation = folderPath + ImportExportConstants.DOCUMENT_FILE_LOCATION;
    try {
        //getting the list of documents
        String jsonContent = FileUtils.readFileToString(new File(docSummaryLocation));
        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(jsonContent);
        JSONArray array = (JSONArray) jsonObject.get(ImportExportConstants.DOCUMENT_LIST);
        if (array.size() == 0) {
            String message = "Imported API doesn't have any documents to be publish";
            log.warn(message);
        } else {
            for (Object anArray : array) {
                JSONObject obj = (JSONObject) anArray;
                //publishing each document
                String url = config.getPublisherUrl() + "apis/" + uuid + "/documents";
                CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
                HttpPost request = new HttpPost(url);
                request.setEntity(new StringEntity(obj.toString(), ImportExportConstants.CHARSET));
                request.setHeader(HttpHeaders.AUTHORIZATION,
                        ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken);
                request.setHeader(HttpHeaders.CONTENT_TYPE, ImportExportConstants.CONTENT_JSON);
                CloseableHttpResponse response = client.execute(request);
                if (response.getStatusLine().getStatusCode() == Response.Status.CREATED.getStatusCode()) {
                    String responseString = EntityUtils.toString(response.getEntity(),
                            ImportExportConstants.CHARSET);
                    String sourceType = ImportExportUtils.readJsonValues(responseString,
                            ImportExportConstants.SOURCE_TYPE);
                    if (sourceType.equalsIgnoreCase(ImportExportConstants.FILE_DOC_TYPE)
                            || sourceType.equalsIgnoreCase(ImportExportConstants.INLINE_DOC_TYPE)) {
                        addDocumentContent(folderPath, uuid, responseString, accessToken);
                    }
                } else {
                    String message = "Error occurred while publishing the API document "
                            + obj.get(ImportExportConstants.DOC_NAME) + " " + response.getStatusLine();
                    log.warn(message);
                }
            }
        }
    } catch (IOException e) {
        errorMsg = "error occurred while adding the API documents";
        log.error(errorMsg, e);
    } catch (ParseException e) {
        errorMsg = "error occurred importing the API documents";
        log.error(errorMsg, e);
    }
}

From source file:org.wuspba.ctams.ws.ITJudgeQualificationController.java

protected static void add() throws Exception {
    CTAMSDocument doc = new CTAMSDocument();
    doc.getJudgeQualifications().add(TestFixture.INSTANCE.drummingQual);
    doc.getJudgeQualifications().add(TestFixture.INSTANCE.ensembleQual);
    doc.getJudgeQualifications().add(TestFixture.INSTANCE.pipingQual);
    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {/*ww w  .  ja va 2s  .  c  om*/
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        for (JudgeQualification q : doc.getJudgeQualifications()) {
            if (q.getPanel() == TestFixture.INSTANCE.pipingQual.getPanel()
                    && q.getType() == TestFixture.INSTANCE.pipingQual.getType()) {
                TestFixture.INSTANCE.pipingQual.setId(q.getId());
            } else if (q.getPanel() == TestFixture.INSTANCE.drummingQual.getPanel()
                    && q.getType() == TestFixture.INSTANCE.drummingQual.getType()) {
                TestFixture.INSTANCE.drummingQual.setId(q.getId());
            } else if (q.getPanel() == TestFixture.INSTANCE.ensembleQual.getPanel()
                    && q.getType() == TestFixture.INSTANCE.ensembleQual.getType()) {
                TestFixture.INSTANCE.ensembleQual.setId(q.getId());
            }
        }

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}

From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java

private static InputStream getInputStream(final CloseableHttpResponse response) throws IOException {

    if (response.getEntity() == null) {
        return new ByteArrayInputStream(new byte[0]);
    } else {//  ww w . j av  a 2s  .  c  o m
        final InputStream i = response.getEntity().getContent();
        if (i.markSupported()) {
            return i;
        }
        return new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
    }
}

From source file:org.house.service.spider.WebSpider.java

private static synchronized String doHttpRequest(final HttpRequestBase httpRequestBase) {
    if (lastCallTime == -1) {
        lastCallTime = System.currentTimeMillis();
    }/*from  w ww  . ja  va2s  .c o m*/
    while (true) {
        if (System.currentTimeMillis() - lastCallTime < 300) {
            try {
                Thread.sleep(200);
            } catch (final InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            lastCallTime = System.currentTimeMillis();
            break;
        }
    }
    try {
        final CloseableHttpResponse theResponse = client.execute(httpRequestBase);
        return EntityUtils.toString(theResponse.getEntity());
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.beginner.core.utils.HttpUtil.java

/**
 * <p>To request the POST way.</p>
 * /*from  w  ww  . j a  v a2s.c  om*/
 * @param url      request URI
 * @param json      request parameter(json format string)
 * @param timeout   request timeout time in milliseconds(The default timeout time for 30 seconds.)
 * @return String   response result
 * @throws Exception
 * @since 1.0.0
 */
public static String post(String url, String json, Integer timeout) throws Exception {

    // Validates input
    if (StringUtils.isBlank(url))
        throw new IllegalArgumentException("The url cannot be null and cannot be empty.");

    //The default timeout time for 30 seconds
    if (null == timeout)
        timeout = 30000;

    String result = null;
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;

    try {
        httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "text/plain");
        httpPost.setEntity(new StringEntity(json, "UTF-8"));

        httpResponse = httpClient.execute(httpPost);

        HttpEntity entity = httpResponse.getEntity();

        result = EntityUtils.toString(entity);

        EntityUtils.consume(entity);
    } catch (Exception e) {
        logger.error("POST?", e);
        return null;
    } finally {
        if (null != httpResponse)
            httpResponse.close();
        if (null != httpClient)
            httpClient.close();
    }
    return result;
}

From source file:org.coding.git.api.CodingNetConnection.java

@NotNull
private static CodingNetStatusCodeException getStatusCodeException(@NotNull CloseableHttpResponse response) {
    StatusLine statusLine = response.getStatusLine();
    try {/*from w ww  . j  a v a 2s . c  om*/
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            CodingNetErrorMessage error = fromJson(parseResponse(entity.getContent()),
                    CodingNetErrorMessage.class);
            String message = statusLine.getReasonPhrase() + " - " + error.getMessage();
            return new CodingNetStatusCodeException(message, error, statusLine.getStatusCode());
        }
    } catch (IOException e) {
        LOG.info(e);
    }
    return new CodingNetStatusCodeException(statusLine.getReasonPhrase(), statusLine.getStatusCode());
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClientTest.java

private static CloseableHttpClient recordHttpClientForSingleJsonAndStatusCodeResponse(String jsonResponse,
        int statusCode) throws IOException {
    CloseableHttpResponse httpResponseMock = mock(CloseableHttpResponse.class);
    HttpEntity httpEntityMock = recordHttpEntityForContent(jsonResponse);

    when(httpResponseMock.getEntity()).thenReturn(httpEntityMock);

    StatusLine statusLineMock = recordStatusLine(statusCode);
    when(httpResponseMock.getStatusLine()).thenReturn(statusLineMock);

    CloseableHttpClient httpClientMock = anyCloseableHttpClient();
    when(httpClientMock.execute(any(HttpPost.class), any(HttpContext.class))).thenReturn(httpResponseMock);

    return httpClientMock;
}

From source file:org.wuspba.ctams.ws.ITBandResultController.java

protected static void delete() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("id", TestFixture.INSTANCE.bandResult.getId()).build();

    HttpDelete httpDelete = new HttpDelete(uri);

    CloseableHttpResponse response = null;

    try {//  w  ww.  jav  a2s. co  m
        response = httpclient.execute(httpDelete);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }

    ITBandController.delete();
    ITBandContestController.delete();
}

From source file:org.wuspba.ctams.ws.ITBandController.java

private static void add(Band band) throws Exception {
    CTAMSDocument doc = new CTAMSDocument();
    doc.getBands().add(band);//from w  w w. ja  v  a  2  s .co  m
    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.skye.setId(doc.getBands().get(0).getId());

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}