List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity
public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams)
From source file:com.openkm.util.DocConverter.java
/** * Handle remote OpenOffice server conversion *//*from w ww . j a va2 s . c o m*/ public void remoteConvert(String uri, File inputFile, String srcMimeType, File outputFile, String dstMimeType) throws ConversionException { PostMethod post = new PostMethod(uri); try { Part[] parts = { new FilePart(inputFile.getName(), inputFile), new StringPart("src_mime", srcMimeType), new StringPart("dst_mime", dstMimeType), new StringPart("okm_uuid", Repository.getUuid()) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); HttpClient httpclient = new HttpClient(); int rc = httpclient.executeMethod(post); log.info("Response Code: {}", rc); if (rc == HttpStatus.SC_OK) { FileOutputStream fos = new FileOutputStream(outputFile); BufferedInputStream bis = new BufferedInputStream(post.getResponseBodyAsStream()); IOUtils.copy(bis, fos); bis.close(); fos.close(); } else { throw new IOException("Error in conversion: " + rc); } } catch (HttpException e) { throw new ConversionException("HTTP exception", e); } catch (FileNotFoundException e) { throw new ConversionException("File not found exeption", e); } catch (IOException e) { throw new ConversionException("IO exception", e); } finally { post.releaseConnection(); } }
From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java
private HttpMethod buildHttpRequest(String address, MessageObject mo) throws Exception { String method = connector.getDispatcherMethod(); String content = replacer.replaceValues(connector.getDispatcherContent(), mo); String contentType = connector.getDispatcherContentType(); String charset = connector.getDispatcherCharset(); boolean isMultipart = connector.isDispatcherMultipart(); Map<String, String> headers = replacer.replaceValuesInMap(connector.getDispatcherHeaders(), mo); Map<String, String> parameters = replacer.replaceValuesInMap(connector.getDispatcherParameters(), mo); HttpMethod httpMethod = null;//from w w w. j ava 2s . c o m // populate the query parameters NameValuePair[] queryParameters = new NameValuePair[parameters.size()]; int index = 0; for (Entry<String, String> parameterEntry : parameters.entrySet()) { queryParameters[index] = new NameValuePair(parameterEntry.getKey(), parameterEntry.getValue()); index++; logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + parameterEntry.getValue() + "]"); } // create the method if ("GET".equalsIgnoreCase(method)) { httpMethod = new GetMethod(address); httpMethod.setQueryString(queryParameters); } else if ("POST".equalsIgnoreCase(method)) { PostMethod postMethod = new PostMethod(address); if (isMultipart) { logger.debug("setting multipart file content"); File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); FileUtils.writeStringToFile(tempFile, content, charset); Part[] parts = new Part[] { new FilePart(tempFile.getName(), tempFile, contentType, charset) }; postMethod.setQueryString(queryParameters); postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } else if (StringUtils.equals(contentType, "application/x-www-form-urlencoded")) { postMethod.setRequestBody(queryParameters); } else { postMethod.setQueryString(queryParameters); postMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset)); } httpMethod = postMethod; } else if ("PUT".equalsIgnoreCase(method)) { PutMethod putMethod = new PutMethod(address); putMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset)); putMethod.setQueryString(queryParameters); httpMethod = putMethod; } else if ("DELETE".equalsIgnoreCase(method)) { httpMethod = new DeleteMethod(address); httpMethod.setQueryString(queryParameters); } // set the headers for (Entry<String, String> headerEntry : headers.entrySet()) { httpMethod.setRequestHeader(new Header(headerEntry.getKey(), headerEntry.getValue())); logger.debug("setting method header: [" + headerEntry.getKey() + ", " + headerEntry.getValue() + "]"); } return httpMethod; }
From source file:com.celamanzi.liferay.portlets.rails286.OnlineClient.java
protected void createMultipartRequest(NameValuePair[] parametersBody, Map<String, Object[]> files, PostMethod method, List<File> tempFiles) throws IOException, FileNotFoundException { List<Part> parts = new ArrayList<Part>(); parametersBody = removeFileParams(parametersBody, files); for (NameValuePair param : parametersBody) { parts.add(createStringPart(param)); }//from w w w. j av a 2s.co m for (String key : files.keySet()) { File file = createFile(files.get(key)); if (file != null) { parts.add(new FilePart(key, file)); tempFiles.add(file); } } Part[] array = new Part[parts.size()]; method.setRequestEntity(new MultipartRequestEntity(parts.toArray(array), method.getParams())); method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); }
From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java
/** * @param cookies// w ww . j a v a2 s . c om * the previous requests cookies to keep in the same session. * @throws MojoExecutionException * if any error occurs during this process. */ @SuppressWarnings("deprecation") private void uploadPackage(final Cookie[] cookies) throws MojoExecutionException { PostMethod filePost = new PostMethod(crxPath + "/packmgr/list.jsp"); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); try { getLog().info("Uploading " + jarfile + " to " + filePost.getPath()); File jarFile = new File(jarfile); Part[] parts = { new FilePart("file", jarFile) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY); client.getState().addCookies(cookies); client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_DEFAULT_TIMEOUT); int status = client.executeMethod(filePost); // log the status getLog().info( "Response status: " + status + ", statusText: " + HttpStatus.getStatusText(status) + "\r\n"); if (status == HttpStatus.SC_MOVED_TEMPORARILY) { getLog().info("Upload complete"); } else { logResponseDetails(filePost); throw new MojoExecutionException( "Package upload failed, response=" + HttpStatus.getStatusText(status)); } } catch (Exception ex) { getLog().error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage()); throw new MojoExecutionException(ex.getMessage()); } finally { filePost.releaseConnection(); } }
From source file:it.haefelinger.flaka.util.HttpUpload.java
public boolean upload() { File file = null;/*from w ww . java 2s .c o m*/ String endpoint = get("endpoint", HttpUpload.ENDPOINT); String testonly = get("testonly", HttpUpload.TESTONLY); String timeout = get("timeout", HttpUpload.TIMEOUT); String filepath = get("filepath", null); String logpath = get("logpath", null); String standard = get("standard", "1.0"); syslog("endpoint: " + endpoint); syslog("testonly: " + testonly); syslog("timeouts: " + timeout); syslog("filepath: " + filepath); syslog("logpath : " + logpath); syslog("standard: " + standard); PostMethod filePost = null; boolean rc; try { /* new game */ rc = false; setError(null); set("logmsg", ""); if (testonly == null || testonly.matches("\\s*false\\s*")) { testonly = "x-do-not-test"; } else { testonly = "test"; } if (filepath == null || filepath.matches("\\s*")) { set("logmsg", "empty property `filepath', nothing to do."); return true; } /* loc to upload */ file = new File(filepath); if (file.exists() == false) { setError("loc `" + file.getPath() + "' does not exist."); return false; } if (file.isFile() == false) { setError("loc `" + file.getPath() + "' exists but not a loc."); return false; } if (file.canRead() == false) { setError("loc `" + file.getPath() + "' can't be read."); return false; } set("filesize", "" + file.length()); /* create HTTP method */ filePost = new PostMethod(endpoint); Part[] parts = { new StringPart(testonly, "(opaque)"), filepart(file) }; filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); /* execute method */ rc = exec(filePost) && eval(filePost); } finally { /* release resources in just any case */ if (filePost != null) filePost.releaseConnection(); } return rc; }
From source file:edu.ku.brc.specify.plugins.ipadexporter.iPadRepositoryHelper.java
/** * @param targetFile//from w ww.j av a2 s. c o m * @param fileName * @param dirName * @return */ public synchronized boolean sendFile(final File targetFile, final String fileName, final String dirName) { String targetURL = getWriteURL(); PostMethod filePost = new PostMethod(targetURL); try { sha1Hash = null; sha1Hash = calculateHash(targetFile); //System.out.println("Uploading " + targetFile.getName() + " to " + targetURL+ "Src Exists: "+targetFile.exists()); //System.out.println("Hash [" + sha1Hash + "]"); Part[] parts = { new FilePart(targetFile.getName(), targetFile), new StringPart("store", fileName), new StringPart("dir", dirName), new StringPart("hash", sha1Hash == null ? "" : sha1Hash), new StringPart("action", "upload"), }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(15000); int status = client.executeMethod(filePost); //System.out.println(filePost.getResponseBodyAsString()); if (status == HttpStatus.SC_OK) { System.err.println("HTTP Status: OK"); return true; } else { System.err.println("HTTP Status: " + status); System.err.println(filePost.getResponseBodyAsString()); } } catch (java.net.UnknownHostException uex) { networkConnError = true; } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { filePost.releaseConnection(); } return false; }
From source file:cuanto.api.CuantoConnector.java
/** * Adds result files to a TestRun on the Cuanto server. This adds test result files to the specified TestRun. A * test result file is not an arbitrary file, but rather it needs to be a file that is in the correct result file * format for the Cuanto project type. For instance, if the Cuanto project is a JUnit project, then it needs to be * a JUnit result file.//from w w w . j a v a 2 s.c om * @param files Test Result files to add. * @param testRun The TestRun for adding results. * @throws FileNotFoundException If any of the files are not found. */ public void importTestFiles(List<File> files, TestRun testRun) throws FileNotFoundException { String fullUri = cuantoUrl + "/testRun/submitFile"; PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, fullUri); if (testRun.id == null) { addTestRun(testRun); } post.addRequestHeader("Cuanto-TestRun-Id", testRun.id.toString()); List<FilePart> parts = new ArrayList<FilePart>(); for (File file : files) { parts.add(new FilePart(file.getName(), file)); } Part[] fileParts = parts.toArray(new Part[] {}); post.setRequestEntity(new MultipartRequestEntity(fileParts, post.getParams())); int responseCode; String responseText; try { HttpClient hclient = getHttpClient(); responseCode = hclient.executeMethod(post); responseText = getResponseBodyAsString(post); } catch (IOException e) { throw new RuntimeException(e); } finally { post.releaseConnection(); } if (responseCode != HttpStatus.SC_OK) { throw new RuntimeException("HTTP Response code " + responseCode + ": " + responseText); } }
From source file:com.tribune.uiautomation.testscripts.Photo.java
private void setParameters(EntityEnclosingMethod method, String newNamespace, String newSlug) throws FileNotFoundException { StringPart namespacePart = newNamespace == null ? new StringPart(NAMESPACE_PARAM, namespace) : new StringPart(NAMESPACE_PARAM, newNamespace); StringPart slugPart = newSlug == null ? new StringPart(SLUG_PARAM, slug) : new StringPart(SLUG_PARAM, newSlug); // next two lines annoying work around for this bug: // https://github.com/rack/rack/issues/186 namespacePart.setContentType(null);//from w w w.j ava 2s .c o m slugPart.setContentType(null); if (file != null) { File f = new File(file); Part[] parts = { namespacePart, slugPart, new FilePart(FILE_PARAM, f, IMAGE_CONTENT_TYPE, FilePart.DEFAULT_CHARSET) }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); } else { Part[] parts = { namespacePart, slugPart }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); } }
From source file:is.idega.block.finance.business.sp.SPDataInsert.java
private void sendCreateClaimsRequest(BankFileManager bfm) { PostMethod filePost = new PostMethod(POST_METHOD); File file = new File(FILE_NAME); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); try {//from w w w. j a v a 2s . c om StringPart userPart = new StringPart("notendanafn", bfm.getUsername()); StringPart pwdPart = new StringPart("password", bfm.getPassword()); StringPart clubssnPart = new StringPart("KtFelags", bfm.getClaimantSSN()); FilePart filePart = new FilePart("Skra", file); Part[] parts = { userPart, pwdPart, clubssnPart, filePart }; 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) { System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString()); } else { System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status)); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } }
From source file:com.apatar.http.HttpNode.java
private HttpMethod sendPost(String url, KeyInsensitiveMap data) { try {/*from www . j a v a 2s .c o m*/ PostMethod post = new PostMethod(url); List<Record> recs = getTiForConnection(AbstractDataBaseNode.OUT_CONN_POINT_NAME).getSchemaTable() .getRecords(); Part[] parts = new Part[recs.size() - 1]; for (int i = 1; i < recs.size(); i++) { Record rec = recs.get(i); String fieldName = rec.getFieldName(); Object obj = data.get(fieldName, true); if (obj instanceof JdbcObject) { obj = ((JdbcObject) obj).getValue(); } if (rec.getType() == ERecordType.Binary) { parts[i - 1] = new FilePart(fieldName, ApplicationData.createFile("temp.temp", (byte[]) obj)); } else { parts[i - 1] = new StringPart(fieldName, obj.toString()); } } post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); return post; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }