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:io.github.thred.climatetray.ClimateTrayUtils.java

public static BuildInfo performBuildInfoRequest() {
    try {//w ww .j av  a  2s . co  m
        CloseableHttpClient client = ClimateTray.PREFERENCES.getProxySettings().createHttpClient();
        HttpGet request = new HttpGet(BUILD_INFO_URL);
        CloseableHttpResponse response;

        try {
            response = client.execute(request);
        } catch (IOException e) {
            ClimateTray.LOG.warn("Failed to request build information from \"%s\".", e, BUILD_INFO_URL);

            consumeUpdateFailed();

            return null;
        }

        try {
            int status = response.getStatusLine().getStatusCode();

            if ((status >= 200) && (status < 300)) {
                try (InputStream in = response.getEntity().getContent()) {
                    BuildInfo buildInfo = BuildInfo.create(in);

                    ClimateTray.LOG.info("Build Information: %s", buildInfo);

                    return buildInfo;
                }
            } else {
                ClimateTray.LOG.warn("Request to \"%s\" failed with error %d.", BUILD_INFO_URL, status);

                consumeUpdateFailed();
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        ClimateTray.LOG.warn("Failed to request build information.", e);
    }

    return null;
}

From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.RnrMergerAndRanker.java

/**
 * Deletes the specified ranker//from  w  ww.ja  va 2s. com
 * 
 * @param ranker_id ofthe ranker to be deleted
 * @throws ClientProtocolException
 * @throws IOException
 * @throws JSONException
 */
public static void deleteRanker(CloseableHttpClient client, String ranker_id)
        throws ClientProtocolException, IOException {

    JSONObject res;

    try {
        HttpDelete httpdelete = new HttpDelete(ranker_url + "/" + ranker_id);
        httpdelete.setHeader("Content-Type", "application/json");
        CloseableHttpResponse response = client.execute(httpdelete);

        try {

            String result = EntityUtils.toString(response.getEntity());
            res = (JSONObject) JSON.parse(result);
            if (res.isEmpty()) {
                logger.info(MessageFormat.format(Messages.getString("RetrieveAndRank.RANKER_DELETE"), //$NON-NLS-1$
                        ranker_id));
            } else {
                logger.info(MessageFormat.format(Messages.getString("RetrieveAndRank.RANKER_DELETE_FAIL"), //$NON-NLS-1$
                        ranker_id));
            }
        } catch (NullPointerException | JSONException e) {
            logger.error(e.getMessage());
        }

        finally {
            response.close();
        }
    }

    finally {
        client.close();
    }
}

From source file:gda.util.ElogEntry.java

/**
 * Creates an ELog entry. Default ELog server is "http://rdb.pri.diamond.ac.uk/devl/php/elog/cs_logentryext_bl.php"
 * which is the development database. "http://rdb.pri.diamond.ac.uk/php/elog/cs_logentryext_bl.php" is the
 * production database. The java.properties file contains the property "gda.elog.targeturl" which can be set to be
 * either the development or production databases.
 * /* w  w w.  j  a v a2 s.c o  m*/
 * @param title
 *            The ELog title
 * @param content
 *            The ELog content
 * @param userID
 *            The user ID e.g. epics or gda or abc12345
 * @param visit
 *            The visit number
 * @param logID
 *            The type of log book, The log book ID: Beam Lines: - BLB16, BLB23, BLI02, BLI03, BLI04, BLI06, BLI11,
 *            BLI16, BLI18, BLI19, BLI22, BLI24, BLI15, DAG = Data Acquisition, EHC = Experimental Hall
 *            Coordinators, OM = Optics and Meteorology, OPR = Operations, E
 * @param groupID
 *            The group sending the ELog, DA = Data Acquisition, EHC = Experimental Hall Coordinators, OM = Optics
 *            and Meteorology, OPR = Operations CS = Control Systems, GroupID Can also be a beam line,
 * @param fileLocations
 *            The image file names with path to upload
 * @throws ELogEntryException
 */
public static void post(String title, String content, String userID, String visit, String logID, String groupID,
        String[] fileLocations) throws ELogEntryException {
    String targetURL = POST_UPLOAD_URL;
    try {
        String entryType = "41";// entry type is always a log (41)
        String titleForPost = visit == null ? title : "Visit: " + visit + " - " + title;

        MultipartEntityBuilder request = MultipartEntityBuilder.create().addTextBody("txtTITLE", titleForPost)
                .addTextBody("txtCONTENT", content).addTextBody("txtLOGBOOKID", logID)
                .addTextBody("txtGROUPID", groupID).addTextBody("txtENTRYTYPEID", entryType)
                .addTextBody("txtUSERID", userID);

        if (fileLocations != null) {
            for (int i = 1; i < fileLocations.length + 1; i++) {
                File targetFile = new File(fileLocations[i - 1]);
                request = request.addBinaryBody("userfile" + i, targetFile, ContentType.create("image/png"),
                        targetFile.getName());
            }
        }

        HttpEntity entity = request.build();
        targetURL = LocalProperties.get("gda.elog.targeturl", POST_UPLOAD_URL);
        HttpPost httpPost = new HttpPost(targetURL);
        httpPost.setEntity(entity);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            String responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
            if (!responseString.contains("New Log Entry ID")) {
                throw new ELogEntryException("Upload failed, status=" + response.getStatusLine().getStatusCode()
                        + " response=" + responseString + " targetURL = " + targetURL + " titleForPost = "
                        + titleForPost + " logID = " + logID + " groupID = " + groupID + " entryType = "
                        + entryType + " userID = " + userID);
            }
        } finally {
            response.close();
            httpClient.close();
        }
    } catch (ELogEntryException e) {
        throw e;
    } catch (Exception e) {
        throw new ELogEntryException("Error in ELogger.  Database:" + targetURL, e);
    }
}

From source file:com.linecorp.armeria.server.http.file.HttpFileServiceTest.java

private static void assert304NotModified(CloseableHttpResponse res, String expectedLastModified) {

    assertStatusLine(res, "HTTP/1.1 304 Not Modified");

    // Ensure that the 'Last-Modified' header did not change.
    assertThat(res.getFirstHeader(HttpHeaders.LAST_MODIFIED).getValue(), is(expectedLastModified));

    // Ensure that the content does not exist.
    assertThat(res.getEntity(), is(nullValue()));
}

From source file:com.networknt.light.server.handler.loader.FormLoader.java

/**
 * Get all forms from the server and construct a map in order to compare content
 * to detect changes or not.//from   www .  j a v  a2s  .  co  m
 *
 */
private static void getFormMap(String host) {

    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "form");
    inputMap.put("name", "getFormMap");
    inputMap.put("readOnly", true);

    CloseableHttpResponse response = null;
    try {
        HttpPost httpPost = new HttpPost(host + "/api/rs");
        httpPost.addHeader("Authorization", "Bearer " + jwt);
        StringEntity input = new StringEntity(
                ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
        input.setContentType("application/json");
        httpPost.setEntity(input);
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        EntityUtils.consume(entity);
        System.out.println("Got form map from server");
        if (json != null && json.trim().length() > 0) {
            formMap = ServiceLocator.getInstance().getMapper().readValue(json,
                    new TypeReference<HashMap<String, Map<String, Object>>>() {
                    });
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

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

protected static void add() throws Exception {
    ITBandController.add();/* ww  w  .  ja v a  2  s  .  c  o m*/

    CTAMSDocument doc = new CTAMSDocument();
    doc.getBands().add(TestFixture.INSTANCE.skye);
    doc.getBandRegistrations().add(TestFixture.INSTANCE.bandRegistration);

    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.bandRegistration.setId(doc.getBandRegistrations().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:org.wuspba.ctams.ws.ITSoloRegistrationController.java

private static void add() throws Exception {
    ITPersonController.add();//  w ww  . jav a 2 s  .  c o m

    CTAMSDocument doc = new CTAMSDocument();
    doc.getPeople().add(TestFixture.INSTANCE.elaine);
    doc.getSoloRegistrations().add(TestFixture.INSTANCE.soloRegistration);

    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.soloRegistration.setId(doc.getSoloRegistrations().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:org.wuspba.ctams.ws.ITSoloResultController.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.soloResult.getId()).build();

    HttpDelete httpDelete = new HttpDelete(uri);

    CloseableHttpResponse response = null;

    try {/*from   ww  w .  j  av a 2 s .c om*/
        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);
            }
        }
    }

    ITSoloContestController.delete();
}

From source file:com.aliyun.oss.common.comm.DefaultServiceClient.java

protected static ResponseMessage buildResponse(ServiceClient.Request request,
        CloseableHttpResponse httpResponse) throws IOException {

    assert (httpResponse != null);

    ResponseMessage response = new ResponseMessage(request);
    response.setUrl(request.getUri());//ww w  . j a v a2s  . c  o  m
    response.setHttpResponse(httpResponse);

    if (httpResponse.getStatusLine() != null) {
        response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
    }

    if (httpResponse.getEntity() != null) {
        if (response.isSuccessful()) {
            response.setContent(httpResponse.getEntity().getContent());
        } else {
            readAndSetErrorResponse(httpResponse.getEntity().getContent(), response);
        }
    }

    for (Header header : httpResponse.getAllHeaders()) {
        if (HttpHeaders.CONTENT_LENGTH.equals(header.getName())) {
            response.setContentLength(Long.parseLong(header.getValue()));
        }
        response.addHeader(header.getName(), header.getValue());
    }

    HttpUtil.convertHeaderCharsetFromIso88591(response.getHeaders());

    return response;
}

From source file:utils.APIImporter.java

/**
 * Updated an existing API/* w ww.  java 2s. c  om*/
 * @param payload payload to update the API
 * @param apiId API id of the updating API (provider-name-version)
 * @param token access token
 * @param folderPath folder path to the imported API folder
 */
private static void updateApi(String payload, String apiId, String token, String folderPath)
        throws APIImportException {
    String url = config.getPublisherUrl() + "apis/" + apiId;
    CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
    HttpPut request = new HttpPut(url);
    request.setEntity(new StringEntity(payload, ImportExportConstants.CHARSET));
    request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + token);
    request.setHeader(HttpHeaders.CONTENT_TYPE, ImportExportConstants.CONTENT_JSON);
    try {
        CloseableHttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == Response.Status.OK.getStatusCode()) {
            //getting API uuid
            String responseString = EntityUtils.toString(response.getEntity());
            String uuid = ImportExportUtils.readJsonValues(responseString, ImportExportConstants.UUID);
            updateAPIDocumentation(uuid, apiId, token, folderPath);
            addAPIImage(folderPath, token, uuid);
            System.out.println("API " + apiId + " updated successfully");
        } else {
            String status = response.getStatusLine().toString();
            log.error(status);
            System.out.println(apiId + " update unsuccessful");
        }
    } catch (IOException e) {
        errorMsg = "Error occurred while updating, API " + apiId;
        log.error(errorMsg, e);
        throw new APIImportException(errorMsg, e);
    }
}