List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder addTextBody
public MultipartEntityBuilder addTextBody(final String name, final String text)
From source file:org.piwigo.remotesync.api.client.WSClient.java
@SuppressWarnings("unchecked") protected <T extends BasicResponse> CloseableHttpResponse getHttpResponse(AbstractRequest<T> request) throws ClientException { try {//from w ww. j a va 2 s. c o m HttpPost method = new HttpPost(clientConfiguration.getUrl() + "/ws.php"); method.setConfig(requestConfig); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addTextBody("method", request.getWSMethodName()); for (Entry<String, Object> entry : request.getParameters().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof File) multipartEntityBuilder.addBinaryBody(key, (File) value); else if (value == null) multipartEntityBuilder.addTextBody(key, ""); else if (value instanceof List) { for (Object object : (List<? extends Object>) value) if (object != null) multipartEntityBuilder.addTextBody(key + "[]", object.toString()); } else if (value instanceof Enum) multipartEntityBuilder.addTextBody(key, value.toString().toLowerCase()); else multipartEntityBuilder.addTextBody(key, value.toString()); } method.setEntity(multipartEntityBuilder.build()); return getHttpClient().execute(method); } catch (SSLException e) { throw new ClientSSLException("SSL certificate exception (Please try option 'Trust SSL certificates')", e); } catch (Exception e) { throw new ClientException("Unable to send request", e); } }
From source file:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.CatalogRequestBuilder.java
protected HttpPost buildCatalogRequest(String fullUri) { String boundary = "---------------" + UUID.randomUUID().toString(); HttpPost post = new HttpPost(fullUri); post.addHeader("Accept", "application/json"); post.addHeader("Content-Type", org.apache.http.entity.ContentType.MULTIPART_FORM_DATA.getMimeType() + ";boundary=" + boundary); post.addHeader("sessionId", this.catalogObjectAction.getSessionId()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setBoundary(boundary);// ww w .j av a 2 s.c o m builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("file", new FileBody(this.catalogObjectAction.getNodeSourceJsonFile())); builder.addTextBody(COMMIT_MESSAGE_PARAM, this.catalogObjectAction.getCommitMessage()); if (!this.catalogObjectAction.isRevised()) { builder.addTextBody(NAME_PARAM, this.catalogObjectAction.getNodeSourceName()); builder.addTextBody(KIND_PARAM, this.catalogObjectAction.getKind()); builder.addTextBody(OBJECT_CONTENT_TYPE_PARAM, this.catalogObjectAction.getObjectContentType()); } post.setEntity(builder.build()); return post; }
From source file:org.plos.crepo.dao.objects.impl.ContentRepoObjectDaoImpl.java
private HttpEntity getObjectEntity(String bucketName, RepoObjectInput repoObjectInput, InputStream stream, CreationMethod creationType, String contentType) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntityBuilder.addTextBody("key", repoObjectInput.getKey()); multipartEntityBuilder.addTextBody("bucketName", bucketName); multipartEntityBuilder.addTextBody("create", creationType.toString()); multipartEntityBuilder.addTextBody("contentType", contentType); multipartEntityBuilder.addBinaryBody("file", stream); if (repoObjectInput.getDownloadName() != null) { multipartEntityBuilder.addTextBody("downloadName", repoObjectInput.getDownloadName()); }/*from w ww.j a v a2 s. c om*/ if (repoObjectInput.getTimestamp() != null) { multipartEntityBuilder.addTextBody("timestamp", repoObjectInput.getTimestamp().toString()); } if (repoObjectInput.getCreationDate() != null) { multipartEntityBuilder.addTextBody("creationDateTime", repoObjectInput.getCreationDate().toString()); } if (repoObjectInput.getTag() != null) { multipartEntityBuilder.addTextBody("tag", repoObjectInput.getTag()); } if (repoObjectInput.getUserMetadata() != null) { multipartEntityBuilder.addTextBody("userMetadata", repoObjectInput.getUserMetadata()); } return multipartEntityBuilder.build(); }
From source file:org.biopax.paxtools.client.BiopaxValidatorClient.java
/** * Checks a BioPAX OWL file(s) or resource * using the online BioPAX Validator //ww w . ja va 2s . c o m * and prints the results to the output stream. * * @param autofix true/false (experimental) * @param profile validation profile name * @param retFormat xml, html, or owl (no errors, just modified owl, if autofix=true) * @param filterBy filter validation issues by the error/warning level * @param maxErrs errors threshold - max no. critical errors to collect before quitting * (warnings not counted; null/0/negative value means unlimited) * @param biopaxUrl check the BioPAX at the URL * @param biopaxFiles an array of BioPAX files to validate * @param out validation report data output stream * @throws IOException when there is an I/O error */ public void validate(boolean autofix, String profile, RetFormat retFormat, Behavior filterBy, Integer maxErrs, String biopaxUrl, File[] biopaxFiles, OutputStream out) throws IOException { MultipartEntityBuilder meb = MultipartEntityBuilder.create(); meb.setCharset(Charset.forName("UTF-8")); if (autofix) meb.addTextBody("autofix", "true"); //TODO add extra options (normalizer.fixDisplayName, normalizer.inferPropertyOrganism, normalizer.inferPropertyDataSource, normalizer.xmlBase)? if (profile != null && !profile.isEmpty()) meb.addTextBody("profile", profile); if (retFormat != null) meb.addTextBody("retDesired", retFormat.toString().toLowerCase()); if (filterBy != null) meb.addTextBody("filter", filterBy.toString()); if (maxErrs != null && maxErrs > 0) meb.addTextBody("maxErrors", maxErrs.toString()); if (biopaxFiles != null && biopaxFiles.length > 0) for (File f : biopaxFiles) //important: use MULTIPART_FORM_DATA content-type meb.addBinaryBody("file", f, ContentType.MULTIPART_FORM_DATA, f.getName()); else if (biopaxUrl != null) { meb.addTextBody("url", biopaxUrl); } else { log.error("Nothing to do (no BioPAX data specified)!"); return; } //execute the query and get results as string HttpEntity httpEntity = meb.build(); // httpEntity.writeTo(System.err); String content = Executor.newInstance()//Executor.newInstance(httpClient) .execute(Request.Post(url).body(httpEntity)).returnContent().asString(); //save: append to the output stream (file) BufferedReader res = new BufferedReader(new StringReader(content)); String line; PrintWriter writer = new PrintWriter(out); while ((line = res.readLine()) != null) { writer.println(line); } writer.flush(); res.close(); }
From source file:io.wcm.maven.plugins.contentpackage.InstallMojo.java
/** * Deploy file via package manager//from w w w. j a v a 2s .co m */ private void installFile(File file) throws MojoExecutionException { try (CloseableHttpClient httpClient = getHttpClient()) { // if bundles are still stopping/starting, wait for completion waitForBundlesActivation(httpClient); if (this.install) { getLog().info("Upload and install " + file.getName() + " to " + getCrxPackageManagerUrl()); } else { getLog().info("Upload " + file.getName() + " to " + getCrxPackageManagerUrl()); } // prepare post method HttpPost post = new HttpPost(getCrxPackageManagerUrl() + "/.json?cmd=upload"); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addBinaryBody("package", file); if (this.force) { entityBuilder.addTextBody("force", "true"); } post.setEntity(entityBuilder.build()); // execute post JSONObject jsonResponse = executePackageManagerMethodJson(httpClient, post); boolean success = jsonResponse.optBoolean("success", false); String msg = jsonResponse.optString("msg", null); String path = jsonResponse.optString("path", null); if (success) { if (this.install) { getLog().info("Package uploaded, now installing..."); try { post = new HttpPost(getCrxPackageManagerUrl() + "/console.html" + new URIBuilder().setPath(path).build().getRawPath() + "?cmd=install" + (this.recursive ? "&recursive=true" : "")); } catch (URISyntaxException ex) { throw new MojoExecutionException("Invalid path: " + path, ex); } // execute post executePackageManagerMethodHtml(httpClient, post, 0); } else { getLog().info("Package uploaded successfully (without installing)."); } } else if (StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX) && !this.force) { getLog().info("Package skipped because it was already uploaded."); } else { throw new MojoExecutionException("Package upload failed: " + msg); } } catch (IOException ex) { throw new MojoExecutionException("Install operation failed.", ex); } }
From source file:mesquite.zephyr.RAxMLRunnerCIPRes.RAxMLRunnerCIPRes.java
void addArgument(MultipartEntityBuilder builder, StringBuffer sb, String param, String value) { if (builder != null) builder.addTextBody(param, value); if (sb != null) sb.append("\n " + param + " = " + value); }
From source file:com.alibaba.shared.django.DjangoClient.java
public DjangoMessage uploadFile(final byte[] bytes, final String filename) throws IOException, URISyntaxException { return executeRequest(new Supplier<HttpUriRequest>() { public HttpUriRequest get() { HttpPost post = new HttpPost(uploadFileUrl); MultipartEntityBuilder meb = MultipartEntityBuilder.create(); meb.addTextBody(ACCESS_TOKEN_KEY, accessToken()).addTextBody("md5", Digests.md5(bytes)) .addBinaryBody(FILE_KEY, bytes, ContentType.APPLICATION_XML, filename); post.setEntity(meb.build()); return post; }//from w w w.jav a 2 s . c om }); }
From source file:org.biopax.validator.BiopaxValidatorClient.java
/** * Checks a BioPAX OWL file(s) or resource * using the online BioPAX Validator //from w w w. java 2 s .c om * and prints the results to the output stream. * * @param autofix true/false (experimental) * @param profile validation profile name * @param retFormat xml, html, or owl (no errors, just modified owl, if autofix=true) * @param biopaxUrl check the BioPAX at the URL * @param biopaxFiles an array of BioPAX files to validate * @param out * @throws IOException */ public void validate(boolean autofix, String profile, RetFormat retFormat, Behavior filterBy, Integer maxErrs, String biopaxUrl, File[] biopaxFiles, OutputStream out) throws IOException { MultipartEntityBuilder meb = MultipartEntityBuilder.create(); meb.setCharset(Charset.forName("UTF-8")); if (autofix) meb.addTextBody("autofix", "true"); //TODO add extra options (normalizer.fixDisplayName, normalizer.xmlBase)? if (profile != null && !profile.isEmpty()) meb.addTextBody("profile", profile); if (retFormat != null) meb.addTextBody("retDesired", retFormat.toString().toLowerCase()); if (filterBy != null) meb.addTextBody("filter", filterBy.toString()); if (maxErrs != null && maxErrs > 0) meb.addTextBody("maxErrors", maxErrs.toString()); if (biopaxFiles != null && biopaxFiles.length > 0) for (File f : biopaxFiles) //important: use MULTIPART_FORM_DATA content-type meb.addBinaryBody("file", f, ContentType.MULTIPART_FORM_DATA, f.getName()); else if (biopaxUrl != null) { meb.addTextBody("url", biopaxUrl); } else { log.error("Nothing to do (no BioPAX data specified)!"); return; } HttpEntity httpEntity = meb.build(); // if(log.isDebugEnabled()) httpEntity.writeTo(System.err); String content = Executor.newInstance().execute(Request.Post(url).body(httpEntity)).returnContent() .asString(); //save: append to the output stream (file) BufferedReader res = new BufferedReader(new StringReader(content)); String line; PrintWriter writer = new PrintWriter(out); while ((line = res.readLine()) != null) { writer.println(line); } writer.flush(); res.close(); }
From source file:org.exmaralda.webservices.G2PConnector.java
public String callG2P(File bpfInFile, HashMap<String, Object> otherParameters) throws IOException, JDOMException { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); if (otherParameters != null) { builder.addTextBody("lng", (String) otherParameters.get("lng")); }/* w w w .j ava 2 s . c o m*/ // add the text file builder.addTextBody("iform", "bpf"); builder.addBinaryBody("i", bpfInFile); // construct a POST request with the multipart entity HttpPost httpPost = new HttpPost(g2pURL); httpPost.setEntity(builder.build()); HttpResponse response = httpClient.execute(httpPost); HttpEntity result = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200 && result != null) { String resultAsString = EntityUtils.toString(result); BASWebServiceResult basResult = new BASWebServiceResult(resultAsString); if (!(basResult.isSuccess())) { String errorText = "Call to G2P was not successful: " + resultAsString; throw new IOException(errorText); } String bpfOutString = basResult.getDownloadText(); EntityUtils.consume(result); httpClient.close(); return bpfOutString; } else { // something went wrong, throw an exception String reason = statusLine.getReasonPhrase(); throw new IOException(reason); } }
From source file:com.alibaba.shared.django.DjangoClient.java
protected void uploadFileChunks(InputStream is, int maxChunkSize, final String fileId, final int sequence, final String fillename, List<DjangoMessage> holder) throws IOException, URISyntaxException { final MessageDigest digest = Digests.defaultDigest(); byte[] buf = new byte[8000]; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = is.read(buf), processCount = len; while (len >= 0 && processCount < maxChunkSize) { baos.write(buf, 0, len);//from ww w. ja v a2 s . c om digest.update(buf, 0, len); processCount += len; if (maxChunkSize <= processCount) { break; } len = is.read(buf); } if (processCount > 0) { holder.add(executeRequest(new Supplier<HttpUriRequest>() { public HttpUriRequest get() { MultipartEntityBuilder meb = MultipartEntityBuilder.create(); meb.addTextBody(ACCESS_TOKEN_KEY, accessToken()).addTextBody("fileId", fileId) .addTextBody("sequence", String.valueOf(sequence)) .addTextBody("md5", Digests.toHexDigest(digest.digest())).addBinaryBody(FILE_KEY, baos.toByteArray(), ContentType.APPLICATION_OCTET_STREAM, fillename); HttpPost post = new HttpPost(chunkUrl); post.setEntity(meb.build()); return post; } })); uploadFileChunks(is, maxChunkSize, fileId, sequence + 1, fillename, holder); } }