Example usage for org.apache.commons.httpclient.methods MultipartPostMethod MultipartPostMethod

List of usage examples for org.apache.commons.httpclient.methods MultipartPostMethod MultipartPostMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods MultipartPostMethod MultipartPostMethod.

Prototype

public MultipartPostMethod(String paramString) 

Source Link

Usage

From source file:edu.umd.cs.eclipse.courseProjectManager.TurninProjectAction.java

public void run(IAction action) {
    // TODO Refactor: Should the places where we raise a dialog and return
    // could throw an exception instead?
    String timeOfSubmission = "t" + System.currentTimeMillis();

    // Make sure we can get the workbench...
    IWorkbench workbench = PlatformUI.getWorkbench();
    if (workbench == null) {
        Dialogs.errorDialog(null, "Warning: project submission failed", "Could not submit project",
                "Internal error: Can't get workbench", IStatus.ERROR);
        return;/*w w  w .j  av a2s .  c o  m*/
    }
    // ...and the workbenchWindow
    IWorkbenchWindow wwin = workbench.getActiveWorkbenchWindow();
    if (wwin == null) {
        Dialogs.errorDialog(null, "Error submitting project", "Could not submit project",
                "Internal error: Can't get workbench window", IStatus.ERROR);
        return;
    }

    // Shell to use as parent of dialogs.
    Shell parent = wwin.getShell();
    // Sanity check.
    if (!(selection instanceof IStructuredSelection)) {
        Dialogs.errorDialog(parent, "Warning: Selection is Invalid",
                "Invalid turnin action: You have selected an object that is not a Project. Please select a Project and try again.",
                "Object selected is not a Project", IStatus.WARNING);
        return;
    }
    IStructuredSelection structured = (IStructuredSelection) selection;
    Object obj = structured.getFirstElement();
    Debug.print("Selection object is a " + obj.getClass().getName() + " @" + System.identityHashCode(obj));
    IProject project;
    if (obj instanceof IProject) {
        project = (IProject) obj;
    } else if (obj instanceof IProjectNature) {
        project = ((IProjectNature) obj).getProject();
    } else {
        Dialogs.errorDialog(null, "Warning: Selection is Invalid",
                "Invalid turnin action: You have selected an object that is not a Project. Please select a Project and try again.",
                "Object selected is not a Project", IStatus.WARNING);
        return;
    }
    Debug.print("Got the IProject for the turnin action @" + System.identityHashCode(project));

    // ================================= save dirty editors
    // ========================================
    // save dirty editors
    try {
        if (!saveDirtyEditors(project, workbench)) {
            Dialogs.errorDialog(parent, "Submit not performed",
                    "Projects cannot be submitted unless all open files are saved",
                    "Unsaved files prevent submission", IStatus.WARNING);
            return;
        }
    } catch (CoreException e) {
        Dialogs.errorDialog(parent, "Submit not performed",
                "Could not turn on cvs management for all project files", e);
        return;
    }

    // ========================= Add all non-ignored files in the project
    // =========================
    IResource[] files;
    try {
        Set<IResource> resourceSet = getProjectResources(project);
        ArrayList<IFile> addedFiles = new ArrayList<IFile>();
        for (Iterator<IResource> iter = resourceSet.iterator(); iter.hasNext();) {
            IResource resource = iter.next();
            if (resource instanceof IFile) {
                IFile file = (IFile) resource;
                if (!AutoCVSPlugin.isCVSIgnored(file) && !AutoCVSPlugin.isCVSManaged(file)) {
                    addedFiles.add(file);
                }
            }
        }
        files = (IResource[]) addedFiles.toArray(new IResource[addedFiles.size()]);
    } catch (CoreException e) {
        Dialogs.errorDialog(parent, "Submit not performed",
                "Could not perform submit; unable to find non-ignored resources", e);
        return;
        // TODO what to do here?
    }

    // ================================= perform CVS commit
    // ========================================
    // TODO Somehow move this into the previous try block
    // This forces add/commit operations when AutoSync was shut off
    // Would it just be easier to enable autoSync and then trigger
    // a resource changed delta, since this method appears to enable
    // autoSync anyway?
    //
    String cvsStatus = "Not performed";
    try {
        cvsStatus = forceCommit(project, files);
    } catch (Exception e) {
        Dialogs.errorDialog(parent,
                "CVS commit not performed as part of submission due to unexpected exception",
                e.getClass().getName() + " " + e.getMessage(), e);
    }

    // ================================= perform CVS tag
    // ========================================
    try {
        CVSOperations.tagProject(project, timeOfSubmission, CVSOperations.SYNC);
    } catch (Exception e) {
        AutoCVSPlugin.getPlugin().getEventLog()
                .logError("Error tagging submission; submission via the web unlikely to work", e);
    }

    // ================================= find properties
    // ========================================
    // find the .submitProject file
    IResource submitProjectFile = project.findMember(AutoCVSPlugin.SUBMITPROJECT);
    if (submitProjectFile == null) {
        Dialogs.errorDialog(parent, "Warning: Project submission not enabled", "Submission is not enabled",
                "There is no " + AutoCVSPlugin.SUBMITPROJECT + " file for the project", IStatus.ERROR);
        return;
    }
    // Get the properties from the .submit file, and the .submitUser file,
    // if it exists
    // or can be fetched from the server
    Properties allSubmissionProps = null;
    try {
        allSubmissionProps = getAllProperties(timeOfSubmission, parent, project, submitProjectFile);
    } catch (IOException e) {
        String message = "IOException finding " + AutoCVSPlugin.SUBMITPROJECT + " and "
                + AutoCVSPlugin.SUBMITUSER + " files; " + cvsStatus;
        AutoCVSPlugin.getPlugin().getEventLog().logError(message, e);
        Dialogs.errorDialog(parent, "Submission failed", message, e.getMessage(), IStatus.ERROR);
        Debug.print("IOException: " + e);
        return;
    } catch (CoreException e) {
        String message = "IOException finding " + AutoCVSPlugin.SUBMITPROJECT + " and "
                + AutoCVSPlugin.SUBMITUSER + " files; " + cvsStatus;
        AutoCVSPlugin.getPlugin().getEventLog().logError(message, e);
        Dialogs.errorDialog(parent, "Submission failed", message, e.getMessage(), IStatus.ERROR);
        Debug.print("CoreException: " + e);
        return;
    }

    //
    // THE ACTUAL SUBMIT HAPPENS HERE
    //
    try {
        // ============================== find files to submit
        // ====================================
        Collection<IFile> cvsFiles = findFilesForSubmission(project);

        // ========================== assemble zip file in byte array
        // ==============================

        ByteArrayOutputStream bytes = new ByteArrayOutputStream(4096);
        ZipOutputStream zipfile = new ZipOutputStream(bytes);
        zipfile.setComment("zipfile for submission created by CourseProjectManager version "
                + AutoCVSPlugin.getPlugin().getVersion());

        try {
            byte[] buf = new byte[4096];
            for (IFile file : cvsFiles) {
                if (!file.exists()) {
                    Debug.print("Resource " + file.getName() + " being ignored because it doesn't exist");
                    continue;
                }

                ZipEntry entry = new ZipEntry(file.getProjectRelativePath().toString());
                entry.setTime(file.getModificationStamp());

                zipfile.putNextEntry(entry);
                // Copy file data to zip file
                InputStream in = file.getContents();

                try {
                    while (true) {
                        int n = in.read(buf);
                        if (n < 0)
                            break;
                        zipfile.write(buf, 0, n);
                    }
                } finally {
                    in.close();
                }
                zipfile.closeEntry();
            }
        } catch (IOException e1) {
            Dialogs.errorDialog(parent, "Warning: Project submission failed",
                    "Unable to zip files for submission\n" + cvsStatus, e1);
            return;
        } finally {
            if (zipfile != null)
                zipfile.close();
        }

        // ============================== Post to submit server
        // ====================================
        String version = System.getProperties().getProperty("java.runtime.version");
        boolean useEasyHttps = version.startsWith("1.3") || version.startsWith("1.2")
                || version.startsWith("1.4.0") || version.startsWith("1.4.1")
                || version.startsWith("1.4.2_0") && version.charAt(7) < '5';
        if (useEasyHttps) {
            String submitURL = allSubmissionProps.getProperty("submitURL");
            if (submitURL.startsWith("https"))
                submitURL = "easy" + submitURL;
            allSubmissionProps.setProperty("submitURL", submitURL);
        }
        // prepare multipart post method
        MultipartPostMethod filePost = new MultipartPostMethod(allSubmissionProps.getProperty("submitURL"));

        // add properties
        addAllPropertiesButSubmitURL(allSubmissionProps, filePost);

        // add filepart
        byte[] allInput = bytes.toByteArray();
        filePost.addPart(new FilePart("submittedFiles", new ByteArrayPartSource("submit.zip", allInput)));

        // prepare httpclient
        HttpClient client = new HttpClient();
        client.setConnectionTimeout(5000);
        int status = client.executeMethod(filePost);

        // Piggy-back uploading the launch events onto submitting.
        EclipseLaunchEventLog.postEventLogToServer(project);

        if (status == HttpStatus.SC_OK) {
            Dialogs.okDialog(parent, "Project submission successful",
                    "Project " + allSubmissionProps.getProperty("projectNumber")
                            + " was submitted successfully\n" + filePost.getResponseBodyAsString());

        } else {
            Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submission failed",
                    filePost.getStatusText() + "\n " + cvsStatus, IStatus.CANCEL);
            AutoCVSPlugin.getPlugin().getEventLog().logMessage(filePost.getResponseBodyAsString());
        }

    } catch (CoreException e) {
        Dialogs.errorDialog(parent, "Warning: Project submission failed",
                "Project submissions via https failed\n" + cvsStatus, e);
    } catch (HttpConnection.ConnectionTimeoutException e) {
        Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submissions failed",
                "Connection timeout while trying to connect to submit server\n " + cvsStatus, IStatus.ERROR);
    } catch (IOException e) {
        Dialogs.errorDialog(parent, "Warning: Project submission failed",
                "Project submissions failed\n " + cvsStatus, e);
    }
}

From source file:edu.umd.cs.buildServer.BuildServerDaemon.java

@Override
protected void reportBuildServerDeath(int submissionPK, int testSetupPK, long lastModified, String kind,
        String load) {//w  ww . j  a  v a  2s  .  com

    MultipartPostMethod method = new MultipartPostMethod(getReportBuildServerDeathURL());

    method.addParameter("submissionPK", Integer.toString(submissionPK));
    method.addParameter("testSetupPK", Integer.toString(testSetupPK));

    addCommonParameters(method);
    method.addParameter("kind", kind);
    method.addParameter("lastModified", Long.toString(lastModified));

    try {
        int statusCode = getClient().executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.out.println("Error eporting build server death for submissionPK " + submissionPK
                    + ": status " + statusCode + ": " + method.getStatusText());
            System.out.println(method.getResponseBodyAsString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:edu.umd.cs.buildServer.BuildServerDaemon.java

@Override
protected void reportTestResults(ProjectSubmission<?> projectSubmission)
        throws MissingConfigurationPropertyException {

    dumpOutcomes(projectSubmission);// w w w .  j av a 2s.  c  o 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: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 {/*from   ww  w.j ava  2s  .  c o  m*/
        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);//  w ww .ja v  a2  s .  co 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  w  w  . ja v  a2 s  .  co  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./*  w w w  .  j  av a  2s.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 = 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();//w  ww .  j  a  v a  2  s.com

    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  w w  . j a  v  a  2s.  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 = 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

/**
 * Creates the HTTP method object for this instance to use.  Can
 * be overridden if a class other than the default should be used.
 *///from  ww w  .  j  av  a2  s .  c o m
protected MultipartPostMethod createPostMethod() {
    MultipartPostMethod post = new MultipartPostMethod(url);
    post.setUseExpectHeader(false);
    return post;
}