List of usage examples for org.apache.http.client.methods CloseableHttpResponse getStatusLine
StatusLine getStatusLine();
From source file:org.cloudsimulator.utility.RestAPI.java
public static ResponseMessageByteArray receiveByteArray(final String restAPIURI, final String username, final String password, final String typeOfByteArray) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; ResponseMessageByteArray responseMessageByteArray = null; httpResponse = getRequestBasicAuth(httpClient, escapeURI(restAPIURI), username, password, typeOfByteArray); if (httpResponse != null) { if (httpResponse.getStatusLine() != null) { if (httpResponse.getEntity() != null) { responseMessageByteArray = new ResponseMessageByteArray( httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), IOUtils.toByteArray(httpResponse.getEntity().getContent())); } else { responseMessageByteArray = new ResponseMessageByteArray( httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), null); }/*ww w . j a v a2 s. c om*/ } else { if (httpResponse.getEntity() != null) { responseMessageByteArray = new ResponseMessageByteArray(null, null, IOUtils.toByteArray(httpResponse.getEntity().getContent())); } } httpResponse.close(); } httpClient.close(); return responseMessageByteArray; }
From source file:com.magnet.tools.tests.RestStepDefs.java
@When("^I send the following Rest queries:$") public static void sendRestQueries(List<RestQueryEntry> entries) throws Throwable { for (RestQueryEntry e : entries) { String url = expandVariables(e.url); StatusLine statusLine;//from ww w . jav a2 s. c o m HttpUriRequest httpRequest; HttpEntity entityResponse; CloseableHttpClient httpClient = getTestHttpClient(new URI(url)); Object body = isStringNotEmpty(e.body) ? e.body : getRef(e.bodyRef); String verb = e.verb; if ("GET".equalsIgnoreCase(verb)) { httpRequest = new HttpGet(url); } else if ("POST".equalsIgnoreCase(verb)) { httpRequest = new HttpPost(url); ((HttpPost) httpRequest).setEntity(new StringEntity(expandVariables((String) body))); } else if ("PUT".equalsIgnoreCase(verb)) { httpRequest = new HttpPut(url); ((HttpPut) httpRequest).setEntity(new StringEntity(expandVariables((String) body))); } else if ("DELETE".equalsIgnoreCase(verb)) { httpRequest = new HttpDelete(url); } else { throw new IllegalArgumentException("Unknown verb: " + e.verb); } String response; setHttpHeaders(httpRequest, e); ScenarioUtils.log("Sending HTTP Request: " + e.url); CloseableHttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpRequest); statusLine = httpResponse.getStatusLine(); entityResponse = httpResponse.getEntity(); InputStream is = entityResponse.getContent(); response = IOUtils.toString(is); EntityUtils.consume(entityResponse); } finally { if (null != httpResponse) { try { httpResponse.close(); } catch (Exception ex) { /* do nothing */ } } } ScenarioUtils.log("====> Received response body:\n " + response); Assert.assertNotNull(response); setHttpResponseBody(response); if (isStringNotEmpty(e.expectedResponseBody)) { // inline the assertion check on http response body ensureHttpResponseBody(e.expectedResponseBody); } if (isStringNotEmpty(e.expectedResponseBodyRef)) { // inline the assertion check on http response body ensureHttpResponseBody((String) getRef(e.expectedResponseBodyRef)); } if (isStringNotEmpty(e.expectedResponseContains)) { // inline the assertion check on http response body ensureHttpResponseBodyContains(e.expectedResponseContains); } if (null == statusLine) { throw new IllegalArgumentException("Status line in http response is null, request was " + e.url); } int statusCode = statusLine.getStatusCode(); ScenarioUtils.log("====> Received response code: " + statusCode); setHttpResponseStatus(statusCode); if (isStringNotEmpty(e.expectedResponseStatus)) { // inline the assertion check on http status ensureHttpResponseStatus(Integer.parseInt(e.expectedResponseStatus)); } } }
From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java
/** * <p>Index a single document into EL server.</p> *//*from w w w .j a v a 2 s. c o m*/ protected static void addDocument(CloseableHttpClient httpclient, String type, String document) throws Exception { HttpPost httpPut = new HttpPost(urlBuilder.getIndexRoot() + "/" + type); StringEntity inputData = new StringEntity(document); inputData.setContentType(CONTENTTYPE_JSON); httpPut.addHeader(HEADER_ACCEPT, CONTENTTYPE_JSON); httpPut.addHeader(HEADER_CONTENTTYPE, CONTENTTYPE_JSON); httpPut.setEntity(inputData); CloseableHttpResponse dataResponse = httpclient.execute(httpPut); if (dataResponse.getStatusLine().getStatusCode() != EL_REST_RESPONSE_CREATED) { System.out.println("Error response body:"); System.out.println(responseAsString(dataResponse)); } Assert.assertEquals(dataResponse.getStatusLine().getStatusCode(), EL_REST_RESPONSE_CREATED); }
From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java
/** * <p>Index documents in bulk mode into EL server.</p> *//*from w w w . ja va2s. c o m*/ protected static void addDocuments(CloseableHttpClient httpClient, File dataContentFile) throws Exception { HttpPost httpPost2 = new HttpPost(urlBuilder.getBulk()); FileEntity inputData = new FileEntity(dataContentFile); inputData.setContentType(CONTENTTYPE_JSON); httpPost2.addHeader(HEADER_ACCEPT, CONTENTTYPE_JSON); httpPost2.addHeader(HEADER_CONTENTTYPE, CONTENTTYPE_JSON); httpPost2.setEntity(inputData); CloseableHttpResponse dataResponse = httpClient.execute(httpPost2); if (dataResponse.getStatusLine().getStatusCode() != EL_REST_RESPONSE_OK) { System.out.println("Error response body:"); System.out.println(responseAsString(dataResponse)); } httpPost2.completed(); Assert.assertEquals(dataResponse.getStatusLine().getStatusCode(), EL_REST_RESPONSE_OK); }
From source file:de.xwic.appkit.core.remote.client.URemoteAccessClient.java
/** * @param param/* ww w. j a v a 2 s . co m*/ * @param config * @return */ public static byte[] postRequest(final IRequestHelper helper, final RemoteSystemConfiguration config) { CloseableHttpResponse response = null; try { CloseableHttpClient client = PoolingHttpConnectionManager.getInstance().getClientInstance(config); HttpPost post = new HttpPost(helper.getTargetUrl()); post.setEntity(helper.getHttpEntity()); response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new RemoteDataAccessException(response.getStatusLine().getReasonPhrase()); } return EntityUtils.toByteArray(response.getEntity()); } catch (RemoteDataAccessException re) { throw re; } catch (Exception e) { throw new RemoteDataAccessException(e); } finally { if (response != null) { try { response.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } }
From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java
public static void createIndexELServer() throws Exception { // Create an http client CloseableHttpClient httpclient = HttpClients.createDefault(); // Obtain data to configure & populate the server. String mappingsContent = getFileAsString(EL_EXAMPLE_MAPPINGS); // Create an index mappings. HttpPost httpPost = new HttpPost(urlBuilder.getIndexRoot()); StringEntity inputMappings = new StringEntity(mappingsContent); inputMappings.setContentType(CONTENTTYPE_JSON); httpPost.setEntity(inputMappings);/*ww w . j av a 2 s. co m*/ CloseableHttpResponse mappingsResponse = httpclient.execute(httpPost); if (mappingsResponse.getStatusLine().getStatusCode() != EL_REST_RESPONSE_OK) { System.out.println("Error response body:"); System.out.println(responseAsString(mappingsResponse)); } Assert.assertEquals(EL_REST_RESPONSE_OK, mappingsResponse.getStatusLine().getStatusCode()); }
From source file:io.github.thred.climatetray.ClimateTrayUtils.java
public static BuildInfo performBuildInfoRequest() { try {/* www . j a va 2 s .c om*/ 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.frochr123.fabqr.FabQRFunctions.java
public static void uploadFabQRProject(String name, String email, String projectName, int licenseIndex, String tools, String description, String location, BufferedImage imageReal, BufferedImage imageScheme, PlfFile plfFile, String lasercutterName, String lasercutterMaterial) throws Exception { // Check for valid situation, otherwise abort if (MainView.getInstance() == null || VisicutModel.getInstance() == null || VisicutModel.getInstance().getPlfFile() == null || !isFabqrActive() || getFabqrPrivateURL() == null || getFabqrPrivateURL().isEmpty() || MaterialManager.getInstance() == null || MappingManager.getInstance() == null || VisicutModel.getInstance().getSelectedLaserDevice() == null) { throw new Exception("FabQR upload exception: Critical error"); }//w w w.j a v a 2s . c o m // Check valid data if (name == null || email == null || projectName == null || projectName.length() < 3 || licenseIndex < 0 || tools == null || tools.isEmpty() || description == null || description.isEmpty() || location == null || location.isEmpty() || imageScheme == null || plfFile == null || lasercutterName == null || lasercutterName.isEmpty() || lasercutterMaterial == null || lasercutterMaterial.isEmpty()) { throw new Exception("FabQR upload exception: Invalid input data"); } // Convert images to byte data for PNG, imageReal is allowed to be empty byte[] imageSchemeBytes = null; ByteArrayOutputStream imageSchemeOutputStream = new ByteArrayOutputStream(); PreviewImageExport.writePngToOutputStream(imageSchemeOutputStream, imageScheme); imageSchemeBytes = imageSchemeOutputStream.toByteArray(); if (imageSchemeBytes == null) { throw new Exception("FabQR upload exception: Error converting scheme image"); } byte[] imageRealBytes = null; if (imageReal != null) { // Need to convert image, ImageIO.write messes up the color space of the original input image BufferedImage convertedImage = new BufferedImage(imageReal.getWidth(), imageReal.getHeight(), BufferedImage.TYPE_3BYTE_BGR); ColorConvertOp op = new ColorConvertOp(null); op.filter(imageReal, convertedImage); ByteArrayOutputStream imageRealOutputStream = new ByteArrayOutputStream(); ImageIO.write(convertedImage, "jpg", imageRealOutputStream); imageRealBytes = imageRealOutputStream.toByteArray(); } // Extract all URLs from used QR codes List<String> referencesList = new LinkedList<String>(); List<PlfPart> plfParts = plfFile.getPartsCopy(); for (PlfPart plfPart : plfParts) { if (plfPart.getQRCodeInfo() != null && plfPart.getQRCodeInfo().getQRCodeSourceURL() != null && !plfPart.getQRCodeInfo().getQRCodeSourceURL().trim().isEmpty()) { // Process url, if it is URL of a FabQR system, remove download flag and point to project page instead // Use regex to check for FabQR system URL structure String qrCodeUrl = plfPart.getQRCodeInfo().getQRCodeSourceURL().trim(); // Check for temporary URL structure of FabQR system Pattern fabQRUrlTemporaryPattern = Pattern .compile("^https{0,1}://.*?" + "/" + FABQR_TEMPORARY_MARKER + "/" + "([a-z]|[0-9]){7,7}$"); // Do not include link if it is just temporary if (fabQRUrlTemporaryPattern.matcher(qrCodeUrl).find()) { continue; } // Check for download URL structure of FabQR system // Change URL to point to project page instead Pattern fabQRUrlDownloadPattern = Pattern .compile("^https{0,1}://.*?" + "/" + FABQR_DOWNLOAD_MARKER + "/" + "([a-z]|[0-9]){7,7}$"); if (fabQRUrlDownloadPattern.matcher(qrCodeUrl).find()) { qrCodeUrl = qrCodeUrl.replace("/" + FABQR_DOWNLOAD_MARKER + "/", "/"); } // Add URL if it is not yet in list if (!referencesList.contains(qrCodeUrl)) { referencesList.add(qrCodeUrl); } } } String references = ""; for (String ref : referencesList) { // Add comma for non first entries if (!references.isEmpty()) { references = references + ","; } references = references + ref; } // Get bytes for PLF file byte[] plfFileBytes = null; ByteArrayOutputStream plfFileOutputStream = new ByteArrayOutputStream(); VisicutModel.getInstance().savePlfToStream(MaterialManager.getInstance(), MappingManager.getInstance(), plfFileOutputStream); plfFileBytes = plfFileOutputStream.toByteArray(); if (plfFileBytes == null) { throw new Exception("FabQR upload exception: Error saving PLF file"); } // Begin uploading data String uploadUrl = getFabqrPrivateURL() + FABQR_API_UPLOAD_PROJECT; // Create HTTP client and cusomized config for timeouts CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(FABQR_UPLOAD_TIMEOUT) .setConnectTimeout(FABQR_UPLOAD_TIMEOUT).setConnectionRequestTimeout(FABQR_UPLOAD_TIMEOUT).build(); // Create HTTP Post request and entity builder HttpPost httpPost = new HttpPost(uploadUrl); httpPost.setConfig(requestConfig); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); // Insert file uploads multipartEntityBuilder.addBinaryBody("imageScheme", imageSchemeBytes, ContentType.APPLICATION_OCTET_STREAM, "imageScheme.png"); multipartEntityBuilder.addBinaryBody("inputFile", plfFileBytes, ContentType.APPLICATION_OCTET_STREAM, "inputFile.plf"); // Image real is allowed to be null, if it is not, send it if (imageRealBytes != null) { multipartEntityBuilder.addBinaryBody("imageReal", imageRealBytes, ContentType.APPLICATION_OCTET_STREAM, "imageReal.png"); } // Prepare content type for text data, especially needed for correct UTF8 encoding ContentType contentType = ContentType.create("text/plain", Consts.UTF_8); // Insert text data multipartEntityBuilder.addTextBody("name", name, contentType); multipartEntityBuilder.addTextBody("email", email, contentType); multipartEntityBuilder.addTextBody("projectName", projectName, contentType); multipartEntityBuilder.addTextBody("licenseIndex", new Integer(licenseIndex).toString(), contentType); multipartEntityBuilder.addTextBody("tools", tools, contentType); multipartEntityBuilder.addTextBody("description", description, contentType); multipartEntityBuilder.addTextBody("location", location, contentType); multipartEntityBuilder.addTextBody("lasercutterName", lasercutterName, contentType); multipartEntityBuilder.addTextBody("lasercutterMaterial", lasercutterMaterial, contentType); multipartEntityBuilder.addTextBody("references", references, contentType); // Assign entity to this post request HttpEntity httpEntity = multipartEntityBuilder.build(); httpPost.setEntity(httpEntity); // Set authentication information String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(), FabQRFunctions.getFabqrPrivatePassword()); if (!encodedCredentials.isEmpty()) { httpPost.addHeader("Authorization", "Basic " + encodedCredentials); } // Send request CloseableHttpResponse res = httpClient.execute(httpPost); // React to possible server side errors if (res.getStatusLine() == null || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new Exception("FabQR upload exception: Server sent wrong HTTP status code: " + new Integer(res.getStatusLine().getStatusCode()).toString()); } // Close everything correctly res.close(); httpClient.close(); }
From source file:utils.APIImporter.java
/** * Updated an existing API/*from w w w . j a va 2 s.c o m*/ * @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); } }
From source file:org.wuspba.ctams.ws.ITBandContestEntryController.java
private static void add() throws Exception { ITVenueController.add();/* w w w .jav a 2 s. co m*/ ITJudgeController.add(); ITBandController.add(); ITBandContestController.add(); CTAMSDocument doc = new CTAMSDocument(); doc.getVenues().add(TestFixture.INSTANCE.venue); doc.getJudges().add(TestFixture.INSTANCE.judgeAndy); doc.getJudges().add(TestFixture.INSTANCE.judgeJamie); doc.getJudges().add(TestFixture.INSTANCE.judgeBob); doc.getJudges().add(TestFixture.INSTANCE.judgeEoin); doc.getBandContests().add(TestFixture.INSTANCE.bandContest); doc.getBands().add(TestFixture.INSTANCE.skye); doc.getBandContestEntry().add(TestFixture.INSTANCE.bandContestEntry); 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.bandContestEntry.setId(doc.getBandContestEntry().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); } } } }