List of usage examples for org.apache.http.entity ContentType create
private static ContentType create(HeaderElement headerElement)
From source file:org.elasticsearch.xpack.ml.integration.MlBasicMultiNodeIT.java
public void testMiniFarequoteReopen() throws Exception { String jobId = "mini-farequote-reopen"; createFarequoteJob(jobId);//from w w w. j ava 2s .com Response response = client().performRequest("post", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_open"); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(Collections.singletonMap("opened", true), responseEntityToMap(response)); String postData = "{\"airline\":\"AAL\",\"responsetime\":\"132.2046\",\"sourcetype\":\"farequote\",\"time\":\"1403481600\"}\n" + "{\"airline\":\"JZA\",\"responsetime\":\"990.4628\",\"sourcetype\":\"farequote\",\"time\":\"1403481700\"}\n" + "{\"airline\":\"JBU\",\"responsetime\":\"877.5927\",\"sourcetype\":\"farequote\",\"time\":\"1403481800\"}\n" + "{\"airline\":\"KLM\",\"responsetime\":\"1355.4812\",\"sourcetype\":\"farequote\",\"time\":\"1403481900\"}\n" + "{\"airline\":\"NKS\",\"responsetime\":\"9991.3981\",\"sourcetype\":\"farequote\",\"time\":\"1403482000\"}"; response = client().performRequest("post", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_data", Collections.emptyMap(), new StringEntity(postData, randomFrom(ContentType.APPLICATION_JSON, ContentType.create("application/x-ndjson")))); assertEquals(202, response.getStatusLine().getStatusCode()); Map<String, Object> responseBody = responseEntityToMap(response); assertEquals(5, responseBody.get("processed_record_count")); assertEquals(10, responseBody.get("processed_field_count")); assertEquals(446, responseBody.get("input_bytes")); assertEquals(15, responseBody.get("input_field_count")); assertEquals(0, responseBody.get("invalid_date_count")); assertEquals(0, responseBody.get("missing_field_count")); assertEquals(0, responseBody.get("out_of_order_timestamp_count")); assertEquals(0, responseBody.get("bucket_count")); assertEquals(1403481600000L, responseBody.get("earliest_record_timestamp")); assertEquals(1403482000000L, responseBody.get("latest_record_timestamp")); response = client().performRequest("post", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_flush"); assertEquals(200, response.getStatusLine().getStatusCode()); assertFlushResponse(response, true, 1403481600000L); response = client().performRequest("post", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_close", Collections.singletonMap("timeout", "20s")); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(Collections.singletonMap("closed", true), responseEntityToMap(response)); response = client().performRequest("get", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_stats"); assertEquals(200, response.getStatusLine().getStatusCode()); response = client().performRequest("post", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_open", Collections.singletonMap("timeout", "20s")); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(Collections.singletonMap("opened", true), responseEntityToMap(response)); // feed some more data points postData = "{\"airline\":\"AAL\",\"responsetime\":\"136.2361\",\"sourcetype\":\"farequote\",\"time\":\"1407081600\"}\n" + "{\"airline\":\"VRD\",\"responsetime\":\"282.9847\",\"sourcetype\":\"farequote\",\"time\":\"1407081700\"}\n" + "{\"airline\":\"JAL\",\"responsetime\":\"493.0338\",\"sourcetype\":\"farequote\",\"time\":\"1407081800\"}\n" + "{\"airline\":\"UAL\",\"responsetime\":\"8.4275\",\"sourcetype\":\"farequote\",\"time\":\"1407081900\"}\n" + "{\"airline\":\"FFT\",\"responsetime\":\"221.8693\",\"sourcetype\":\"farequote\",\"time\":\"1407082000\"}"; response = client().performRequest("post", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_data", Collections.emptyMap(), new StringEntity(postData, randomFrom(ContentType.APPLICATION_JSON, ContentType.create("application/x-ndjson")))); assertEquals(202, response.getStatusLine().getStatusCode()); responseBody = responseEntityToMap(response); assertEquals(5, responseBody.get("processed_record_count")); assertEquals(10, responseBody.get("processed_field_count")); assertEquals(442, responseBody.get("input_bytes")); assertEquals(15, responseBody.get("input_field_count")); assertEquals(0, responseBody.get("invalid_date_count")); assertEquals(0, responseBody.get("missing_field_count")); assertEquals(0, responseBody.get("out_of_order_timestamp_count")); assertEquals(1000, responseBody.get("bucket_count")); // unintuitive: should return the earliest record timestamp of this feed??? assertEquals(null, responseBody.get("earliest_record_timestamp")); assertEquals(1407082000000L, responseBody.get("latest_record_timestamp")); response = client().performRequest("post", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_close", Collections.singletonMap("timeout", "20s")); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(Collections.singletonMap("closed", true), responseEntityToMap(response)); // counts should be summed up response = client().performRequest("get", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_stats"); assertEquals(200, response.getStatusLine().getStatusCode()); @SuppressWarnings("unchecked") Map<String, Object> dataCountsDoc = (Map<String, Object>) ((Map) ((List) responseEntityToMap(response) .get("jobs")).get(0)).get("data_counts"); assertEquals(10, dataCountsDoc.get("processed_record_count")); assertEquals(20, dataCountsDoc.get("processed_field_count")); assertEquals(888, dataCountsDoc.get("input_bytes")); assertEquals(30, dataCountsDoc.get("input_field_count")); assertEquals(0, dataCountsDoc.get("invalid_date_count")); assertEquals(0, dataCountsDoc.get("missing_field_count")); assertEquals(0, dataCountsDoc.get("out_of_order_timestamp_count")); assertEquals(1000, dataCountsDoc.get("bucket_count")); assertEquals(1403481600000L, dataCountsDoc.get("earliest_record_timestamp")); assertEquals(1407082000000L, dataCountsDoc.get("latest_record_timestamp")); response = client().performRequest("delete", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId); assertEquals(200, response.getStatusLine().getStatusCode()); }
From source file:com.intuit.karate.http.apache.ApacheHttpClient.java
@Override protected HttpEntity getEntity(InputStream value, String mediaType) { return new InputStreamEntity(value, ContentType.create(mediaType)); }
From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java
private org.apache.http.HttpRequest buildHttpUriRequest(HttpRequest request, Joiner joiner, URI requestUri) { org.apache.http.HttpRequest httpRequest; if (autoEncodeUri) { switch (request.getHttpMethod()) { case GET: httpRequest = new HttpGet(requestUri); break; case POST: httpRequest = new HttpPost(requestUri); break; case PUT: httpRequest = new HttpPut(requestUri); break; case DELETE: httpRequest = new HttpDelete(requestUri); break; case HEAD: httpRequest = new HttpHead(requestUri); break; case OPTIONS: httpRequest = new HttpOptions(requestUri); break; case PATCH: httpRequest = new HttpPatch(requestUri); break; default:/* w ww.jav a 2s .c om*/ throw new ClientException("You have to one of the REST verbs such as GET, POST etc."); } } else { switch (request.getHttpMethod()) { case POST: case PUT: case DELETE: case PATCH: httpRequest = new BasicHttpEntityEnclosingRequest(request.getHttpMethod().method(), requestUri.toString()); break; default: httpRequest = new BasicHttpRequest(request.getHttpMethod().method(), requestUri.toString()); } } byte[] entity = request.getEntity(); if (entity != null) { if (httpRequest instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest httpEntityEnclosingRequestBase = (HttpEntityEnclosingRequest) httpRequest; httpEntityEnclosingRequestBase .setEntity(new ByteArrayEntity(entity, ContentType.create(request.getContentType()))); } else { throw new ClientException( "sending content for request type " + request.getHttpMethod() + " is not supported!"); } } else { if (request instanceof ApacheHttpRequest && httpRequest instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest httpEntityEnclosingRequestBase = (HttpEntityEnclosingRequest) httpRequest; ApacheHttpRequest apacheHttpRequest = (ApacheHttpRequest) request; httpEntityEnclosingRequestBase.setEntity(apacheHttpRequest.getApacheHttpEntity()); } } Map<String, Collection<String>> headers = request.getHeaders(); for (Map.Entry<String, Collection<String>> stringCollectionEntry : headers.entrySet()) { String key = stringCollectionEntry.getKey(); Collection<String> stringCollection = stringCollectionEntry.getValue(); String value = joiner.join(stringCollection); httpRequest.setHeader(key, value); } return httpRequest; }
From source file:com.sangupta.jerry.http.WebInvoker.java
/** * POST the JSON representation of the given object to the given URL. The * object is converted to JSON format usign {@link Gson} project. * //from w w w . ja v a 2 s . c om * @param uri * the url to hit * * @param object * the object to be sent in request body * * @return the {@link WebResponse} obtained */ public static WebResponse postJSON(final String uri, final Object object) { WebRequest request = getWebRequest(uri, WebRequestMethod.POST); String requestBody = GsonUtils.getGson().toJson(object); request.bodyString(requestBody, ContentType.create("application/json")); try { return request.execute().webResponse(); } catch (IOException e) { logger.debug("Unable to fetch repsonse from url: {}", uri, e); } return null; }
From source file:it.greenvulcano.gvesb.virtual.gv_multipart.MultipartCallOperation.java
/** * creates a Content-Type element//from www . j a v a 2 s . c o m * * @param contentType * @return created contentType */ private ContentType getContentType(String contentType) { return ContentType.create(contentType); }
From source file:com.baidu.qa.service.test.client.SoapReqImpl.java
private static String sendSoapViaHttps(String hosturl, String ip, int port, String action, String method, String xml) {//from w w w . j a v a 2s . com String reqURL = "https://" + ip + ":" + port + action; // Map<String, String> params = null; long responseLength = 0; // ? String responseContent = null; // ? HttpClient httpClient = new DefaultHttpClient(); // httpClient httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000); X509TrustManager xtm = new X509TrustManager() { // TrustManager public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; try { // TLS1.0SSL3.0??TLSSSL?SSLContext SSLContext ctx = SSLContext.getInstance("TLS"); // TrustManager??TrustManager?SSLSocket ctx.init(null, new TrustManager[] { xtm }, null); // SSLSocketFactory SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); // SchemeRegistrySSLSocketFactoryHttpClient httpClient.getConnectionManager().getSchemeRegistry() .register(new Scheme("https", port, socketFactory)); HttpPost httpPost = new HttpPost(reqURL); // HttpPost // add the 3 headers below httpPost.addHeader("Accept-Encoding", "gzip,deflate"); httpPost.addHeader("SOAPAction", hosturl + action + method);// SOAP action httpPost.addHeader("uuid", "itest");// for editor token of DR-Api // HttpEntity requestBody = new // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO byte[] b = xml.getBytes("UTF-8"); // must be UTF-8 InputStream is = new ByteArrayInputStream(b, 0, b.length); HttpEntity requestBody = new InputStreamEntity(is, b.length, ContentType.create("text/xml;charset=UTF-8"));// must be // UTF-8 httpPost.setEntity(requestBody); log.info(">> Request URI: " + httpPost.getRequestLine().getUri()); HttpResponse response = httpClient.execute(httpPost); // POST HttpEntity entity = response.getEntity(); // ?? if (null != entity) { responseLength = entity.getContentLength(); String contentEncoding = null; Header ce = response.getEntity().getContentEncoding(); if (ce != null) { contentEncoding = ce.getValue(); } if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) { GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent()); Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8")); StringBuilder sb = new StringBuilder(); while (in.hasNextLine()) { sb.append(in.nextLine()).append(System.getProperty("line.separator")); } responseContent = sb.toString(); } else { responseContent = EntityUtils.toString(response.getEntity(), "UTF-8"); } EntityUtils.consume(entity); // Consume response content } log.info("?: " + httpPost.getURI()); log.info("??: " + response.getStatusLine()); log.info("?: " + responseLength); log.info("?: " + responseContent); } catch (KeyManagementException e) { log.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { log.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } catch (ClientProtocolException e) { log.error(e.getMessage(), e); } catch (ParseException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } finally { httpClient.getConnectionManager().shutdown(); // ,? return responseContent; } }
From source file:SubmitResults.java
private File populateRequest(final Main parent, String formStatus, String filePath, HttpPost req, final String changeIdXSLT, ContentType ct, MultipartEntityBuilder entityBuilder, final String newIdent) { File ammendedFile = null;/* w w w . j a va 2 s . co m*/ final File instanceFile = new File(filePath); if (formStatus != null) { System.out.println("Setting form status in header: " + formStatus); req.setHeader("form_status", formStatus); // smap add form_status header } else { System.out.println("Form Status null"); } if (newIdent != null) { // Transform the survey ID try { System.out.println("Transformaing Instance file: " + instanceFile); PipedInputStream in = new PipedInputStream(); final PipedOutputStream outStream = new PipedOutputStream(in); new Thread(new Runnable() { public void run() { try { InputStream xslStream = new ByteArrayInputStream(changeIdXSLT.getBytes("UTF-8")); Transformer transformer = TransformerFactory.newInstance() .newTransformer(new StreamSource(xslStream)); StreamSource source = new StreamSource(instanceFile); StreamResult out = new StreamResult(outStream); transformer.setParameter("surveyId", newIdent); transformer.transform(source, out); outStream.close(); } catch (TransformerConfigurationException e1) { parent.appendToStatus("Error changing ident: " + e1.toString()); } catch (TransformerFactoryConfigurationError e1) { parent.appendToStatus("Error changing ident: " + e1.toString()); } catch (TransformerException e) { parent.appendToStatus("Error changing ident: " + e.toString()); } catch (IOException e) { parent.appendToStatus("Error changing ident: " + e.toString()); } } }).start(); System.out.println("Saving stream to file"); ammendedFile = saveStreamTemp(in); } catch (Exception e) { parent.appendToStatus("Error changing ident: " + e.toString()); } } /* * Add submission file as file body, hence save to temporary file first */ if (newIdent == null) { ct = ContentType.create("text/xml"); entityBuilder.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath()); } else { FileBody fb = new FileBody(ammendedFile); entityBuilder.addPart("xml_submission_file", fb); } parent.appendToStatus("Instance file path: " + instanceFile.getPath()); /* * find all files referenced by the survey * Temporarily check to see if the parent directory is "uploadedSurveys". If it is * then we will need to scan the submission file to get the list of attachments to * send. * Alternatively this is a newly submitted survey stored in its own directory just as * surveys are stored on the phone. We can then just add all the surveys that are in * the same directory as the submission file. */ File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files ignoring invisible files and the submission file List<File> files = new ArrayList<File>(); for (File f : allFiles) { String fileName = f.getName(); if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) { // ignore invisible files and instance xml file files.add(f); } } for (int j = 0; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); ct = ContentType.create(getContentType(parent, fileName)); FileBody fba = new FileBody(f, ct, fileName); entityBuilder.addPart(fileName, fba); } req.setEntity(entityBuilder.build()); return ammendedFile; }
From source file:com.ebixio.virtmus.stats.StatsLogger.java
/** Should only be called from uploadLogs(). Compresses all files that belong to the given log set, and uploads all compressed files to the server. */ private boolean uploadLogs(final String logSet) { if (logSet == null) return false; File logsDir = getLogsDir();/* w w w .j a v a2 s . c o m*/ if (logsDir == null) return false; gzipLogs(logsDir, logSet); // Uploading only gz'd files FilenameFilter gzFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".gz"); } }; File[] toUpload = logsDir.listFiles(gzFilter); String url = getUploadUrl(); if (url == null) { /* This means the server is unable to accept the logs. */ keepRecents(toUpload, 100); return false; } CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); addHttpHeaders(post); MultipartEntityBuilder entity = MultipartEntityBuilder.create(); entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("InstallId", new StringBody(String.valueOf(MainApp.getInstallId()), ContentType.TEXT_PLAIN)); ContentType ct = ContentType.create("x-application/gzip"); for (File f : toUpload) { entity.addPart("VirtMusStats", new FileBody(f, ct, f.getName())); } post.setEntity(entity.build()); boolean success = false; try (CloseableHttpResponse response = client.execute(post)) { int status = response.getStatusLine().getStatusCode(); Log.log(Level.INFO, "Log upload result: {0}", status); if (status == HttpStatus.SC_OK) { // 200 for (File f : toUpload) { try { f.delete(); } catch (SecurityException ex) { } } success = true; } else { LogRecord rec = new LogRecord(Level.INFO, "Server Err"); rec.setParameters(new Object[] { url, "Status: " + status }); getLogger().log(rec); } HttpEntity rspEntity = response.getEntity(); EntityUtils.consume(rspEntity); client.close(); } catch (IOException ex) { Log.log(ex); } keepRecents(toUpload, 100); // In case of exceptions or errors return success; }
From source file:org.identityconnectors.office365.Office365Connection.java
public boolean patchObject(String path, JSONObject body) { log.info("patchRequest(" + path + ")"); // http://msdn.microsoft.com/en-us/library/windowsazure/dn151671.aspx HttpPatch httpPatch = new HttpPatch(getAPIEndPoint(path)); httpPatch.addHeader("Authorization", this.getToken()); // patch.addHeader("Content-Type", "application/json;odata=verbose"); httpPatch.addHeader("DataServiceVersion", "3.0;NetFx"); httpPatch.addHeader("MaxDataServiceVersion", "3.0;NetFx"); httpPatch.addHeader("Accept", "application/atom+xml"); EntityBuilder eb = EntityBuilder.create(); eb.setText(body.toString());//from w ww.j a v a 2s .co m eb.setContentType(ContentType.create("application/json")); httpPatch.setEntity(eb.build()); HttpClient httpClient = HttpClientBuilder.create().build(); try { HttpResponse response = httpClient.execute(httpPatch); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() != 204) { log.error("An error occured when modify an object in Office 365"); this.invalidateToken(); StringBuffer sb = new StringBuffer(); if (entity != null && entity.getContent() != null) { BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent())); String s = null; log.info("Response :{0}", response.getStatusLine().toString()); while ((s = in.readLine()) != null) { sb.append(s); log.info(s); } } throw new ConnectorException("Modify Object failed to " + path + " and body of " + body.toString() + ". Error code was " + response.getStatusLine().getStatusCode() + ". Received the following response " + sb.toString()); } else { return true; } } catch (ClientProtocolException cpe) { log.error(cpe, "Error doing patchRequest to path {0}", path); throw new ConnectorException("Exception whilst doing PATCH to " + path); } catch (IOException ioe) { log.error(ioe, "IOE Error doing patchRequest to path {0}", path); throw new ConnectorException("Exception whilst doing PATCH to " + path); } }