List of usage examples for org.apache.commons.httpclient.methods MultipartPostMethod releaseConnection
@Override public void releaseConnection()
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 ww . ja v a 2 s . c o m String response = method.getResponseBodyAsString(); System.out.println(response); method.releaseConnection(); }
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 {/*from ww w . j a v a 2 s.c om*/ 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:edu.umd.cs.buildServer.BuildServerDaemon.java
@Override protected void downloadProjectJarFile(ProjectSubmission<?> projectSubmission) throws MissingConfigurationPropertyException, HttpException, IOException, BuilderException { // FIXME: We should cache these MultipartPostMethod method = new MultipartPostMethod(getTestSetupURL()); method.addParameter("testSetupPK", projectSubmission.getTestSetupPK()); method.addParameter("projectJarfilePK", projectSubmission.getTestSetupPK()); String supportedCourses = getBuildServerConfiguration().getSupportedCourses(); method.addParameter("courses", supportedCourses); BuildServer.printURI(getLog(), method); try {/*from ww w. j a v a 2s. c o m*/ int responseCode = client.executeMethod(method); if (responseCode != HttpStatus.SC_OK) { throw new BuilderException("Could not download project test setup from " + getTestSetupURL() + ": " + responseCode + ": " + method.getStatusText()); } getLog().trace("Downloading test setup file"); IO.download(projectSubmission.getTestSetup(), method); // We're passing the project_jarfile_pk so we don't need to read it // from // the headers // wait for a while in case the files have not "settled" // TODO: Verify that this is still necessary; should be OK unless // run on NFS pause(10); getLog().trace("Done."); } finally { method.releaseConnection(); } }
From source file:edu.umd.cs.buildServer.BuildServerDaemon.java
@Override protected void reportTestResults(ProjectSubmission<?> projectSubmission) throws MissingConfigurationPropertyException { dumpOutcomes(projectSubmission);//from ww w . j ava 2 s .c om getLog().info("Test outcome collection for " + projectSubmission.getSubmissionPK() + " for test setup " + projectSubmission.getTestSetupPK() + " contains " + projectSubmission.getTestOutcomeCollection().size() + " entries"); // Format the test outcome collection as bytes in memory ByteArrayOutputStream sink = new ByteArrayOutputStream(); ObjectOutputStream out = null; try { out = new ObjectOutputStream(sink); } catch (IOException ignore) { getLog().error("IOException creating ObjectOutputStream"); } TestOutcomeCollection c = projectSubmission.getTestOutcomeCollection(); // Print some info about the size of the collection getLog().info("Got TestOutcomeCollection; size: " + c.size()); for (TestOutcome to : c.getAllOutcomes()) { // Truncate to avoid OutOfMemories to.truncateLongTestResult(); // Most important size to print is the longResult len - it // can be really long int length = to.getLongTestResult().length(); getLog().info(" Outcome " + to.getTestNumber() + ": " + to.getTestName() + " = " + to.getOutcome() + (length > 0 ? ", longResult len: " + length : "")); } try { c.write(out); } catch (IOException ignore) { getLog().error("IOException writing to ObjectOutputStream", ignore); } catch (Error e) { // Can happen if the long test output is really long; we // truncate down to 64K (also the limit imposed by the // MySQL 'text' type) in order to avoid this, but we should // note it. getLog().error("While writing, caught Error", e); getLog().error("Rethrowing..."); throw (e); } try { out.close(); } catch (IOException ignore) { getLog().error("IOException closing ObjectOutputStream"); } byte[] testOutcomeData = sink.toByteArray(); String subPK = projectSubmission.getSubmissionPK(); String jarfilePK = projectSubmission.getTestSetupPK(); int outcomes = projectSubmission.getTestOutcomeCollection().size(); getLog().info("Test data for submission " + subPK + " for test setup " + jarfilePK + " contains " + testOutcomeData.length + " bytes from " + outcomes + " test outcomes"); String hostname = getBuildServerConfiguration().getHostname(); MultipartPostMethod method = new MultipartPostMethod(getReportTestResultsURL()); method.addParameter("submissionPK", projectSubmission.getSubmissionPK()); method.addParameter("testSetupPK", projectSubmission.getTestSetupPK()); method.addParameter("projectJarfilePK", projectSubmission.getTestSetupPK()); method.addParameter("newTestSetup", projectSubmission.getIsNewTestSetup()); method.addParameter("newProjectJarfile", projectSubmission.getIsNewTestSetup()); method.addParameter("isBackgroundRetest", projectSubmission.getIsBackgroundRetest()); method.addParameter("testMachine", hostname); method.addParameter("testDurationsMillis", Long.toString(projectSubmission.getTestDurationMillis())); addCommonParameters(method); method.addParameter("kind", projectSubmission.getKind()); // CodeMetrics if (projectSubmission.getCodeMetrics() != null) { getLog().debug("Code Metrics: " + projectSubmission.getCodeMetrics()); projectSubmission.getCodeMetrics().mapIntoHttpHeader(method); } method.addPart(new FilePart("testResults", new ByteArrayPartSource("testresults.out", testOutcomeData))); printURI(method); try { getLog().debug("Submitting test results for " + projectSubmission.getSubmissionPK() + "..."); int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) getLog().debug("Done submitting test results for submissionPK " + projectSubmission.getSubmissionPK() + "; statusCode=" + statusCode); else { getLog().error("Error submitting test results for submissionPK " + projectSubmission.getSubmissionPK() + ": " + statusCode + ": " + method.getStatusText()); getLog().error(method.getResponseBodyAsString()); // TODO: Should we do anything else in case of an error? } } catch (HttpException e) { getLog().error("Internal error: HttpException submitting test results", e); return; } catch (IOException e) { getLog().error("Internal error: IOException submitting test results", e); return; } finally { getLog().trace("Releasing connection..."); method.releaseConnection(); getLog().trace("Done releasing connection"); } }
From source file:org.apache.commons.httpclient.demo.HttpMultiPartFileUpload.java
public static void main(String[] args) throws IOException { HttpClient client = new HttpClient(); MultipartPostMethod mPost = new MultipartPostMethod(url); client.setConnectionTimeout(8000);/*from w w w. j ava 2 s. c o m*/ // Send any XML file as the body of the POST request File f1 = new File("students.xml"); File f2 = new File("academy.xml"); File f3 = new File("academyRules.xml"); System.out.println("File1 Length = " + f1.length()); System.out.println("File2 Length = " + f2.length()); System.out.println("File3 Length = " + f3.length()); mPost.addParameter(f1.getName(), f1); mPost.addParameter(f2.getName(), f2); mPost.addParameter(f3.getName(), f3); //int statusCode1 = client.executeMethod(mPost); System.out.println("statusLine>>>" + mPost.getStatusLine()); // String response = new String(mPost.getResponseBodyAsString().getBytes("8859_1")); // System.out.println("==================================="); System.out.println(":"); System.out.println(response); System.out.println("==================================="); mPost.releaseConnection(); }
From source file:org.bibsonomy.rest.client.worker.impl.PostWorker.java
public Reader perform(final String url, final File file) throws ErrorPerformingRequestException { LOGGER.debug("POST Multipart: URL: " + url); if (this.proxyHost != null) { this.getHttpClient().getHostConfiguration().setProxy(this.proxyHost, this.proxyPort); }/* w ww .j a va 2s. com*/ // TODO: remove deprecated method final MultipartPostMethod post = new MultipartPostMethod(url); post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); post.addRequestHeader(HeaderUtils.HEADER_AUTHORIZATION, HeaderUtils.encodeForAuthorization(this.username, this.apiKey)); post.addRequestHeader("Content-Type", "multipart/form-data"); try { post.addParameter("file", file); this.getHttpClient().getHttpConnectionManager().getParams().setConnectionTimeout(5000); this.httpResult = this.getHttpClient().executeMethod(post); LOGGER.debug("HTTP result: " + this.httpResult); LOGGER.debug("response:\n" + post.getResponseBodyAsString()); LOGGER.debug("==================================================="); return new StringReader(post.getResponseBodyAsString()); } catch (final IOException e) { LOGGER.debug(e.getMessage(), e); throw new ErrorPerformingRequestException(e); } finally { post.releaseConnection(); } }
From source file:org.camera.service.CAMERARESTService.java
/** * File & regular parameters are passed as two separate lists and they are treated * little differently. If flPairList is not null or empty then this method uses Part * Object else no.// ww w.j a v a 2 s. co m * @param pmPairList List of the name and value parameters that user has provided * @param flPairList List of the name and value (full file path)of file parameters. * It is essentially a list of files that user wishes to attach. * @return the results after executing the Post service. */ public String executePostMethod(List<NameValuePair> pmPairList, List<NameValuePair> flPairList, String serSiteURL) throws IllegalActionException { if (_debugging) { _debug("I AM IN POST METHOD"); } log.debug("I AM IN POST METHOD"); String postAddress = serSiteURL; HttpClient client = new HttpClient(); MultipartPostMethod method = new MultipartPostMethod(postAddress); List<NameValuePair> fullNameValueList = pmPairList; if (flPairList != null && flPairList.size() > 0) { fullNameValueList.addAll(flPairList); int totalSize = fullNameValueList.size(); Part[] parts = new Part[totalSize]; try { for (int i = 0; i < parts.length; i++) { String nm = fullNameValueList.get(i).getName(); String vl = fullNameValueList.get(i).getValue(); if (i > totalSize - flPairList.size() - 1) { System.out.println("FILE NAME: " + nm); File file = getFileObject(vl); System.out.println("FILE NAME: " + file.getName()); parts[i] = new FilePart(nm, file); method.addPart(parts[i]); System.out.println("PARTS: " + i + " " + parts[i].getName()); System.out.println("file Name: " + vl); } else { System.out.println("PARAMETER NAME: " + nm); System.out.println("PARAMETER Value: " + vl); parts[i] = new StringPart(nm, vl); method.addPart(parts[i]); } if (_debugging) { _debug("Value of i: " + i); } } } catch (FileNotFoundException fnfe) { if (_debugging) { _debug("File Not Found Exception: " + fnfe.getMessage()); } fnfe.printStackTrace(); throw new IllegalActionException("File Not Found: " + fnfe.getMessage()); } } else { for (NameValuePair nmPair : fullNameValueList) { method.addParameter(nmPair.getName(), nmPair.getValue()); System.out.println("Name: " + nmPair.getName() + " Value:" + nmPair.getValue()); } } InputStream rstream = null; StringBuilder results = new StringBuilder(); try { messageBldr = new StringBuilder(); messageBldr.append("In excutePostMethod, communicating with service: ").append(serSiteURL) .append(" STATUS Code: "); int statusCode = client.executeMethod(method); messageBldr.append(statusCode); log.debug("DEBUG: " + messageBldr.toString()); System.out.println(messageBldr.toString()); rstream = method.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(rstream)); log.debug("BEFORE WHILE LOOP"); String s; while ((s = br.readLine()) != null) { results.append(s).append(ServiceUtils.LINESEP); } } catch (HttpException httpe) { if (_debugging) { _debug("Fatal protocol violation: " + httpe.getMessage()); } httpe.printStackTrace(); // return "Protocol Violation"; throw new IllegalActionException("Fatal protocol violation: " + httpe.getMessage()); } catch (ConnectException conExp) { if (_debugging) { _debug("Perhaps service not reachable: " + conExp.getMessage()); } conExp.printStackTrace(); throw new IllegalActionException("Perhaps service not reachable: " + conExp.getMessage()); // return "Perhaps service not reachable"; } catch (IOException ioe) { if (_debugging) { _debug("Fatal transport error: " + ioe.getMessage()); } ioe.printStackTrace(); // return "IOException: Perhaps could not connect to the service."; throw new IllegalActionException("Fatal transport error: " + ioe.getMessage()); } catch (Exception e) { if (_debugging) { _debug("Unknown error: " + e.getMessage()); } e.printStackTrace(); // return "Exception: Unknown type error"; throw new IllegalActionException("Error: " + e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } return results.toString(); }
From source file:org.kepler.actor.rest.RESTService.java
/** * File & regular parameters are passed as two separate lists and they are * treated little differently. If flPairList is not null or empty then this * method uses Part Object else no./*from ww w .j a v a 2 s . c o m*/ * * @param pmPairList * List of the name and value parameters that user has provided * @param flPairList * List of the name and value (full file path)of file parameters. * It is essentially a list of files that user wishes to attach. * @return the results after executing the Post service. */ public String executePostMethod(List<NameValuePair> pmPairList, List<NameValuePair> flPairList, String serSiteURL) throws IllegalActionException { if (_debugging) { _debug("I AM IN POST METHOD"); } //log.debug("I AM IN POST METHOD"); String postAddress = serSiteURL; HttpClient client = new HttpClient(); MultipartPostMethod method = new MultipartPostMethod(postAddress); List<NameValuePair> fullNameValueList = getCombinedPairList(pmPairList); if (flPairList != null && flPairList.size() > 0) { fullNameValueList.addAll(flPairList); int totalSize = fullNameValueList.size(); Part[] parts = new Part[totalSize]; try { for (int i = 0; i < parts.length; i++) { String nm = fullNameValueList.get(i).getName(); String vl = fullNameValueList.get(i).getValue(); if (i > totalSize - flPairList.size() - 1) { System.out.println("FILE NAME: " + nm); File file = getFileObject(vl); // System.out.println("FILE NAME: " + file.getName()); parts[i] = new FilePart(nm, file); method.addPart(parts[i]); System.out.println("PARTS: " + i + " " + parts[i].getName()); System.out.println("file Name: " + vl); } else { System.out.println("PARAMETER NAME: " + nm); System.out.println("PARAMETER Value: " + vl); parts[i] = new StringPart(nm, vl); method.addPart(parts[i]); } if (_debugging) { _debug("Value of i: " + i); } } } catch (FileNotFoundException fnfe) { if (_debugging) { _debug("File Not Exception: " + fnfe.getMessage()); } fnfe.printStackTrace(); throw new IllegalActionException(this, fnfe, "File Not Found: " + fnfe.getMessage()); } } else { for (NameValuePair nmPair : fullNameValueList) { method.addParameter(nmPair.getName(), nmPair.getValue()); } } InputStream rstream = null; StringBuilder results = new StringBuilder(); try { messageBldr = new StringBuilder(); messageBldr.append("In excutePostMethod, communicating with service: ").append(serSiteURL) .append(" STATUS Code: "); int statusCode = client.executeMethod(method); messageBldr.append(statusCode); log.debug("DEBUG: " + messageBldr.toString()); System.out.println(messageBldr.toString()); // if(statusCode == 201){ // System.out.println("Succuess -- " + statusCode + // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString()); // }else{ // System.out.println("Failure -- " + statusCode + // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString()); // } rstream = method.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(rstream)); log.debug("BEFORE WHILE LOOP"); String s; while ((s = br.readLine()) != null) { results.append(s).append(ServiceUtils.LINESEP); } } catch (HttpException e) { if (_debugging) { _debug("Fatal protocol violation: " + e.getMessage()); } e.printStackTrace(); return "Protocol Violation"; } catch (ConnectException conExp) { if (_debugging) { _debug("Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage()); } conExp.printStackTrace(); throw new IllegalActionException(this, conExp, "Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage()); } catch (IOException ioe) { if (_debugging) { _debug("Fatal transport error: " + ioe.getMessage()); } // System.err.println("Fatal transport error: " + e.getMessage()); ioe.printStackTrace(); throw new IllegalActionException(this, ioe, "IOException: Perhaps could not" + " connect to the service '" + serSiteURL + "'. " + ioe.getMessage()); } catch (Exception e) { if (_debugging) { _debug("Error: " + e.getMessage()); } // System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); throw new IllegalActionException(this, e, "Error: " + e.getMessage()); } finally { // Release the connection. method.releaseConnection(); client = null; // close InputStream; if (rstream != null) try { rstream.close(); } catch (IOException e) { e.printStackTrace(); throw new IllegalActionException(this, e, "InputStream Close Exception: " + e.getMessage()); } } return results.toString(); }
From source file:org.openmicroscopy.is.HttpImageServer.java
private void finishCall(MultipartPostMethod post) { post.releaseConnection(); }