List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build
public HttpEntity build()
From source file:org.biopax.paxtools.client.BiopaxValidatorClient.java
/** * Checks a BioPAX OWL file(s) or resource * using the online BioPAX Validator /*www . j a v a2s.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:hello.MyPostHTTP.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); requestConfigBuilder.setConnectionRequestTimeout( context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setConnectTimeout( context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setRedirectsEnabled(false); requestConfigBuilder//from ww w . ja v a2 s. c om .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); final RequestConfig requestConfig = requestConfigBuilder.build(); final StreamThrottler throttler = throttlerRef.get(); final ProcessorLog logger = getLogger(); String lastUrl = null; long bytesToSend = 0L; final List<FlowFile> toSend = new ArrayList<>(); CloseableHttpClient client = null; final String transactionId = UUID.randomUUID().toString(); final ObjectHolder<String> dnHolder = new ObjectHolder<>("none"); while (true) { FlowFile flowFile = session.get(); if (flowFile == null) { break; } final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue(); try { new java.net.URL(url); } catch (final MalformedURLException e) { logger.error( "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure", new Object[] { flowFile, url }); flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); continue; } // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles if (lastUrl != null && !lastUrl.equals(url)) { session.transfer(flowFile); break; } lastUrl = url; toSend.add(flowFile); if (client == null) { final Config config = getConfig(url, context); final HttpClientConnectionManager conMan = config.getConnectionManager(); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setConnectionManager(conMan); clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException { final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext); final ManagedHttpClientConnection conn = coreContext .getConnection(ManagedHttpClientConnection.class); if (!conn.isOpen()) { return; } final SSLSession sslSession = conn.getSSLSession(); if (sslSession != null) { final X509Certificate[] certChain = sslSession.getPeerCertificateChain(); if (certChain == null || certChain.length == 0) { throw new SSLPeerUnverifiedException("No certificates found"); } final X509Certificate cert = certChain[0]; dnHolder.set(cert.getSubjectDN().getName().trim()); } } }); clientBuilder.disableAutomaticRetries(); clientBuilder.disableContentCompression(); client = clientBuilder.build(); } bytesToSend += flowFile.getSize(); break; } if (toSend.isEmpty()) { return; } final String url = lastUrl; final HttpPost post = new HttpPost(url); final List<FlowFile> flowFileList = toSend; String userName = "Chris"; String password = "password"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("userName", userName); builder.addTextBody("password", password); for (final FlowFile flowFile : flowFileList) { session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream rawIn) throws IOException { InputStream in = new ByteArrayInputStream(IOUtils.toByteArray(rawIn)); builder.addBinaryBody("file", in, ContentType.DEFAULT_BINARY, "filename"); } }); } final HttpEntity entity2 = builder.build(); post.setEntity(entity2); post.setConfig(requestConfig); final String contentType; contentType = DEFAULT_CONTENT_TYPE; post.setHeader(CONTENT_TYPE_HEADER, contentType); post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true"); post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION); post.setHeader(TRANSACTION_ID_HEADER, transactionId); // Do the actual POST final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles"; final String uploadDataRate; final long uploadMillis; CloseableHttpResponse response = null; try { final StopWatch stopWatch = new StopWatch(true); response = client.execute(post); // consume input stream entirely, ignoring its contents. If we // don't do this, the Connection will not be returned to the pool EntityUtils.consume(response.getEntity()); stopWatch.stop(); uploadDataRate = stopWatch.calculateDataRate(bytesToSend); uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS); } catch (final IOException e) { logger.error("Failed to Post {} due to {}; transferring to failure", new Object[] { flowFileDescription, e }); context.yield(); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } finally { if (response != null) { try { response.close(); } catch (final IOException e) { getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e }); } } } // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us // from posting to some other webservice and then attempting to delete some resource to which // we are redirected final int responseCode = response.getStatusLine().getStatusCode(); final String responseReason = response.getStatusLine().getReasonPhrase(); String holdUri = null; if (responseCode == HttpServletResponse.SC_SEE_OTHER) { final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME); if (locationUriHeader != null) { if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) { final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME); if (holdUriHeader != null) { holdUri = holdUriHeader.getValue(); } } } if (holdUri == null) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error( "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } return; } } if (holdUri == null) { if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error( "Failed to Post {} to {}: response code was {}:{}; will yield processing, " + "since the destination is temporarily unavailable", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } context.yield(); return; } if (responseCode >= 300) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error("Failed to Post {} to {}: response code was {}:{}", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } return; } logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription, url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate }); for (final FlowFile flowFile : toSend) { session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis, true); session.transfer(flowFile, REL_SUCCESS); } return; } // // the response indicated a Hold URI; delete the Hold. // // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have // changed over the past, so we have to take into account a few different possibilities. String fullHoldUri = holdUri; if (holdUri.startsWith("/contentListener")) { // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener, // as this really indicates that it should be whatever we posted to -- if posting directly to the // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may // be posting to some other URL. fullHoldUri = url + holdUri.substring(16); } else if (holdUri.startsWith("/")) { // URL indicates the full path but not hostname or port; use the same hostname & port that we posted // to but use the full path indicated by the response. int firstSlash = url.indexOf("/", 8); if (firstSlash < 0) { firstSlash = url.length(); } final String beforeSlash = url.substring(0, firstSlash); fullHoldUri = beforeSlash + holdUri; } else if (!holdUri.startsWith("http")) { // Absolute URL fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri; } final HttpDelete delete = new HttpDelete(fullHoldUri); delete.setHeader(TRANSACTION_ID_HEADER, transactionId); while (true) { try { final HttpResponse holdResponse = client.execute(delete); EntityUtils.consume(holdResponse.getEntity()); final int holdStatusCode = holdResponse.getStatusLine().getStatusCode(); final String holdReason = holdResponse.getStatusLine().getReasonPhrase(); if (holdStatusCode >= 300) { logger.error( "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure", new Object[] { flowFileDescription, holdStatusCode, holdReason }); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}", new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate }); for (final FlowFile flowFile : toSend) { session.getProvenanceReporter().send(flowFile, url); session.transfer(flowFile, REL_SUCCESS); } return; } catch (final IOException e) { logger.warn("Failed to delete Hold that destination placed on {} due to {}", new Object[] { flowFileDescription, e }); } if (!isScheduled()) { context.yield(); logger.warn( "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure", new Object[] { flowFileDescription }); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } } }
From source file:com.licryle.httpposter.HttpPoster.java
/** * Builds the {@link _ProgressiveEntity} that we will send to the server. * Takes for input an {@link HttpConfiguration} that contains the Post * variables and File Names to send.//from w w w. jav a 2 s . c o m * * @param mConf Configuration of the POST request to be processed. * @return A ProgressiveEntity which progress can be tracked as we send it to * the server. * * @throws IOException When a file in the list of files from * {@link HttpConfiguration#getFiles()} cannot be read. * * @see {@link com.licryle.httpposter.HttpPoster._ProgressiveEntity} * @see {@link com.licryle.httpposter.HttpConfiguration} */ protected _ProgressiveEntity _buildEntity(HttpConfiguration mConf) throws IOException { Log.d("HttpPoster", String.format("_buildEntity: Entering for Instance %d", _iInstanceId)); /********* Build request content *********/ MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create(); mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); mBuilder.setBoundary(mConf.getHTTPBoundary()); int iFileNb = 0; Iterator mFiles = mConf.getFiles().iterator(); while (mFiles.hasNext()) { final File mFile = (File) mFiles.next(); try { mBuilder.addBinaryBody("file_" + iFileNb, mFile, ContentType.DEFAULT_BINARY, mFile.getName()); } catch (Exception e) { throw new IOException(); } iFileNb++; } Iterator mArgs = mConf.getArgs().entrySet().iterator(); while (mArgs.hasNext()) { Map.Entry mPair = (Map.Entry) mArgs.next(); mBuilder.addTextBody((String) mPair.getKey(), (String) mPair.getValue(), ContentType.MULTIPART_FORM_DATA); } Log.d("HttpPoster", String.format("_buildEntity: Leaving for Instance %d", _iInstanceId)); return new _ProgressiveEntity(mBuilder.build(), this); }
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java
/** * attach log using run id//from ww w .jav a 2 s . c o m * * @param token * - token generate using username and password * @param scope * : project:release:cycle * @param testCaseRunId * @param filePath * - absolute path of file to be attached * @return */ public int attachTestLogsUsingRunId(long testCaseRunId, File filePath) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); final String CurrentDate = format.format(new Date()); Path path = Paths.get(filePath.toURI()); byte[] outFileArray = Files.readAllBytes(path); if (outFileArray != null) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addTextBody("desc", "Attached on " + CurrentDate, org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("entityId", String.valueOf(testCaseRunId), org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", scope); CloseableHttpResponse response = httpclient.execute(httppost); String str = null; try { str = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { } JsonElement gson = new Gson().fromJson(str, JsonElement.class); JsonElement data = gson.getAsJsonObject().get("data"); int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString()); return id; } finally { httpclient.close(); } } else { System.out.println(filePath + " file does not exists"); } } catch (Exception ex) { System.out.println("Error in attaching file - " + filePath); System.out.println(ex.getMessage()); } return 0; }
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java
/** * attach log using run id//from w ww. j a v a2 s. c o m * * @param token * - token generate using username and password * @param scope * : project:release:cycle * @param testCaseRunId * @param filePath * - absolute path of file to be attached * @param serviceUrl * @param scope * @return */ public int attachTestLogsUsingRunID(String serviceUrl, long testCaseRunId, File filePath, String scope) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); final String CurrentDate = format.format(new Date()); Path path = Paths.get(filePath.toURI()); byte[] outFileArray = Files.readAllBytes(path); if (outFileArray != null) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addTextBody("desc", "Attached on " + CurrentDate, org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("entityId", String.valueOf(testCaseRunId), org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", scope); CloseableHttpResponse response = httpclient.execute(httppost); String str = null; try { str = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { } JsonElement gson = new Gson().fromJson(str, JsonElement.class); JsonElement data = gson.getAsJsonObject().get("data"); int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString()); return id; } finally { httpclient.close(); } } else { System.out.println(filePath + " file does not exists"); } } catch (Exception ex) { System.out.println("Error in attaching file - " + filePath); System.out.println(ex.getMessage()); } return 0; }
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 ww w . jav a 2 s. c o m 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:at.gv.egiz.sl.util.BKUSLConnector.java
private String performHttpBulkRequestToBKU(String xmlRequest, BulkRequestPackage pack, SignParameter parameter) throws ClientProtocolException, IOException, IllegalStateException { CloseableHttpClient client = null;/*from w w w .ja va 2s . com*/ try { client = buildHttpClient(); HttpPost post = new HttpPost(this.bkuUrl); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setCharset(Charset.forName("UTF-8")); entityBuilder.addTextBody(XMLREQUEST, xmlRequest, ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8"))); if (parameter != null) { String transactionId = parameter.getTransactionId(); if (transactionId != null) { entityBuilder.addTextBody("TransactionId_", transactionId); } } for (SignRequestPackage signRequestPackage : pack.getSignRequestPackages()) { if (pack != null && signRequestPackage != null && signRequestPackage.getCmsRequest().getSignatureData() != null) { entityBuilder.addBinaryBody("fileupload", PDFUtils.blackOutSignature(signRequestPackage.getCmsRequest().getSignatureData(), signRequestPackage.getCmsRequest().getByteRange())); } } post.setEntity(entityBuilder.build()); HttpResponse response = client.execute(post); logger.debug("Response Code : " + response.getStatusLine().getStatusCode()); if (parameter instanceof BKUHeaderHolder) { BKUHeaderHolder holder = (BKUHeaderHolder) parameter; Header[] headers = response.getAllHeaders(); if (headers != null) { for (int i = 0; i < headers.length; i++) { BKUHeader hdr = new BKUHeader(headers[i].getName(), headers[i].getValue()); logger.debug("Response Header : {}", hdr.toString()); holder.getProcessInfo().add(hdr); } } BKUHeader hdr = new BKUHeader(ErrorConstants.STATUS_INFO_SIGDEVICE, SIGNATURE_DEVICE); logger.debug("Response Header : {}", hdr.toString()); holder.getProcessInfo().add(hdr); } BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); response = null; rd = null; logger.trace(result.toString()); return result.toString(); } catch (PDFIOException e) { throw new PdfAsWrappedIOException(e); } finally { if (client != null) { client.close(); } } }
From source file:be.samey.io.ServerConn.java
private HttpEntity makeEntity(String baits, String[] names, Path[] filepaths, double poscutoff, double negcutoff, String[] orthNames, Path[] orthPaths) throws UnsupportedEncodingException { MultipartEntityBuilder mpeb = MultipartEntityBuilder.create(); //make hidden form fields, to the server knows to use the api mpeb.addPart("__controller", new StringBody("api")); mpeb.addPart("__action", new StringBody("execute_job")); //make the bait part StringBody baitspart = new StringBody(baits, ContentType.TEXT_PLAIN); mpeb.addPart("baits", baitspart); //make the species file upload parts for (int i = 0; i < CyModel.MAX_SPECIES_COUNT; i++) { if (i < names.length && i < filepaths.length) { mpeb.addBinaryBody("matrix[]", filepaths[i].toFile(), ContentType.TEXT_PLAIN, names[i]); }//w w w. j a v a2 s . c o m } //make the cutoff parts StringBody poscpart = new StringBody(Double.toString(poscutoff)); mpeb.addPart("positive_correlation", poscpart); StringBody negcpart = new StringBody(Double.toString(negcutoff)); mpeb.addPart("negative_correlation", negcpart); //make the orthgroup file upload parts for (int i = 0; i < CyModel.MAX_ORTHGROUP_COUNT; i++) { if (cyModel.getOrthGroupPaths() != null && i < orthNames.length && i < orthPaths.length) { mpeb.addBinaryBody("orthologs[]", orthPaths[i].toFile(), ContentType.TEXT_PLAIN, orthNames[i]); } } return mpeb.build(); }