List of usage examples for org.apache.commons.httpclient.methods MultipartPostMethod addParameter
public void addParameter(String paramString1, String paramString2)
From source file:edu.umd.cs.buildServer.BuildServerDaemon.java
@Override protected void reportTestResults(ProjectSubmission<?> projectSubmission) throws MissingConfigurationPropertyException { dumpOutcomes(projectSubmission);// ww w. j a va 2 s. co m 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:edu.umd.cs.buildServer.BuildServerDaemon.java
@Override protected ProjectSubmission<?> getProjectSubmission() throws MissingConfigurationPropertyException, IOException { try {/*from w ww.jav a 2 s.c o m*/ String url = getRequestSubmissionURL(); MultipartPostMethod method = new MultipartPostMethod(url); String supportedCoursePKList = getBuildServerConfiguration().getSupportedCourses(); String specificProjectNum = getConfig().getOptionalProperty(DEBUG_SPECIFIC_PROJECT); String specificCourse = getConfig().getOptionalProperty(DEBUG_SPECIFIC_COURSE); if (specificCourse != null) supportedCoursePKList = specificCourse; String specificSubmission = getConfig().getOptionalProperty(DEBUG_SPECIFIC_SUBMISSION); String specificTestSetup = getConfig().getOptionalProperty(DEBUG_SPECIFIC_TESTSETUP); if (specificSubmission != null) { method.addParameter("submissionPK", specificSubmission); if (!isQuiet()) System.out.printf("Requesting submissionPK %s%n", specificSubmission); } if (specificTestSetup != null) { method.addParameter("testSetupPK", specificTestSetup); if (!isQuiet()) System.out.printf("Requesting testSetupPK %s%n", specificTestSetup); } if (specificProjectNum != null) { method.addParameter("projectNumber", specificProjectNum); } addCommonParameters(method); BuildServer.printURI(getLog(), method); int responseCode = client.executeMethod(method); if (responseCode != HttpStatus.SC_OK) { if (responseCode == HttpStatus.SC_SERVICE_UNAVAILABLE) { getLog().trace("Server returned 503 (no work)"); } else { String msg = "HTTP server returned non-OK response: " + responseCode + ": " + method.getStatusText(); getLog().error(msg); getLog().error(" for URI: " + method.getURI()); getLog().error("Full error message: " + method.getResponseBodyAsString()); if (responseCode == HttpStatus.SC_BAD_REQUEST) { if (!isQuiet()) { System.err.println(msg); System.out.println(msg); } System.exit(1); } } return null; } getLog().debug("content-type: " + method.getResponseHeader("Content-type")); getLog().debug("content-length: " + method.getResponseHeader("content-length")); // Ensure we have a submission PK. String submissionPK = getRequiredHeaderValue(method, HttpHeaders.HTTP_SUBMISSION_PK_HEADER); if (submissionPK == null) { if (specificSubmission != null) getLog().error("Server did not return submission " + specificSubmission); return null; } // Ensure we have a project PK. String testSetupPK = specificTestSetup != null ? specificTestSetup : getTestSetupPK(method); if (testSetupPK == null) return null; // This is a boolean value specifying whether the project jar file // is NEW, meaning that it needs to be tested against the // canonical project solution. The build server doesn't need // to do anything with this value except pass it back to // the submit server when reporting test outcomes. String isNewTestSetup = getIsNewTestSetup(method); if (isNewTestSetup == null) return null; // Opaque boolean value representing whether this was a // "background retest". // The BuildServer doesn't need to do anything with this except pass it // back to the SubmitServer. String isBackgroundRetest = getRequiredHeaderValue(method, HttpHeaders.HTTP_BACKGROUND_RETEST); if (isBackgroundRetest == null) isBackgroundRetest = "no"; ServletAppender servletAppender = (ServletAppender) getLog().getAppender("servletAppender"); if (isBackgroundRetest.equals("yes")) servletAppender.setThreshold(Level.FATAL); else servletAppender.setThreshold(Level.INFO); String kind = method.getResponseHeader(HttpHeaders.HTTP_KIND_HEADER).getValue(); String logMsg = "Got submission " + submissionPK + ", testSetup " + testSetupPK + ", kind: " + kind; getLog().info(logMsg); ProjectSubmission<?> projectSubmission = new ProjectSubmission<TestProperties>( getBuildServerConfiguration(), getLog(), submissionPK, testSetupPK, isNewTestSetup, isBackgroundRetest, kind); projectSubmission.setMethod(method); getCurrentFile().delete(); writeToCurrentFile(submissionPK + "\n" + testSetupPK + "\n" + kind + "\n" + SystemInfo.getSystemLoad() + "\n" + logMsg); return projectSubmission; } catch (ConnectException e) { getLog().warn("Unable to connect to " + getBuildServerConfiguration().getSubmitServerURL()); return null; } }
From source file:org.apache.commons.httpclient.demo.httpclientfileupload.java
public static void main(String[] args) { MultipartPostMethod filePost = new MultipartPostMethod(targetURL); File targetFilePath = new File("htmlparser.zip"); try {/* w w w . ja v a2 s . c om*/ filePost.addParameter("fileName", targetFilePath); } catch (FileNotFoundException ex) { ex.printStackTrace(); } HttpClient client = new HttpClient(); //, client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); // try { // int status = client.executeMethod(filePost); // } catch (IOException ex1) { // ex1.printStackTrace(); // } }
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);/* www .ja v a2 s.c om*/ // 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); }//ww w . j a va2 s .c o m // 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.//from w w w .jav a2s. com * @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.junitee.testngee.ant.AntTask.java
public void execute() throws BuildException { validateOptions();/*from www . j av a2s .c o m*/ HttpClient client = new HttpClient(); MultipartPostMethod method = new MultipartPostMethod(runnerUrl); if (null != m_isJUnit) { if (m_isJUnit.booleanValue()) { method.addParameter("isJunit", "true"); } } // if (null != m_verbose) { // cmd.createArgument().setValue(TestNGCommandLineArgs.LOG); // cmd.createArgument().setValue(m_verbose.toString()); // } if ((null != m_outputDir)) { if (!m_outputDir.exists()) { m_outputDir.mkdirs(); } if (!m_outputDir.isDirectory()) { throw new BuildException("Output directory is not a directory: " + m_outputDir); } } if ((null != m_testjar)) { method.addParameter("testjar", m_testjar.getName()); } if (null != m_groups) { method.addParameter("groups", m_groups); } if (m_classFilesets.size() > 0) { for (String file : fileset(m_classFilesets)) { method.addParameter("classfile", file); } } if (m_xmlFilesets.size() > 0) { for (String file : fileset(m_xmlFilesets)) { try { method.addParameter("file", new File(file)); } catch (FileNotFoundException e) { throw new BuildException(e); } } } int exitValue = -1; try { client.executeMethod(method); InputStream in = method.getResponseBodyAsStream(); ZipInputStream zipIn = new ZipInputStream(in); ZipEntry zipEntry; while ((zipEntry = zipIn.getNextEntry()) != null) { byte[] buffer = new byte[4096]; File file = new File(m_outputDir, zipEntry.getName()); file.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(file); int r; while ((r = zipIn.read(buffer)) != -1) { out.write(buffer, 0, r); } out.close(); zipIn.closeEntry(); } zipIn.close(); exitValue = 0; } catch (IOException e) { throw new BuildException(e); } actOnResult(exitValue); }
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 w ww .j a va2 s . c om*/ * * @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 executeCall(MultipartPostMethod post) throws ImageServerException { int status = 0; try {//from w w w .j av a 2 s .c om post.addParameter("SessionKey", sessionKey); status = client.executeMethod(post); } catch (IOException e) { e.printStackTrace(); throw new ImageServerException(e.getMessage()); } if (status != HttpStatus.SC_OK) { throw new ImageServerException(HttpStatus.getStatusText(status)); } }
From source file:org.openmicroscopy.is.HttpImageServer.java
/** * Helper method -- adds all of the parameters specified by the * given {@link CompositingSettings} to the parameters of the * given HTTP post.//from w w w . j ava2s.co m */ private void addCompositingSettings(MultipartPostMethod post, CompositingSettings settings) { post.addParameter("theZ", Integer.toString(settings.getTheZ())); post.addParameter("theT", Integer.toString(settings.getTheT())); post.addParameter("LevelBasis", settings.getLevelBasisSpec()); if (settings.isResized()) post.addParameter("Size", settings.getSizeSpec()); if (settings.isGrayChannelOn()) post.addParameter("GrayChannel", settings.getGrayChannelSpec()); if (settings.isRedChannelOn()) post.addParameter("RedChannel", settings.getRedChannelSpec()); if (settings.isGreenChannelOn()) post.addParameter("GreenChannel", settings.getGreenChannelSpec()); if (settings.isBlueChannelOn()) post.addParameter("BlueChannel", settings.getBlueChannelSpec()); }