List of usage examples for org.apache.http.client.methods CloseableHttpResponse close
public void close() throws IOException;
From source file:org.camunda.bpm.engine.rest.standalone.AbstractEmptyBodyFilterTest.java
private void evaluatePostRequest(HttpEntity reqBody, String reqContentType, int expectedStatusCode, boolean assertResponseBody) throws IOException { HttpPost post = new HttpPost(BASE_URL + START_PROCESS_INSTANCE_BY_KEY_URL); post.setConfig(reqConfig);//w ww.j a v a 2 s . c o m if (reqContentType != null) { post.setHeader(HttpHeaders.CONTENT_TYPE, reqContentType); } post.setEntity(reqBody); CloseableHttpResponse response = client.execute(post); assertEquals(expectedStatusCode, response.getStatusLine().getStatusCode()); if (assertResponseBody) { assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, new JSONObject(EntityUtils.toString(response.getEntity(), "UTF-8")).get("id")); } response.close(); }
From source file:com.wattzap.model.social.SelfLoopsAPI.java
public static int uploadActivity(String email, String passWord, String fileName, String note) throws IOException { JSONObject jsonObj = null;// www.ja v a 2 s. com FileInputStream in = null; GZIPOutputStream out = null; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); httpPost.setHeader("enctype", "multipart/mixed"); in = new FileInputStream(fileName); // Create stream to compress data and write it to the to file. ByteArrayOutputStream obj = new ByteArrayOutputStream(); out = new GZIPOutputStream(obj); // Copy bytes from one stream to the other byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } out.close(); in.close(); ByteArrayBody bin = new ByteArrayBody(obj.toByteArray(), ContentType.create("application/x-gzip"), fileName); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("email", new StringBody(email, ContentType.TEXT_PLAIN)) .addPart("pw", new StringBody(passWord, ContentType.TEXT_PLAIN)).addPart("tcxfile", bin) .addPart("note", new StringBody(note, ContentType.TEXT_PLAIN)).build(); httpPost.setEntity(reqEntity); CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); int code = response.getStatusLine().getStatusCode(); switch (code) { case 200: HttpEntity respEntity = response.getEntity(); if (respEntity != null) { // EntityUtils to get the response content String content = EntityUtils.toString(respEntity); //System.out.println(content); JSONParser jsonParser = new JSONParser(); jsonObj = (JSONObject) jsonParser.parse(content); } break; case 403: throw new RuntimeException( "Authentification failure " + email + " " + response.getStatusLine()); default: throw new RuntimeException("Error " + code + " " + response.getStatusLine()); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (response != null) { response.close(); } } int activityId = ((Long) jsonObj.get("activity_id")).intValue(); // parse error code int error = ((Long) jsonObj.get("error_code")).intValue(); if (activityId == -1) { String message = (String) jsonObj.get("message"); switch (error) { case 102: throw new RuntimeException("Empty TCX file " + fileName); case 103: throw new RuntimeException("Invalide TCX Format " + fileName); case 104: throw new RuntimeException("TCX Already Present " + fileName); case 105: throw new RuntimeException("Invalid XML " + fileName); case 106: throw new RuntimeException("invalid compression algorithm"); case 107: throw new RuntimeException("Invalid file mime types"); default: throw new RuntimeException(message + " " + error); } } return activityId; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } httpClient.close(); } }
From source file:org.apache.felix.http.itest.SessionHandlingTest.java
private JSONObject getJSONResponse(final CloseableHttpClient client, final String path) throws IOException, ParseException { final HttpGet httpGet = new HttpGet(createURL(path).toExternalForm().toString()); CloseableHttpResponse response1 = client.execute(httpGet); try {//from ww w. ja v a 2s. co m HttpEntity entity1 = response1.getEntity(); final String content = EntityUtils.toString(entity1); return (JSONObject) JSONValue.parseWithException(content); } finally { response1.close(); } }
From source file:org.wso2.carbon.ml.analysis.test.ModelConfigurationsTestCase.java
/** * Test setting default values to hyper-parameters of an analysis. * /* w w w .j av a2 s .c o m*/ * @throws MLHttpClientException * @throws IOException */ @Test(priority = 3, description = "Set default values to hyperparameters") public void testSetDefaultHyperparameters() throws MLHttpClientException, IOException { CloseableHttpResponse response = mlHttpclient .doHttpPost("/api/analyses/" + analysisId + "/hyperParams/defaults", null); assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); response.close(); }
From source file:org.wso2.carbon.ml.dataset.test.CreateDatasetTestCase.java
/** * Test creating a dataset without version. * /*from ww w.j a v a2 s . com*/ * @throws MLHttpClientException * @throws IOException */ @Test(description = "Create a dataset without version") public void testCreateDatasetWithoutVersion() throws MLHttpClientException, IOException { CloseableHttpResponse response = mlHttpclient.uploadDatasetFromCSV("SampleDataForCreateDatasetTestCase_3", null, MLIntegrationTestConstants.DIABETES_DATASET_SAMPLE); assertEquals("Unexpected response received", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusLine().getStatusCode()); response.close(); }
From source file:org.wso2.carbon.ml.project.test.MLProjectsTestCase.java
/** * Test retrieving projects of a dataset with analyses. * // w w w .j a v a2s. c om * @throws MLHttpClientException * @throws IOException */ @Test(priority = 5, description = "Retrieve projects of a dataset with analyses") public void testGetProjectsOfDatasetWithAnalyses() throws MLHttpClientException, IOException { CloseableHttpResponse response = mlHttpclient.doHttpGet( "/api/projects/analyses?datasetName=" + MLIntegrationTestConstants.DATASET_NAME_DIABETES); assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); response.close(); }
From source file:fr.treeptik.cloudunit.cli.rest.RestUtils.java
/** * sendGetCommand/*from w w w . java 2 s .c o m*/ * * @param url * @param parameters * @return */ public Map<String, String> sendGetCommand(String url, Map<String, Object> parameters) throws ManagerResponseException { Map<String, String> response = new HashMap<String, String>(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); try { CloseableHttpResponse httpResponse = httpclient.execute(httpget, localContext); ResponseHandler<String> handler = new CustomResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put("body", body); httpResponse.close(); } catch (Exception e) { throw new ManagerResponseException(e.getMessage(), e); } return response; }
From source file:com.ccc.crest.servlet.auth.CrestAuthCallback.java
private void getVerifyData(Base20ClientInfo clientInfo) throws Exception { Properties properties = CoreController.getController().getProperties(); String verifyUrl = properties.getProperty(CrestController.OauthVerifyUrlKey, CrestController.OauthVerifyUrlDefault); String userAgent = properties.getProperty(CrestController.UserAgentKey, CrestController.UserAgentDefault); //@formatter:off CloseableHttpClient httpclient = HttpClients.custom().setUserAgent(userAgent).build(); //@formatter:on String accessToken = ((OAuth2AccessToken) clientInfo.getAccessToken()).getAccessToken(); HttpGet httpGet = new HttpGet(verifyUrl); httpGet.addHeader("Authorization", "Bearer " + accessToken); CloseableHttpResponse response1 = httpclient.execute(httpGet); try {//ww w .j ava 2 s . c o m HttpEntity entity1 = response1.getEntity(); InputStream is = entity1.getContent(); String json = IOUtils.toString(is, "UTF-8"); is.close(); ((CrestClientInfo) clientInfo).setVerifyData(OauthVerify.getOauthVerifyData(json)); EntityUtils.consume(entity1); } finally { response1.close(); } }
From source file:net.xenqtt.httpgateway.HttpGatewayHandler.java
/** * The handler sets the response status, content-type, and marks the request as handled before it generates the body of the response using a writer. There * are a number of built in <a href="http://download.eclipse.org/jetty/stable-9/xref/org/eclipse/jetty/server/handler/package-summary.html">handlers</a> * that might come in handy.//from ww w .j ava2 s . c o m * * @param target * the target of the request, which is either a URI or a name from a named dispatcher. * @param baseRequest * the Jetty mutable request object, which is always unwrapped. * @param request * the immutable request object, which may have been wrapped by a filter or servlet. * @param response * the response, which may have been wrapped by a filter or servlet. * * @see org.eclipse.jetty.server.Handler#handle(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // FIXME [jim] - make sure http 1.1 persistent connections are being used on both server and client sides CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://www.google.com" + target); CloseableHttpResponse response1 = httpclient.execute(httpGet); try { response.setStatus(response1.getStatusLine().getStatusCode()); HttpEntity entity = response1.getEntity(); InputStream in = entity.getContent(); OutputStream out = response.getOutputStream(); for (int i = in.read(); i >= 0; i = in.read()) { out.write(i); } } finally { response1.close(); } baseRequest.setHandled(true); // TODO Auto-generated method stub }
From source file:eu.riscoss.datacollector.fossology.FossologyRiskDataCollector.java
public void createIndicators(IndicatorsMap indicatorsMap, Properties properties) throws Exception { String targetFossology = properties.getProperty(TARGET_FOSSOLOGY_PROPERTY); if (targetFossology == null) { throw new Exception(String.format("%s property not speficied", TARGET_FOSSOLOGY_PROPERTY)); }/* w ww. j a v a 2 s . co m*/ LicenseAnalysisReport licenseAnalysisReport = null; if (targetFossology.toLowerCase().startsWith("http")) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet get = new HttpGet(targetFossology); CloseableHttpResponse response = httpClient.execute(get); try { HttpEntity entity = response.getEntity(); licenseAnalysisReport = parseLicenseAnalysisReport(entity.getContent()); EntityUtils.consume(entity); } finally { response.close(); } } else { licenseAnalysisReport = parseLicenseAnalysisReport(new FileInputStream(targetFossology)); } indicatorsMap.add("number-of-different-licenses", licenseAnalysisReport.numberOfLicenses); //Number of (different?) component licenses indicatorsMap.add("percentage-of-files-without-license", ((double) licenseAnalysisReport.filesWithoutLicense / (double) licenseAnalysisReport.totalFiles)); indicatorsMap.add("files-with-unknown-license", ((double) licenseAnalysisReport.filesWithUnknownLicense / (double) licenseAnalysisReport.totalFiles)); indicatorsMap.add("copyleft-licenses", ((double) licenseAnalysisReport.filesWithCopyleftLicense / (double) licenseAnalysisReport.totalFiles)); indicatorsMap.add("copyleft-licenses-with-linking", ((double) licenseAnalysisReport.filesWithCopyleftWithLinkingLicense / (double) licenseAnalysisReport.totalFiles)); indicatorsMap.add("percentage-of-files-with-permissive-license", ((double) licenseAnalysisReport.filesWithPermissiveLicense / (double) licenseAnalysisReport.totalFiles)); indicatorsMap.add("files-with-commercial-license", ((double) licenseAnalysisReport.filesWithCommercialLicense / (double) licenseAnalysisReport.totalFiles)); //TODO //"percentage-of-files-with-public-domain-license" //"files-with-ads-required-license", 0); }