List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:com.evrythng.java.wrapper.util.FileUtils.java
/** * Uploads text as a file content with PRIVATE read access. * * @param uri upload {@link URI}/*from ww w.ja va 2 s . c o m*/ * @param contentTypeString content type * @param contentString text content * @throws IOException */ public static void uploadPrivateContent(final URI uri, final String contentTypeString, final String contentString) throws IOException { LOGGER.info("uploadPrivateContent START: uri: [{}]; content type: [{}], content length: [{}]", new Object[] { uri, contentTypeString, contentString.length() }); CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpPut httpPut = new HttpPut(uri); httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString); httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE); ContentType contentType = ContentType.create(contentTypeString); StringEntity stringEntity = new StringEntity(contentString, contentType); httpPut.setEntity(stringEntity); CloseableHttpResponse response = closeableHttpClient.execute(httpPut); StatusLine statusLine = response.getStatusLine(); if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) { throw new IOException(String.format("An error occurred while trying to upload private file - %d: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase())); } LOGGER.info("uploadPrivateContent END: uri: [{}]; content type: [{}], content length: [{}]", new Object[] { uri, contentTypeString, contentString.length() }); }
From source file:org.wuspba.ctams.ws.ITVenueController.java
protected static void add() throws Exception { CTAMSDocument doc = new CTAMSDocument(); doc.getVenues().add(TestFixture.INSTANCE.venue); 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 {/*w w w .j av a 2 s. co m*/ httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); TestFixture.INSTANCE.venue.setId(doc.getVenues().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.ITHiredJudgeController.java
protected static void add() throws Exception { ITJudgeController.add();/*from ww w.j av a 2 s. c o m*/ CTAMSDocument doc = new CTAMSDocument(); doc.getPeople().add(TestFixture.INSTANCE.andy); doc.getPeople().add(TestFixture.INSTANCE.jamie); doc.getPeople().add(TestFixture.INSTANCE.bob); doc.getPeople().add(TestFixture.INSTANCE.eoin); 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.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeAndy); doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeJamie); doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeBob); doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeEoin); 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); for (HiredJudge j : doc.getHiredJudges()) { if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeAndy.getId())) { TestFixture.INSTANCE.hiredJudgeAndy.setId(j.getId()); } else if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeBob.getId())) { TestFixture.INSTANCE.hiredJudgeBob.setId(j.getId()); } else if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeJamie.getId())) { TestFixture.INSTANCE.hiredJudgeJamie.setId(j.getId()); } else if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeEoin.getId())) { TestFixture.INSTANCE.hiredJudgeEoin.setId(j.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:de.adesso.referencer.search.helper.MyHelpMethods.java
public static String sendHttpRequest(String url, String requestBody, String requestType) throws IOException { String result = null;//from w w w . j a va2 s .c o m CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse httpResponse; try { switch (requestType) { case "Get": httpResponse = httpclient.execute(new HttpGet(url)); break; case "Post": HttpPost httppost = new HttpPost(url); if (requestBody != null) { httppost.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET)); } httpResponse = httpclient.execute(httppost); break; case "Put": HttpPut httpPut = new HttpPut(url); httpPut.addHeader("Content-Type", "application/json"); httpPut.addHeader("Accept", "application/json"); if (requestBody != null) { httpPut.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET)); } httpResponse = httpclient.execute(httpPut); break; case "Delete": httpResponse = httpclient.execute(new HttpDelete(url)); break; default: httpResponse = httpclient.execute(new HttpGet(url)); break; } try { HttpEntity entity1 = httpResponse.getEntity(); if (entity1 != null) { long len = entity1.getContentLength(); if (len != -1 && len < MAX_CONTENT_LENGTH) { result = EntityUtils.toString(entity1, DEFAULT_CHARSET); } else { System.out.println("Error!!!! entity length=" + len); } } EntityUtils.consume(entity1); } finally { httpResponse.close(); } } catch (Exception e) { e.printStackTrace(); } finally { httpclient.close(); } return result; }
From source file:de.adesso.referencer.search.helper.MyHelpMethods.java
public static String sendHttpRequest2(String url, String requestBody, String requestType) throws IOException { String result = null;/*from w ww . j av a2 s . c o m*/ CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse httpResponse; try { switch (requestType) { case "Get": httpResponse = httpclient.execute(new HttpGet(url)); break; case "Post": HttpPost httppost = new HttpPost(url); if (requestBody != null) { httppost.setEntity(new StringEntity(requestBody)); } httpResponse = httpclient.execute(httppost); break; case "Put": HttpPut httpPut = new HttpPut(url); httpPut.addHeader("Content-Type", "application/json"); httpPut.addHeader("Accept", "application/json"); if (requestBody != null) { httpPut.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET)); } httpResponse = httpclient.execute(httpPut); break; case "Delete": httpResponse = httpclient.execute(new HttpDelete(url)); break; default: httpResponse = httpclient.execute(new HttpGet(url)); break; } try { HttpEntity entity1 = httpResponse.getEntity(); if (entity1 != null) { long len = entity1.getContentLength(); if (len != -1 && len < MAX_CONTENT_LENGTH) { result = EntityUtils.toString(entity1, DEFAULT_CHARSET); } else { System.out.println("Error!!!! entity length=" + len); } } EntityUtils.consume(entity1); } finally { httpResponse.close(); } } catch (Exception e) { e.printStackTrace(); } finally { httpclient.close(); } return result; }
From source file:org.glowroot.tests.WebDriverSetup.java
private static Container createContainer(int uiPort, File testDir) throws Exception { File adminFile = new File(testDir, "admin.json"); Files.asCharSink(adminFile, UTF_8).write("{\"web\":{\"port\":" + uiPort + "}}"); Container container;//from w ww . j a v a 2 s .c o m if (Containers.useJavaagent()) { container = new JavaagentContainer(testDir, true, ImmutableList.of()); } else { container = new LocalContainer(testDir, true, ImmutableMap.of()); } // wait for UI to be available (UI starts asynchronously in order to not block startup) CloseableHttpClient httpClient = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy()) .build(); Stopwatch stopwatch = Stopwatch.createStarted(); Exception lastException = null; while (stopwatch.elapsed(SECONDS) < 10) { HttpGet request = new HttpGet("http://localhost:" + uiPort); try (CloseableHttpResponse response = httpClient.execute(request); InputStream content = response.getEntity().getContent()) { ByteStreams.exhaust(content); lastException = null; break; } catch (Exception e) { lastException = e; } } httpClient.close(); if (lastException != null) { throw new IllegalStateException("Timed out waiting for Glowroot UI", lastException); } return container; }
From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java
/** * Get the contents of a redirect URL and use as reponse for the provided HttpServletResponse. * If possible, pass in error responses as well. * @param redirectURIStr   /*from w ww .ja v a2s.c om*/ * @param resp HttpServletResponse * @throws IOException   */ public static void proxyURL(String redirectURIStr, HttpServletResponse resp) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet getMethod = new HttpGet(redirectURIStr); getMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/ try (CloseableHttpResponse response = httpclient.execute(getMethod)) { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); HashSet<String> proxiedHeaders = new HashSet<String>(); proxiedHeaders.addAll(Arrays.asList(MimeResponse.PROXIED_HEADERS)); Header[] headers = response.getAllHeaders(); for (Header header : headers) { if (proxiedHeaders.contains(header.getName())) { logger.debug("Adding headerName " + header.getName() + " and value " + header.getValue() + " when proxying request"); resp.addHeader(header.getName(), header.getValue()); } } if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); try (OutputStream os = resp.getOutputStream(); InputStream is = new BufferedInputStream(entity.getContent())) { byte buf[] = new byte[10 * 1024]; int bytesRead = is.read(buf); while (bytesRead > 0) { os.write(buf, 0, bytesRead); resp.flushBuffer(); bytesRead = is.read(buf); } } } else { throw new IOException("HTTP response did not have an entity associated with it"); } } else { logger.error("Invalid status code " + response.getStatusLine().getStatusCode() + " when connecting to URL " + redirectURIStr + ". Sending the errorstream across"); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { try (InputStream is = new BufferedInputStream(response.getEntity().getContent())) { byte buf[] = new byte[10 * 1024]; int bytesRead = is.read(buf); while (bytesRead > 0) { os.write(buf, 0, bytesRead); bytesRead = is.read(buf); } } resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); resp.sendError(response.getStatusLine().getStatusCode(), new String(os.toByteArray())); } } } }
From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java
private static InputStream getURLContentAsStream(String serverURL) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet getMethod = new HttpGet(serverURL); getMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/ getMethod.addHeader(ARCHAPPL_COMPONENT, "true"); HttpResponse response = httpclient.execute(getMethod); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); // ArchiverValuesHandler takes over the burden of closing the input stream. InputStream is = entity.getContent(); return is; } else {//w ww.ja v a 2s. c o m throw new IOException("HTTP response did not have an entity associated with it"); } } else { throw new IOException("Invalid status calling " + serverURL + ". Got " + response.getStatusLine().getStatusCode() + response.getStatusLine().getReasonPhrase()); } }
From source file:utils.APIExporter.java
/** * This method get the API thumbnail and write in to the zip file * @param uuid API id of the API/*from w w w . ja v a 2 s . c om*/ * @param accessToken valide access token with view scope * @param APIFolderpath archive base path */ private static void exportAPIThumbnail(String uuid, String accessToken, String APIFolderpath) { ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance(); try { //REST API call to get API thumbnail String url = config.getPublisherUrl() + "apis/" + uuid + "/thumbnail"; CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate()); HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken); CloseableHttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); //assigning the response in to inputStream BufferedHttpEntity httpEntity = new BufferedHttpEntity(entity); InputStream imageStream = httpEntity.getContent(); byte[] byteArray = IOUtils.toByteArray(imageStream); InputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(byteArray)); //getting the mime type of the input Stream String mimeType = URLConnection.guessContentTypeFromStream(inputStream); //getting file extension String extension = getThumbnailFileType(mimeType); OutputStream outputStream = null; if (extension != null) { //writing image in to the archive try { outputStream = new FileOutputStream(APIFolderpath + File.separator + "icon." + extension); IOUtils.copy(httpEntity.getContent(), outputStream); } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(imageStream); IOUtils.closeQuietly(inputStream); } } } catch (IOException e) { log.error("Error occurred while exporting the API thumbnail"); } }
From source file:utils.APIImporter.java
/** * update the content of a document of the API been sent * @param folderPath folder path to the imported API * @param uuid uuid of the API/*from w w w . j a v a 2 s . c o m*/ * @param response payload for the publishing document * @param accessToken access token */ private static void addDocumentContent(String folderPath, String uuid, String response, String accessToken) { String documentId = ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_ID); String sourceType = ImportExportUtils.readJsonValues(response, ImportExportConstants.SOURCE_TYPE); String documentName = ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME); String directoryName; //setting directory name depending on the document source type if (sourceType.equals(ImportExportConstants.INLINE_DOC_TYPE)) { directoryName = ImportExportConstants.INLINE_DOCUMENT_DIRECTORY; } else { directoryName = ImportExportConstants.FILE_DOCUMENT_DIRECTORY; } //getting document content String documentContentPath = folderPath + ImportExportConstants.DIRECTORY_SEPARATOR + ImportExportConstants.DOCUMENT_DIRECTORY + ImportExportConstants.DIRECTORY_SEPARATOR + directoryName + ImportExportConstants.DIRECTORY_SEPARATOR + documentName; File content = new File(documentContentPath); HttpEntity entity = null; if (sourceType.equals(ImportExportConstants.FILE_DOC_TYPE)) { //adding file type content MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody(ImportExportConstants.MULTIPART_FILE, content); entity = multipartEntityBuilder.build(); } else { BufferedReader br = null; try { br = new BufferedReader(new FileReader(content)); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append("\n"); line = br.readLine(); } String inlineContent = sb.toString(); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addTextBody(ImportExportConstants.MULTIPART_Inline, inlineContent, ContentType.APPLICATION_OCTET_STREAM); entity = multipartEntityBuilder.build(); } catch (IOException e) { errorMsg = "error occurred while retrieving content of document " + ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME); log.error(errorMsg, e); } finally { IOUtils.closeQuietly(br); } } String url = config.getPublisherUrl() + "apis/" + uuid + "/documents/" + documentId + "/content"; CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate()); HttpPost request = new HttpPost(url); request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken); request.setEntity(entity); try { client.execute(request); } catch (IOException e) { errorMsg = "error occurred while uploading the content of document " + ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME); log.error(errorMsg, e); } }