List of usage examples for org.apache.commons.httpclient.methods.multipart FilePartSource FilePartSource
public FilePartSource(String paramString, File paramFile) throws FileNotFoundException
From source file:com.cognifide.maven.plugins.crx.CrxPackageUploadMojo.java
protected List<Part> createUploadParameters(File file) throws IOException { List<Part> partList = new ArrayList<Part>(); if (file != null) { partList.add(new FilePart("package", new FilePartSource(file.getName(), file))); }//from ww w . java2s . c o m partList.add(new StringPart("force", Boolean.toString(this.force))); return partList; }
From source file:ccc.migration.FileUploader.java
/** {@inheritDoc} */ public void uploadFile(final UUID parentId, final String fileName, final String originalTitle, final String originalDescription, final Date originalLastUpdate, final File file, final boolean publish) { try {/*from ww w .j a v a2 s.c o m*/ if (file.length() < 1) { LOG.warn("Zero length file : " + fileName); return; } final PartSource ps = new FilePartSource(file.getName(), file); uploadFile(_filesUrl, parentId, fileName, originalTitle, originalDescription, originalLastUpdate, ps, HTTP.determineMimetype(file.getName()).toString(), null, publish); } catch (final RuntimeException e) { LOG.error("Upload failed: " + file.getAbsolutePath(), e); } catch (final IOException e) { LOG.error("Upload failed: " + file.getAbsolutePath(), e); } }
From source file:com.ziaconsulting.zoho.EditorController.java
@Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { Match match = req.getServiceMatch(); Map<String, String> vars = match.getTemplateVars(); NodeRef theNodeRef = new NodeRef(vars.get("store_type"), vars.get("store_id"), vars.get("id")); String fileName = serviceRegistry.getNodeService().getProperty(theNodeRef, ContentModel.PROP_NAME) .toString();//w ww .ja v a 2 s .c om String protocol = ssl ? "https" : "http"; String extension; if (fileName.lastIndexOf('.') != -1) { extension = fileName.substring(fileName.lastIndexOf('.') + 1); } else { String contentMime = serviceRegistry.getContentService() .getReader(theNodeRef, ContentModel.PROP_CONTENT).getMimetype(); extension = serviceRegistry.getMimetypeService().getExtensionsByMimetype().get(contentMime); // Attach this extension to the filename fileName += "." + extension; log.debug("Extension not found, using mimetype " + contentMime + " to guess the extension file name is now " + fileName); } String zohoUrl = ""; if (Arrays.binarySearch(zohoDocFileExtensions, extension) >= 0) { zohoUrl = writerUrl; } else if (Arrays.binarySearch(zohoXlsFileExtensions, extension) >= 0) { zohoUrl = sheetUrl; } else if (Arrays.binarySearch(zohoPptFileExtensions, extension) >= 0) { zohoUrl = showUrl; } else { log.info("Invalid extension " + extension); return getErrorMap("Invalid extension"); } // Create multipart form for post List<Part> parts = new ArrayList<Part>(); String output = ""; if (vars.get("mode").equals("edit")) { output = "url"; parts.add(new StringPart("mode", "collabedit")); } else if (vars.get("mode").equals("view")) { output = "viewurl"; parts.add(new StringPart("mode", "view")); } String docIdBase = vars.get("store_type") + vars.get("store_id") + vars.get("id"); parts.add(new StringPart("documentid", generateDocumentId(docIdBase))); String id = theNodeRef.toString() + "#" + serviceRegistry.getAuthenticationService().getCurrentTicket(); parts.add(new StringPart("id", id)); parts.add(new StringPart("format", extension)); parts.add(new StringPart("filename", fileName)); parts.add(new StringPart("username", serviceRegistry.getAuthenticationService().getCurrentUserName())); parts.add(new StringPart("skey", skey)); if (useRemoteAgent) { parts.add(new StringPart("agentname", remoteAgentName)); } else { String saveUrl; saveUrl = protocol + "://" + this.saveUrl + "/alfresco/s/zohosave"; parts.add(new StringPart("saveurl", saveUrl)); } ContentReader cr = serviceRegistry.getContentService().getReader(theNodeRef, ContentModel.PROP_CONTENT); if (!(cr instanceof FileContentReader)) { log.error("The content reader was not a FileContentReader"); return getErrorMap("Error"); } PartSource src = null; try { src = new FilePartSource(fileName, ((FileContentReader) cr).getFile()); } catch (FileNotFoundException e) { e.printStackTrace(); log.error("The content did not exist."); return getErrorMap("Error"); } parts.add(new FilePart("content", src, cr.getMimetype(), null)); HttpClient client = new HttpClient(); String zohoFormUrl = protocol + "://" + zohoUrl + "/remotedoc.im?" + "apikey=" + apiKey + "&output=" + output; PostMethod httppost = new PostMethod(zohoFormUrl); httppost.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), httppost.getParams())); Map<String, Object> returnMap = getReturnMap(); String retStr = ""; int zohoStatus = 0; try { zohoStatus = client.executeMethod(httppost); retStr = httppost.getResponseBodyAsString(); } catch (HttpException he) { log.error("Error", he); returnMap = getErrorMap("Error"); } catch (IOException io) { io.printStackTrace(); log.error("Error", io); returnMap = getErrorMap("Error"); } if (zohoStatus == 200) { Map<String, String> parsedResponse = parseResponse(retStr); if (parsedResponse.containsKey("RESULT") && parsedResponse.get("RESULT").equals("TRUE")) { returnMap.put("zohourl", parsedResponse.get("URL")); } else if (parsedResponse.containsKey("RESULT") && parsedResponse.get("RESULT").equals("FALSE")) { returnMap = getErrorMap(parsedResponse.get("ERROR")); } } else { returnMap = getErrorMap("Remote server did not respond"); } return returnMap; }
From source file:JiraWebClient.java
public void attachFile(final JiraIssue issue, final String comment, final String filename, final File file, final String contentType, IProgressMonitor monitor) throws JiraException { try {//from w w w . j a v a 2s .co m FilePartSource partSource = new FilePartSource(filename, file); attachFile(issue, comment, new FilePart("filename.1", partSource), contentType, monitor); //$NON-NLS-1$ } catch (FileNotFoundException e) { throw new JiraException(e); } }
From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java
/** * post multiple resources through a single call, all resources are posted * under 'repoPath'/*from ww w. ja v a2 s . c o m*/ * * @param repoPath * path in registry where resources should be posted * @param resourceList * list of resources to be posted * @return * @throws HttpException * @throws IOException * @throws RegistryExtException * @throws OAuthSystemException * @throws OAuthProblemException */ public String postMultiResources(String repoPath, List<ResourceFileType> resourceList) throws HttpException, IOException, RegistryExtException, OAuthSystemException, OAuthProblemException { Map<String, Object> session = ActionContext.getContext().getSession(); int statusCode = 200; String accessToken = (String) session.get(Constants.SESSION_TOKEN); String requestURL = composeURL(FILEOPPREFIX, repoPath); if (logger.isDebugEnabled()) { logger.debug("Post request URL=" + requestURL); } HttpClient httpclient = new HttpClient(); PostMethod post = new PostMethod(requestURL); post.addRequestHeader("Content-Type", "multipart/form-data"); post.addRequestHeader("Authorization", "Bearer " + accessToken); Part[] parts = new Part[resourceList.size()]; for (int i = 0; i < resourceList.size(); i++) { parts[i] = new FilePart(resourceList.get(i).getName(), new FilePartSource(resourceList.get(i).getName(), resourceList.get(i).getFile())); } post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); try { httpclient.executeMethod(post); statusCode = post.getStatusLine().getStatusCode(); /* handle token expiration */ if (statusCode == 401) { logger.info(String.format("Access token %s expired, going to refresh it", accessToken)); refreshToken(session); // use refreshed access token accessToken = (String) session.get(Constants.SESSION_TOKEN); post.addRequestHeader("Authorization", "Bearer " + accessToken); // re-send the request httpclient.executeMethod(post); statusCode = post.getStatusLine().getStatusCode(); } if (post.getStatusLine().getStatusCode() != 204) { throw new RegistryExtException( "Failed in post resources : HTTP error code : " + post.getStatusLine().getStatusCode()); } } finally { if (post != null) post.releaseConnection(); } return repoPath; }
From source file:org.apache.commons.httpclient.methods.multipart.FilePart.java
/** * FilePart Constructor./* www. j a va 2 s . com*/ * * @param name the name of the file part * @param fileName the file name * @param file the file to post * * @throws FileNotFoundException if the <i>file</i> is not a normal * file or if it is not readable. */ public FilePart(String name, String fileName, File file) throws FileNotFoundException { this(name, new FilePartSource(fileName, file), null, null); }
From source file:org.apache.commons.httpclient.methods.multipart.FilePart.java
/** * FilePart Constructor./*from w w w. j a v a 2 s .co m*/ * * @param name the name of the file part * @param fileName the file name * @param file the file to post * @param contentType the content type for this part, if <code>null</code> the * {@link #DEFAULT_CONTENT_TYPE default} is used * @param charset the charset encoding for this part, if <code>null</code> the * {@link #DEFAULT_CHARSET default} is used * * @throws FileNotFoundException if the <i>file</i> is not a normal * file or if it is not readable. */ public FilePart(String name, String fileName, File file, String contentType, String charset) throws FileNotFoundException { this(name, new FilePartSource(fileName, file), contentType, charset); }
From source file:org.apache.sling.maven.bundlesupport.AbstractBundleDeployMojo.java
private void post(String targetURL, File file) throws MojoExecutionException { PostMethod filePost = new PostMethod(targetURL); try {/* w ww. j av a2 s. co m*/ Part[] parts = { new FilePart(file.getName(), new FilePartSource(file.getName(), file)), new StringPart("_noredir_", "_noredir_") }; 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) { getLog().info("Bundle deployed"); } else { String msg = "Deployment failed, cause: " + HttpStatus.getStatusText(status); if (failOnError) { throw new MojoExecutionException(msg); } else { getLog().error(msg); } } } catch (Exception ex) { throw new MojoExecutionException("Deployment on " + targetURL + " failed, cause: " + ex.getMessage(), ex); } finally { filePost.releaseConnection(); } }
From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java
/** * Install the bundle via POST to the Felix Web Console * @param targetURL the URL to the Felix Web Console Bundles listing * @param file the file to POST/* w w w .java2 s .c om*/ * @throws MojoExecutionException * @see <a href="http://felix.apache.org/documentation/subprojects/apache-felix-web-console/web-console-restful-api.html#post-requests">Webconsole RESTful API</a> * @see <a href="https://github.com/apache/felix/blob/trunk/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundlesServlet.java">BundlesServlet@Github</a> */ protected void postToFelix(String targetURL, File file) throws MojoExecutionException { // append pseudo path after root URL to not get redirected for nothing final PostMethod filePost = new PostMethod(targetURL + "/install"); try { // set referrer filePost.setRequestHeader("referer", "about:blank"); List<Part> partList = new ArrayList<Part>(); partList.add(new StringPart("action", "install")); partList.add(new StringPart("_noredir_", "_noredir_")); partList.add(new FilePart("bundlefile", new FilePartSource(file.getName(), file))); partList.add(new StringPart("bundlestartlevel", bundleStartLevel)); if (bundleStart) { partList.add(new StringPart("bundlestart", "start")); } if (refreshPackages) { partList.add(new StringPart("refreshPackages", "true")); } Part[] parts = partList.toArray(new Part[partList.size()]); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); int status = getHttpClient().executeMethod(filePost); if (status == HttpStatus.SC_OK) { getLog().info("Bundle installed"); } else { String msg = "Installation failed, cause: " + HttpStatus.getStatusText(status); if (failOnError) { throw new MojoExecutionException(msg); } else { getLog().error(msg); } } } catch (Exception ex) { throw new MojoExecutionException("Installation on " + targetURL + " failed, cause: " + ex.getMessage(), ex); } finally { filePost.releaseConnection(); } }
From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java
/** * Perform the operation via POST to SlingPostServlet * @param targetURL the URL of the Sling instance to post the file to. * @param file the file being interacted with the POST to Sling. * @throws MojoExecutionException/*from w ww .j av a2 s . c o m*/ */ protected void postToSling(String targetURL, File file) throws MojoExecutionException { /* truncate off trailing slash as this has special behaviorisms in * the SlingPostServlet around created node name conventions */ if (targetURL.endsWith("/")) { targetURL = targetURL.substring(0, targetURL.length() - 1); } // append pseudo path after root URL to not get redirected for nothing final PostMethod filePost = new PostMethod(targetURL); try { Part[] parts = new Part[2]; // Add content type to force the configured mimeType value parts[0] = new FilePart("*", new FilePartSource(file.getName(), file), mimeType, null); // Add TypeHint to have jar be uploaded as file (not as resource) parts[1] = new StringPart("*@TypeHint", "nt:file"); /* Request JSON response from Sling instead of standard HTML, to * reduce the payload size (if the PostServlet supports it). */ filePost.setRequestHeader("Accept", JSON_MIME_TYPE); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); int status = getHttpClient().executeMethod(filePost); // SlingPostServlet may return 200 or 201 on creation, accept both if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) { getLog().info("Bundle installed"); } else { String msg = "Installation failed, cause: " + HttpStatus.getStatusText(status); if (failOnError) { throw new MojoExecutionException(msg); } else { getLog().error(msg); } } } catch (Exception ex) { throw new MojoExecutionException("Installation on " + targetURL + " failed, cause: " + ex.getMessage(), ex); } finally { filePost.releaseConnection(); } }