List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create
public static MultipartEntityBuilder create()
From source file:org.biopax.paxtools.client.BiopaxValidatorClient.java
/** * Checks a BioPAX OWL file(s) or resource * using the online BioPAX Validator //from w w w . j ava 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.swagger.client.api.DefaultApi.java
/** * Full card detail//from ww w . ja v a 2 s. com * Retrieves a full card detail, and optionally its relations to other cards * @param authorization Authorization token ('Bearer <token>') * @param cardId Provided card ID (value of the 'card_id' field) * @param version Provided card version (value of the 'version' field) * @param acceptLanguage Client locale, as <language>-<country> * @param contentType application/json * @param relations Indicates if the received scene cards should contain the scene hierarchy (true) or be a flat list of the main scene items (false) * @param imageSize Size of the images returned in the response * @return Card */ public Card getCardVersion(String authorization, String cardId, String version, String acceptLanguage, String contentType, Boolean relations, String imageSize) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'authorization' is set if (authorization == null) { throw new ApiException(400, "Missing the required parameter 'authorization' when calling getCardVersion"); } // verify the required parameter 'cardId' is set if (cardId == null) { throw new ApiException(400, "Missing the required parameter 'cardId' when calling getCardVersion"); } // verify the required parameter 'version' is set if (version == null) { throw new ApiException(400, "Missing the required parameter 'version' when calling getCardVersion"); } // create path and map variables String localVarPath = "/cards/{card_id}/versions/{version}".replaceAll("\\{format\\}", "json") .replaceAll("\\{" + "card_id" + "\\}", apiInvoker.escapeString(cardId.toString())) .replaceAll("\\{" + "version" + "\\}", apiInvoker.escapeString(version.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); // header params Map<String, String> localVarHeaderParams = new HashMap<String, String>(); // form params Map<String, String> localVarFormParams = new HashMap<String, String>(); localVarQueryParams.addAll(ApiInvoker.parameterToPairs("", "relations", relations)); localVarQueryParams.addAll(ApiInvoker.parameterToPairs("", "image_size", imageSize)); localVarHeaderParams.put("Authorization", ApiInvoker.parameterToString(authorization)); localVarHeaderParams.put("Accept-Language", ApiInvoker.parameterToString(acceptLanguage)); localVarHeaderParams.put("Content-Type", ApiInvoker.parameterToString(contentType)); String[] localVarContentTypes = { "application/json" }; String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; if (localVarContentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); localVarPostBody = localVarBuilder.build(); } else { // normal form params } try { String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); if (localVarResponse != null) { return (Card) ApiInvoker.deserialize(localVarResponse, "", Card.class); } else { return null; } } catch (ApiException ex) { throw ex; } }
From source file:ua.pp.msk.maven.MavenHttpClient.java
private int execute(File file) throws ArtifactPromotingException { CloseableHttpClient client = HttpClientBuilder.create().build(); int status = -1; try {/*from www.j a v a2s .c om*/ getLog().debug("Connecting to URL: " + url); HttpPost post = new HttpPost(url); post.setHeader("User-Agent", userAgent); if (username != null && username.length() != 0 && password != null) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); post.addHeader(new BasicScheme().authenticate(creds, post, null)); } if (file == null) { if (!urlParams.isEmpty()) { post.setEntity(new UrlEncodedFormEntity(urlParams)); } } else { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (!urlParams.isEmpty()) { for (NameValuePair nvp : urlParams) { builder.addPart(nvp.getName(), new StringBody(nvp.getValue(), ContentType.MULTIPART_FORM_DATA)); } } FileBody fb = new FileBody(file); // Not used because of form submission // builder.addBinaryBody("file", file, // ContentType.DEFAULT_BINARY, file.getName()); builder.addPart("file", fb); HttpEntity sendEntity = builder.build(); post.setEntity(sendEntity); } CloseableHttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); status = statusLine.getStatusCode(); getLog().info( "Response status code: " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase()); // Perhaps I need to parse html // String html = EntityUtils.toString(entity); } catch (AuthenticationException ex) { throw new ArtifactPromotingException(ex); } catch (UnsupportedEncodingException ex) { throw new ArtifactPromotingException(ex); } catch (IOException ex) { throw new ArtifactPromotingException(ex); } finally { try { client.close(); } catch (IOException ex) { throw new ArtifactPromotingException("Cannot close http client", ex); } } return status; }
From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java
protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey, String deploymentName) {//from ww w .ja v a 2s. c om String deployApiUrl = modelerAppProperties.getDeploymentApiUrl(); Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set"); String basicAuthUser = properties.getIdmAdmin().getUser(); String basicAuthPassword = properties.getIdmAdmin().getPassword(); String tenantId = tenantProvider.getTenantId(); if (!deployApiUrl.endsWith("/")) { deployApiUrl = deployApiUrl.concat("/"); } deployApiUrl = deployApiUrl .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s", encode(deploymentKey), encode(deploymentName))); if (tenantId != null) { StringBuilder sb = new StringBuilder(deployApiUrl); sb.append("&tenantId=").append(encode(tenantId)); deployApiUrl = sb.toString(); } HttpPost httpPost = new HttpPost(deployApiUrl); httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder() .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8"))))); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName); HttpEntity entity = entityBuilder.build(); httpPost.setEntity(entity); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); clientBuilder .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure SSL for http client", e); throw new InternalServerErrorException("Could not configure SSL for http client", e); } CloseableHttpClient client = clientBuilder.build(); try { HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { return; } else { LOGGER.error("Invalid deploy result code: {} for url", response.getStatusLine() + httpPost.getURI().toString()); throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine()); } } catch (IOException ioe) { LOGGER.error("Error calling deploy endpoint", ioe); throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage()); } finally { if (client != null) { try { client.close(); } catch (IOException e) { LOGGER.warn("Exception while closing http client", e); } } } }
From source file:com.tur0kk.facebook.FacebookClient.java
public String publishPicture(String msg, Image image, String placeId) throws IOException { OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/v2.2/me/photos"); // request node request.addHeader("Authorization", "Bearer " + accesTokenString); // authentificate // check input to avoid error responses if (msg != null && image != null) { // facebook requires multipart post structure MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("message", msg); // description if (placeId != null && !"".equals(placeId)) { builder.addTextBody("place", placeId); // add link to FabLab site if property is set in preferences }/* w w w. j ava 2s. c om*/ // convert image to bytearray and append to multipart BufferedImage bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(image, 0, 0, null); bGr.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bimage, "png", baos); builder.addBinaryBody(msg, baos.toByteArray(), ContentType.MULTIPART_FORM_DATA, "test.png"); // generate multipart byte stream and add to payload of post package HttpEntity multipart = builder.build(); ByteArrayOutputStream multipartOutStream = new ByteArrayOutputStream( (int) multipart.getContentLength()); multipart.writeTo(multipartOutStream); request.addPayload(multipartOutStream.toByteArray()); // set header of post package Header contentType = multipart.getContentType(); request.addHeader(contentType.getName(), contentType.getValue()); // send and response answer Response response = request.send(); return response.getBody(); } else { throw new RuntimeException("message and image needed"); } }
From source file:org.wso2.security.tools.scanner.dependency.js.ticketcreator.JIRARestClient.java
/** * Invoke put method to attach file for particular ticket. * * @param auth credentials info of JIRA. * @param url url to be invoked.//from w w w.j a va2 s.co m * @param path path of the file to be attached. * @throws TicketCreatorException Exception occurred while attaching the file with ticket. */ public void invokePutMethodWithFile(String auth, String url, String path) throws TicketCreatorException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); httppost.setHeader("X-Atlassian-Token", "nocheck"); httppost.setHeader("Authorization", "Basic " + auth); File fileToUpload = new File(path); FileBody fileBody = new FileBody(fileToUpload); HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody).build(); httppost.setEntity(entity); CloseableHttpResponse response; try { response = httpclient.execute(httppost); log.info("[JS_SEC_DAILY_SCAN] File attached with ticket : " + response.toString()); } catch (IOException e) { throw new TicketCreatorException( "File upload failed while attaching the scan report with issue ticket: " + path, e); } finally { try { httpclient.close(); } catch (IOException e) { log.error("Exception occurred while closing the http connection", e); } } }
From source file:com.google.appinventor.components.runtime.MediaStore.java
/** * Asks the Web service to store the given media file. * * @param mediafile The value to store./*from ww w . j a v a 2s . c o m*/ */ @SimpleFunction public void PostMedia(String mediafile) throws FileNotFoundException { AsyncCallbackPair<String> myCallback = new AsyncCallbackPair<String>() { public void onSuccess(final String response) { androidUIHandler.post(new Runnable() { public void run() { MediaStored(response); } }); } public void onFailure(final String message) { androidUIHandler.post(new Runnable() { public void run() { WebServiceError(message); } }); } }; try { HttpClient client = new DefaultHttpClient(); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); String[] pathtokens = mediafile.split("/"); String newMediaPath; if (pathtokens[0].equals("file:")) { newMediaPath = new java.io.File(new URL(mediafile).toURI()).getAbsolutePath(); } else { newMediaPath = mediafile; } File media = new File(newMediaPath); entityBuilder.addPart("file", new FileBody(media)); HttpEntity entity = entityBuilder.build(); String uploadURL = getUploadUrl(); HttpPost post = new HttpPost(uploadURL); post.setEntity(entity); HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); String result = EntityUtils.toString(httpEntity); myCallback.onSuccess(result); } catch (Exception e) { e.printStackTrace(); myCallback.onFailure(e.getMessage()); } }
From source file:ai.susi.server.ClientConnection.java
/** * POST request//from w ww. ja va 2 s . com * @param urlstring * @param map * @param useAuthentication * @throws ClientProtocolException * @throws IOException */ public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication) throws ClientProtocolException, IOException { this.httpClient = HttpClients.custom().useSystemProperties() .setConnectionManager(getConnctionManager(useAuthentication)) .setDefaultRequestConfig(defaultRequestConfig).build(); this.request = new HttpPost(urlstring); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (Map.Entry<String, byte[]> entry : map.entrySet()) { entityBuilder.addBinaryBody(entry.getKey(), entry.getValue()); } ((HttpPost) this.request).setEntity(entityBuilder.build()); this.request.setHeader("User-Agent", USER_AGENT); this.init(); }
From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java
/** * Trains the ranker using the trainingdata.csv * //from ww w . jav a2 s . c o m * @param ranker_url URL associated with the ranker Ex.) * "https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/rankers" * @param rankerName The name of the ranker, to be sent as metadata * @param client {@link HttpClient} to send the request to * @param training_file Path to the trainingdata.csv * @return JSON of the result: { "name": "example-ranker", "url": * "https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/rankers/6C76AF-ranker-43", * "ranker_id": "6C76AF-ranker-43", "created": "2015-09-21T18:01:57.393Z", "status": * "Training", "status_description": * "The ranker instance is in its training phase, not yet ready to accept requests" } * @throws IOException */ public static String trainRanker(String ranker_url, String rankerName, HttpClient client, StringBuffer training_data) throws IOException { // Create a POST request HttpPost post = new HttpPost(ranker_url); MultipartEntityBuilder postParams = MultipartEntityBuilder.create(); // Add data String metadata = "\"" + rankerName + "\""; StringBody metadataBody = new StringBody(metadata, ContentType.TEXT_PLAIN); postParams.addPart(RetrieveAndRankSearcherConstants.TRAINING_DATA_LABEL, new AnswerFileBody(training_data.toString())); postParams.addPart(RetrieveAndRankSearcherConstants.TRAINING_METADATA_LABEL, metadataBody); post.setEntity(postParams.build()); // Obtain and parse response HttpResponse response = client.execute(post); String result = getHttpResultString(response); return result; }