List of usage examples for org.apache.http.entity FileEntity FileEntity
public FileEntity(File file)
From source file:ch.asadzia.cognitive.EmotionDetect.java
public ServiceResult process() { HttpClient httpclient = HttpClients.createDefault(); try {/* w w w . ja v a2 s .co m*/ URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/emotion/v1.0/recognize"); URI uri = builder.build(); HttpPost request = new HttpPost(uri); request.setHeader("Content-Type", "application/octet-stream"); request.setHeader("Ocp-Apim-Subscription-Key", apikey); // Request body FileEntity reqEntity = new FileEntity(imageData); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { String responseStr = EntityUtils.toString(entity); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.println(responseStr); return null; } JSONArray jsonArray = (JSONArray) new JSONParser().parse(responseStr); JSONObject jsonObject = (JSONObject) jsonArray.get(0); HashMap<char[], Double> scores = (HashMap) jsonObject.get("scores"); Map.Entry<char[], Double> maxEntry = null; for (Map.Entry<char[], Double> entry : scores.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) { maxEntry = entry; } } Object key = maxEntry.getKey(); String winningEmotionName = (String) key; ServiceResult result = new ServiceResult(translateEmotion(winningEmotionName), winningEmotionName); System.out.println(responseStr); return result; } } catch (Exception e) { System.err.println(e.toString()); } return null; }
From source file:ch.asadzia.cognitive.SituationAnalysis.java
public ServiceResult process() { HttpClient httpclient = HttpClients.createDefault(); try {// w w w .java2s .co m URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/vision/v1.0/analyze"); builder.setParameter("visualFeatures", "Categories,Tags,Description,Faces,Adult"); URI uri = builder.build(); HttpPost request = new HttpPost(uri); request.setHeader("Content-Type", "application/octet-stream"); request.setHeader("Ocp-Apim-Subscription-Key", apikey); // Request body FileEntity reqEntity = new FileEntity(imageData); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { String responseStr = EntityUtils.toString(entity); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.println(responseStr); return null; } ServiceResult result = translateSituation(responseStr); System.out.println(responseStr); return result; } } catch (Exception e) { System.out.println(e.getMessage()); } return null; }
From source file:com.mber.client.HTTParty.java
public static Call put(final String url, final File file) throws IOException { FileEntity entity = new FileEntity(file); entity.setContentType("application/octet-stream"); HttpPut request = new HttpPut(url); request.setEntity(entity);/*from www .j a v a 2 s . co m*/ return execute(request); }
From source file:com.vmware.content.samples.client.util.HttpUtil.java
/** * Uploads a file from local storage to a given HTTP URI. * * @param localFile local storage path to the file to upload. * @param uploadUri HTTP URI where the file needs to be uploaded. * @throws java.security.NoSuchAlgorithmException * @throws java.security.KeyStoreException * @throws java.security.KeyManagementException * @throws java.io.IOException//from w ww .j a va 2s. c om */ public static void uploadFileToUri(File localFile, URI uploadUri) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException { CloseableHttpClient httpClient = getCloseableHttpClient(); HttpPut request = new HttpPut(uploadUri); HttpEntity content = new FileEntity(localFile); request.setEntity(content); HttpResponse response = httpClient.execute(request); EntityUtils.consumeQuietly(response.getEntity()); }
From source file:gov.nih.nci.system.web.client.RESTfulCreateClient.java
public Response create(File fileLoc, String url) { try {//w w w . ja va2 s. com if (url == null) { ResponseBuilder builder = Response.status(Status.BAD_REQUEST); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INVALID_URL</code>"); buffer.append("<message>Invalid URL: " + url + "</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); return builder.build(); } if (fileLoc == null || !fileLoc.exists()) { ResponseBuilder builder = Response.status(Status.BAD_REQUEST); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INVALID_FILE</code>"); buffer.append("<message>Invalid File given to read</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); return builder.build(); } DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPut putRequest = new HttpPut(url); FileEntity input = new FileEntity(fileLoc); input.setContentType("application/xml"); if (userName != null && password != null) { String base64encodedUsernameAndPassword = new String( Base64.encodeBase64((userName + ":" + password).getBytes())); putRequest.addHeader("Authorization", "Basic " + base64encodedUsernameAndPassword); } putRequest.setEntity(input); HttpResponse response = httpClient.execute(putRequest); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); while ((output = br.readLine()) != null) { buffer.append(output); } ResponseBuilder builder = Response.status(Status.CREATED); builder.type("application/xml"); buffer.append("</response>"); builder.entity(buffer.toString()); httpClient.getConnectionManager().shutdown(); return builder.build(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.eclipse.packagedrone.testing.server.channel.UploadApiV2Test.java
protected CloseableHttpResponse upload(final URIBuilder uri, final File file) throws IOException, URISyntaxException { final HttpPut httppost = new HttpPut(uri.build()); httppost.setEntity(new FileEntity(file)); return httpclient.execute(httppost); }
From source file:org.n52.oss.IT.ValidatorIT.java
private String executeCheckRequest(String testFile) throws IOException, ClientProtocolException { String responseString = null; File f = new File(getClass().getResource(testFile).getFile()); HttpPost post = new HttpPost(smlCheckEndpoint); HttpEntity entity = new FileEntity(f); post.setEntity(entity);//w w w. j a v a 2s .c o m post.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); try (CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = client.execute(post);) { HttpEntity responseEntity = response.getEntity(); responseString = EntityUtils.toString(responseEntity); } return responseString; }
From source file:com.amazonaws.devicefarm.DeviceFarmUploader.java
/** * Upload a single file, waits for upload to complete. * @param file the file/* www. j a v a 2 s. c om*/ * @param project the project * @param uploadType the upload type * @return upload object */ public Upload upload(final File file, final Project project, final UploadType uploadType) { if (!(file.exists() && file.canRead())) { throw new DeviceFarmException(String.format("File %s does not exist or is not readable", file)); } final CreateUploadRequest appUploadRequest = new CreateUploadRequest().withName(file.getName()) .withProjectArn(project.getArn()).withContentType("application/octet-stream") .withType(uploadType.toString()); final Upload upload = api.createUpload(appUploadRequest).getUpload(); final CloseableHttpClient httpClient = HttpClients.createDefault(); final HttpPut httpPut = new HttpPut(upload.getUrl()); httpPut.setHeader("Content-Type", upload.getContentType()); final FileEntity entity = new FileEntity(file); httpPut.setEntity(entity); writeToLog(String.format("Uploading %s to S3", file.getName())); final HttpResponse response; try { response = httpClient.execute(httpPut); } catch (IOException e) { throw new DeviceFarmException(String.format("Error uploading artifact %s", file), e); } if (response.getStatusLine().getStatusCode() != 200) { throw new DeviceFarmException(String.format("Upload returned non-200 responses: %s", response.getStatusLine().getStatusCode())); } waitForUpload(file, upload); return upload; }
From source file:gov.nih.nci.system.web.client.RESTfulUpdateClient.java
public Response update(File fileLoc, String url) { try {//from ww w . jav a 2 s . com if (url == null) { System.out.println("Invalid URL"); ResponseBuilder builder = Response.status(Status.BAD_REQUEST); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INVALID_URL</code>"); buffer.append("<message>Invalid URL: " + url + "</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); return builder.build(); } if (fileLoc == null || !fileLoc.exists()) { System.out.println("Invalid file to create"); ResponseBuilder builder = Response.status(Status.BAD_REQUEST); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INVALID_FILE</code>"); buffer.append("<message>Invalid File given to read</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); return builder.build(); } DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(url); FileEntity input = new FileEntity(fileLoc); input.setContentType("application/xml"); if (userName != null && password != null) { String base64encodedUsernameAndPassword = new String( Base64.encodeBase64((userName + ":" + password).getBytes())); postRequest.addHeader("Authorization", "Basic " + base64encodedUsernameAndPassword); } postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); while ((output = br.readLine()) != null) { buffer.append(output); } ResponseBuilder builder = Response.status(Status.CREATED); builder.type("application/xml"); buffer.append("</response>"); builder.entity(buffer.toString()); httpClient.getConnectionManager().shutdown(); return builder.build(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.hp.mqm.clt.TestResultCollectionTool.java
public void collectAndPushTestResults() { Map<File, String> publicApiXMLs = new LinkedHashMap<File, String>(); if (settings.isInternal()) { for (String fileName : settings.getInputXmlFileNames()) { publicApiXMLs.put(new File(fileName), fileName); }// ww w . jav a2s . c o m } else if (settings.getOutputFile() != null) { processJunitReport(new File(settings.getInputXmlFileNames().get(0)), new File(settings.getOutputFile())); System.out.println("JUnit report was saved to the output file"); System.exit(ReturnCode.SUCCESS.getReturnCode()); } else { for (String fileName : settings.getInputXmlFileNames()) { File publicApiTempXML = null; try { publicApiTempXML = File.createTempFile("testResult.xml", null); publicApiTempXML.deleteOnExit(); } catch (IOException e) { System.out.println("Can not create temp file for test result"); System.exit(ReturnCode.FAILURE.getReturnCode()); } processJunitReport(new File(fileName), publicApiTempXML); publicApiXMLs.put(publicApiTempXML, fileName); } } client = new RestClient(settings); try { for (Map.Entry<File, String> publicApiXML : publicApiXMLs.entrySet()) { long testResultId; try { testResultId = client.postTestResult(new FileEntity(publicApiXML.getKey())); } catch (ValidationException e) { // One invalid public API XML should not stop the whole process when supplied externally System.out.println("Test result from file '" + publicApiXML.getValue() + "' was not pushed"); System.out.println(e.getMessage()); continue; } if (settings.isCheckResult()) { validatePublishResult(testResultId, publicApiXML.getValue()); } else { System.out.println("Test result from file '" + publicApiXML.getValue() + "' was pushed to the server with ID " + testResultId); } } } catch (IOException e) { releaseClient(); System.out.println("Unable to push test result: " + e.getMessage()); System.exit(ReturnCode.FAILURE.getReturnCode()); } catch (RuntimeException e) { releaseClient(); System.out.println("Unable to push test result: " + e.getMessage()); System.exit(ReturnCode.FAILURE.getReturnCode()); } finally { releaseClient(); } }