List of usage examples for org.apache.commons.httpclient.methods.multipart FilePart FilePart
public FilePart(String paramString1, PartSource paramPartSource, String paramString2, String paramString3)
From source file:com.discursive.jccook.httpclient.MultipartPostFileExample.java
public static void main(String[] args) throws HttpException, IOException { // Configure Logging System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug"); HttpClient client = new HttpClient(); // Create POST method String weblintURL = "http://ats.nist.gov/cgi-bin/cgi.tcl/echo.cgi"; MultipartPostMethod method = new MultipartPostMethod(weblintURL); File file = new File("data", "test.txt"); File file2 = new File("data", "sample.txt"); method.addParameter("test.txt", file); method.addPart(new FilePart("sample.txt", file2, "text/plain", "ISO-8859-1")); // Execute and print response client.executeMethod(method);/* w w w . j a va2s.co m*/ String response = method.getResponseBodyAsString(); System.out.println(response); method.releaseConnection(); }
From source file:net.formio.servlet.MockServletRequests.java
/** * Creates new servlet request that contains given resource as multi part. * @param paramName// w w w .j av a 2 s. com * @param resourceName * @return */ public static MockHttpServletRequest newRequest(String paramName, String resourceName, String mimeType) { try { MockHttpServletRequest request = new MockHttpServletRequest(); // Load resource being uploaded ByteArrayOutputStream bos = new ByteArrayOutputStream(); Streams.copy(MockServletRequests.class.getResourceAsStream(resourceName), bos, true); byte[] fileContent = bos.toByteArray(); // Create part & entity from resource Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent), mimeType, (String) null) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); request.setContent(requestContent.toByteArray()); // Set content type of request (important, includes MIME boundary string) String contentType = multipartRequestEntity.getContentType(); request.setContentType(contentType); request.setMethod("POST"); return request; } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
From source file:net.formio.portlet.MockPortletRequests.java
/** * Creates new portlet request that contains given resource as multi part. * @param paramName/*from ww w . j a v a2s. c o m*/ * @param resourceName * @return */ public static MockMultipartActionRequest newRequest(String paramName, String resourceName, String mimeType) { try { MockMultipartActionRequest request = new MockMultipartActionRequest(); // Load resource being uploaded ByteArrayOutputStream bos = new ByteArrayOutputStream(); Streams.copy(MockPortletRequests.class.getResourceAsStream(resourceName), bos, true); byte[] fileContent = bos.toByteArray(); // Create part & entity from resource Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent), mimeType, (String) null) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); request.setContent(requestContent.toByteArray()); // Set content type of request (important, includes MIME boundary string) String contentType = multipartRequestEntity.getContentType(); request.setContentType(contentType); return request; } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
From source file:it.iit.genomics.cru.simsearch.bundle.utils.PantherBridge.java
public static Collection<String[]> getEnrichment(String organism, String fileName, double threshold) { ArrayList<String[]> results = new ArrayList<>(); ArrayListMultimap<String, String> genes = ArrayListMultimap.create(); ArrayListMultimap<Double, String> pvalues = ArrayListMultimap.create(); HashSet<String> uniqueGenes = new HashSet<>(); try {//w w w .ja v a 2 s . co m String[] enrichmentTypes = { "process", "pathway" }; for (String enrichmentType : enrichmentTypes) { HttpClient client = new HttpClient(); MultipartPostMethod method = new MultipartPostMethod( "http://pantherdb.org/webservices/garuda/tools/enrichment/VER_2/enrichment.jsp?"); // Define name-value pairs to set into the QueryString method.addParameter("organism", organism); method.addParameter("type", "enrichment"); method.addParameter("enrichmentType", enrichmentType); // "function", // "process", // "cellular_location", // "protein_class", // "pathway" File inputFile = new File(fileName); method.addPart(new FilePart("geneList", inputFile, "text/plain", "ISO-8859-1")); // PANTHER does not use the ID type // method.addParameter("IdType", "UniProt"); // Execute and print response client.executeMethod(method); String response = method.getResponseBodyAsString(); for (String line : response.split("\n")) { if (false == "".equals(line.trim())) { String[] row = line.split("\t"); // Id Name GeneId P-value if ("Id".equals(row[0])) { // header continue; } // if (row.length > 1) { String name = row[1]; String gene = row[2]; Double pvalue = Double.valueOf(row[3]); uniqueGenes.add(gene); if (pvalue < threshold) { if (false == genes.containsKey(name)) { pvalues.put(pvalue, name); } genes.put(name, gene); } // } else { // System.out.println("oups: " + row[0]); // } } } method.releaseConnection(); } ArrayList<Double> pvalueList = new ArrayList<>(); Collections.sort(pvalueList); pvalueList.addAll(pvalues.keySet()); Collections.sort(pvalueList); int numGenes = uniqueGenes.size(); for (Double pvalue : pvalueList) { for (String name : pvalues.get(pvalue)) { String geneList = String.join(",", genes.get(name)); String result[] = { name, "" + pvalue, genes.get(name).size() + "/" + numGenes, geneList }; results.add(result); } } } catch (IOException e) { e.printStackTrace(); } return results; }
From source file:fr.opensagres.xdocreport.remoting.reporting.server.ReportingServiceWithHttpClientTestCase.java
@Test public void generateReport() throws Exception { PostMethod post = new PostMethod("http://localhost:" + PORT + "/report"); String ct = "multipart/mixed"; post.setRequestHeader("Content-Type", ct); Part[] parts = new Part[6]; String fileName = "DocxProjectWithVelocityAndImageList.docx"; // 1) Param [templateDocument]: input stream of the docx, odt... parts[0] = new FilePart("templateDocument", new File(root, fileName), "application/vnd.oasis.opendocument.text", "UTF-8"); // 2) Param [templateEngineKind]: Velocity or Freemarker parts[1] = new StringPart("templateEngineKind", "Velocity"); // 3) Param [metadata]: XML fields metadata // XML fields metadata // ex:<?xml version="1.0" encoding="UTF-8" standalone="yes"?><fields templateEngineKind="" // ><description><![CDATA[]]></description><field name="developers.Name" list="true" imageName="" // syntaxKind=""><description><![CDATA[]]></description></field><field name="developers.LastName" list="true" // imageName="" syntaxKind=""><description><![CDATA[]]></description></field><field name="developers.Mail" // list="true" imageName="" syntaxKind=""><description><![CDATA[]]></description></field></fields> FieldsMetadata metadata = new FieldsMetadata(); // manage lazy loop for the table which display list of developers in the docx metadata.addFieldAsList("developers.Name"); metadata.addFieldAsList("developers.LastName"); metadata.addFieldAsList("developers.Mail"); StringWriter xml = new StringWriter(); metadata.saveXML(xml);/*w w w .jav a 2 s . co m*/ parts[2] = new StringPart("metadata", xml.toString()); // 4) Param [data]: JSON data which must be merged with the docx template String jsonData = "{" + "project:" + "{Name:'XDocReport', URL:'http://code.google.com/p/xdocreport'}, " + "developers:" + "[" + "{Name: 'ZERR', Mail: 'angelo.zerr@gmail.com',LastName: 'Angelo'}," + "{Name: 'Leclercq', Mail: 'pascal.leclercq@gmail.com',LastName: 'Pascal'}" + "]" + "}"; parts[3] = new StringPart("data", jsonData); // 4) Param [dataType]: data type parts[4] = new StringPart("dataType", "json"); // 5) Param [outFileName]: output file name parts[5] = new StringPart("outFileName", "report.docx"); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); HttpClient httpclient = new HttpClient(); try { int result = httpclient.executeMethod(post); Assert.assertEquals(200, result); Assert.assertEquals("attachment; filename=\"report.docx\"", post.getResponseHeader("Content-Disposition").getValue()); byte[] convertedDocument = post.getResponseBody(); Assert.assertNotNull(convertedDocument); File outFile = new File("target/report.docx"); outFile.getParentFile().mkdirs(); IOUtils.copy(new ByteArrayInputStream(convertedDocument), new FileOutputStream(outFile)); } finally { post.releaseConnection(); } }
From source file:mercury.UploadController.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); try {//from w ww . j a va 2 s.c o m List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String targetUrl = Config.getConfigProperty(ConfigurationEnum.DIGITAL_MEDIA); if (StringUtils.isBlank(targetUrl)) { targetUrl = request.getRequestURL().toString(); targetUrl = targetUrl.substring(0, targetUrl.lastIndexOf('/')); } targetUrl += "/DigitalMediaController"; PostMethod filePost = new PostMethod(targetUrl); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); UploadPartSource src = new UploadPartSource(item.getName(), item.getSize(), item.getInputStream()); Part[] parts = new Part[1]; parts[0] = new FilePart(item.getName(), src, item.getContentType(), null); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { String data = filePost.getResponseBodyAsString(); JSONObject json = new JSONObject(data); if (json.has("id")) { JSONObject responseJson = new JSONObject(); responseJson.put("success", true); responseJson.put("id", json.getString("id")); responseJson.put("uri", targetUrl + "?id=" + json.getString("id")); response.getWriter().write(responseJson.toString()); } } filePost.releaseConnection(); return; } } } catch (FileUploadException e) { e.printStackTrace(); } catch (JSONException je) { je.printStackTrace(); } } response.getWriter().write("{success: false}"); }
From source file:fr.opensagres.xdocreport.remoting.converter.server.ConverterServiceTestCase.java
@Test public void convertPDF() throws Exception { PostMethod post = new PostMethod("http://localhost:" + PORT + "/convert"); String ct = "multipart/mixed"; post.setRequestHeader("Content-Type", ct); Part[] parts = new Part[4]; String fileName = "ODTCV.odt"; parts[0] = new FilePart("document", new File(root, fileName), "application/vnd.oasis.opendocument.text", "UTF-8"); parts[1] = new StringPart("outputFormat", ConverterTypeTo.PDF.name()); parts[2] = new StringPart("via", ConverterTypeVia.ODFDOM.name()); parts[3] = new StringPart("download", "true"); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); HttpClient httpclient = new HttpClient(); try {//from w w w . j av a 2 s. c o m int result = httpclient.executeMethod(post); Assert.assertEquals(200, result); Assert.assertEquals("attachment; filename=\"ODTCV_odt.pdf\"", post.getResponseHeader("Content-Disposition").getValue()); byte[] convertedDocument = post.getResponseBody(); Assert.assertNotNull(convertedDocument); File outFile = new File("target/ODTCV_odt.pdf"); outFile.getParentFile().mkdirs(); IOUtils.copy(new ByteArrayInputStream(convertedDocument), new FileOutputStream(outFile)); } finally { post.releaseConnection(); } }
From source file:com.zimbra.cs.client.soap.LmcSendMsgRequest.java
public String postAttachment(String uploadURL, LmcSession session, File f, String domain, // cookie domain e.g. ".example.zimbra.com" int msTimeout) throws LmcSoapClientException, IOException { String aid = null;//from w ww. j av a 2 s . c om // set the cookie. if (session == null) System.err.println(System.currentTimeMillis() + " " + Thread.currentThread() + " LmcSendMsgRequest.postAttachment session=null"); HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); PostMethod post = new PostMethod(uploadURL); ZAuthToken zat = session.getAuthToken(); Map<String, String> cookieMap = zat.cookieMap(false); if (cookieMap != null) { HttpState initialState = new HttpState(); for (Map.Entry<String, String> ck : cookieMap.entrySet()) { Cookie cookie = new Cookie(domain, ck.getKey(), ck.getValue(), "/", -1, false); initialState.addCookie(cookie); } client.setState(initialState); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } post.getParams().setSoTimeout(msTimeout); int statusCode = -1; try { String contentType = URLConnection.getFileNameMap().getContentTypeFor(f.getName()); Part[] parts = { new FilePart(f.getName(), f, contentType, "UTF-8") }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); statusCode = HttpClientUtil.executeMethod(client, post); // parse the response if (statusCode == 200) { // paw through the returned HTML and get the attachment id String response = post.getResponseBodyAsString(); //System.out.println("response is\n" + response); int lastQuote = response.lastIndexOf("'"); int firstQuote = response.indexOf("','") + 3; if (lastQuote == -1 || firstQuote == -1) throw new LmcSoapClientException("Attachment post failed, unexpected response: " + response); aid = response.substring(firstQuote, lastQuote); } else { throw new LmcSoapClientException("Attachment post failed, status=" + statusCode); } } catch (IOException e) { System.err.println("Attachment post failed"); e.printStackTrace(); throw e; } finally { post.releaseConnection(); } return aid; }
From source file:com.netflix.postreview.ExtendedCrucibleSession.java
/** * Override addItemsToReview to differentiate the 3 cases of pairs present 1/1, 1/0, 0/1 (0/0 * being invalid).//from w w w.j av a 2 s .c o m */ @Override public void addItemsToReview(PermId permId, Collection<UploadItem> uploadItems) throws RemoteApiException { final String REVIEW_SERVICE = "/rest-service/reviews-v1"; final String ADD_FILE = "/addFile"; try { String urlString = getBaseUrl() + REVIEW_SERVICE + "/" + permId.getId() + ADD_FILE; for (UploadItem uploadItem : uploadItems) { // Item add if (uploadItem.getOldContent() == null && uploadItem.getNewContent() != null) { ByteArrayPartSource targetNewFile = new ByteArrayPartSource(uploadItem.getFileName(), uploadItem.getNewContent()); Part[] parts = { new FilePart("file", targetNewFile, uploadItem.getNewContentType(), uploadItem.getNewCharset()) }; retrievePostResponse(urlString, parts, true); // Item modify // TODO: use this approach for deletions too for now. } else if (true) { //uploadItem.getOldContent() != null && uploadItem.getNewContent() != null) { ByteArrayPartSource targetNewFile = new ByteArrayPartSource(uploadItem.getFileName(), uploadItem.getNewContent()); ByteArrayPartSource targetOldFile = new ByteArrayPartSource(uploadItem.getFileName(), uploadItem.getOldContent()); Part[] parts = { new FilePart("file", targetNewFile, uploadItem.getNewContentType(), uploadItem.getNewCharset()), new FilePart("diffFile", targetOldFile, uploadItem.getOldContentType(), uploadItem.getOldCharset()) }; retrievePostResponse(urlString, parts, true); // Item delete // TODO: this rest combo doesn't work: crucible seems to need the "file" part... } else { // uploadItem.getOldContent() != null && uploadItem.getNewContent() == null ByteArrayPartSource targetOldFile = new ByteArrayPartSource(uploadItem.getFileName(), uploadItem.getOldContent()); Part[] parts = { new FilePart("diffFile", targetOldFile, uploadItem.getOldContentType(), uploadItem.getOldCharset()) }; retrievePostResponse(urlString, parts, true); } } } catch (JDOMException e) { throw new RemoteApiException(getBaseUrl() + ": Server returned malformed response", e); } }
From source file:fr.opensagres.xdocreport.remoting.reporting.server.ReportingServiceWithHttpClientTestCase.java
@Test public void generateReportandConvertToPDF() throws Exception { PostMethod post = new PostMethod("http://localhost:" + PORT + "/report"); String ct = "multipart/mixed"; post.setRequestHeader("Content-Type", ct); Part[] parts = new Part[7]; String fileName = "DocxProjectWithVelocityAndImageList.docx"; // 1) Param [templateDocument]: input stream of the docx, odt... parts[0] = new FilePart("templateDocument", new File(root, fileName), "application/vnd.oasis.opendocument.text", "UTF-8"); // 2) Param [templateEngineKind]: Velocity or Freemarker parts[1] = new StringPart("templateEngineKind", "Velocity"); // 3) Param [metadata]: XML fields metadata // XML fields metadata // ex:<?xml version="1.0" encoding="UTF-8" standalone="yes"?><fields templateEngineKind="" // ><description><![CDATA[]]></description><field name="developers.Name" list="true" imageName="" // syntaxKind=""><description><![CDATA[]]></description></field><field name="developers.LastName" list="true" // imageName="" syntaxKind=""><description><![CDATA[]]></description></field><field name="developers.Mail" // list="true" imageName="" syntaxKind=""><description><![CDATA[]]></description></field></fields> FieldsMetadata metadata = new FieldsMetadata(); // manage lazy loop for the table which display list of developers in the docx metadata.addFieldAsList("developers.Name"); metadata.addFieldAsList("developers.LastName"); metadata.addFieldAsList("developers.Mail"); StringWriter xml = new StringWriter(); metadata.saveXML(xml);/*from ww w . j a v a 2 s . c o m*/ parts[2] = new StringPart("metadata", xml.toString()); // 4) Param [data]: JSON data which must be merged with the docx template String jsonData = "{" + "project:" + "{Name:'XDocReport', URL:'http://code.google.com/p/xdocreport'}, " + "developers:" + "[" + "{Name: 'ZERR', Mail: 'angelo.zerr@gmail.com',LastName: 'Angelo'}," + "{Name: 'Leclercq', Mail: 'pascal.leclercq@gmail.com',LastName: 'Pascal'}" + "]" + "}"; parts[3] = new StringPart("data", jsonData); // 4) Param [dataType]: data type parts[4] = new StringPart("dataType", "json"); // 5) Param [outFileName]: output file name parts[5] = new StringPart("outFileName", "report.pdf"); parts[6] = new StringPart("outFormat", "PDF"); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); HttpClient httpclient = new HttpClient(); try { int result = httpclient.executeMethod(post); Assert.assertEquals(200, result); Assert.assertEquals("attachment; filename=\"report.pdf\"", post.getResponseHeader("Content-Disposition").getValue()); byte[] convertedDocument = post.getResponseBody(); Assert.assertNotNull(convertedDocument); File outFile = new File("target/report.pdf"); outFile.getParentFile().mkdirs(); IOUtils.copy(new ByteArrayInputStream(convertedDocument), new FileOutputStream(outFile)); } finally { post.releaseConnection(); } }