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

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

Introduction

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

Prototype

public void addPart(Part paramPart) 

Source Link

Usage

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);//from   w  w  w  .j a v  a  2 s.  c o  m
    String response = method.getResponseBodyAsString();
    System.out.println(response);

    method.releaseConnection();
}

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

/**
 * Uploads a String containing eclipse launch events to the server.
 * /*from   w  w w  .  ja v  a2s .c  o  m*/
 * @param launchEvents
 *            the eclipse launch events to be uploaded
 * @param classAccount
 *            the class account of the user who generated the launch events
 * @param oneTimePassword
 *            the one-time password of the user who generated the launch
 *            events
 * @param url
 *            the URL of the server that will accept the launch events
 * @throws IOException
 * @throws HttpException
 */
private static int uploadMessages(String launchEvents, Properties props) throws IOException, HttpException {
    // Replace the path with /eclipse/LogEclipseLaunchEvent.
    if (!props.containsKey("submitURL")) {
        props.put("submitURL", "https://submit.cs.umd.edu:8443/eclipse/LogEclipseLaunchEvent");
    }
    String submitURL = props.getProperty("submitURL");
    Debug.print("submitURL: " + props.getProperty("submitURL"));
    int index = submitURL.indexOf("/eclipse/");
    if (index == -1) {
        Debug.print("Cannot find submitURL in .submitUser file");
        throw new IOException("Cannot find submitURL in .submitUser file");
    }
    submitURL = submitURL.substring(0, index) + "/eclipse/LogEclipseLaunchEvent";
    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) {
        if (submitURL.startsWith("https"))
            submitURL = "easy" + submitURL;
    }
    Debug.print("submitURL: " + submitURL);
    MultipartPostMethod filePost = new MultipartPostMethod(submitURL);

    // add filepart
    byte[] bytes = launchEvents.getBytes();
    filePost.addPart(new FilePart("eclipseLaunchEvent", new ByteArrayPartSource("eclipseLaunchEvent", bytes)));

    TurninProjectAction.addAllPropertiesButSubmitURL(props, filePost);

    filePost.addParameter("clientTime", Long.toString(System.currentTimeMillis()));

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(5000);

    int status = client.executeMethod(filePost);
    if (status != HttpStatus.SC_OK) {
        System.err.println(filePost.getResponseBodyAsString());
        throw new HttpException("status is: " + status);
    }
    return status;
}

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   w w  w .  j  a v a  2s .c o m*/
        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.submit.CommandLineSubmit.java

/**
 * @param p/*from w ww.  j av a  2 s . c o m*/
 * @param find
 * @param files
 * @param userProps
 * @return
 * @throws IOException
 * @throws FileNotFoundException
 */
public static MultipartPostMethod createFilePost(Properties p, FindAllFiles find, Collection<File> files,
        Properties userProps) throws IOException, FileNotFoundException {
    // ========================== assemble zip file in byte array
    // ==============================
    String loginName = userProps.getProperty("loginName");
    String classAccount = userProps.getProperty("classAccount");
    String from = classAccount;
    if (loginName != null && !loginName.equals(classAccount))
        from += "/" + loginName;
    System.out.println(" submitted by " + from);
    System.out.println();
    System.out.println("Submitting the following files");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(4096);
    byte[] buf = new byte[4096];
    ZipOutputStream zipfile = new ZipOutputStream(bytes);
    zipfile.setComment("zipfile for CommandLineTurnin, version " + VERSION);
    for (File resource : files) {
        if (resource.isDirectory())
            continue;
        String relativePath = resource.getCanonicalPath().substring(find.rootPathLength + 1);
        System.out.println(relativePath);
        ZipEntry entry = new ZipEntry(relativePath);
        entry.setTime(resource.lastModified());

        zipfile.putNextEntry(entry);
        InputStream in = new FileInputStream(resource);
        try {
            while (true) {
                int n = in.read(buf);
                if (n < 0)
                    break;
                zipfile.write(buf, 0, n);
            }
        } finally {
            in.close();
        }
        zipfile.closeEntry();

    } // for each file
    zipfile.close();

    MultipartPostMethod filePost = new MultipartPostMethod(p.getProperty("submitURL"));

    p.putAll(userProps);
    // add properties
    for (Map.Entry<?, ?> e : p.entrySet()) {
        String key = (String) e.getKey();
        String value = (String) e.getValue();
        if (!key.equals("submitURL"))
            filePost.addParameter(key, value);
    }
    filePost.addParameter("submitClientTool", "CommandLineTool");
    filePost.addParameter("submitClientVersion", VERSION);
    byte[] allInput = bytes.toByteArray();
    filePost.addPart(new FilePart("submittedFiles", new ByteArrayPartSource("submit.zip", allInput)));
    return filePost;
}

From source file:edu.umd.cs.buildServer.util.ServletAppender.java

@Override
protected void append(LoggingEvent event) {
    if (!APPEND_TO_SUBMIT_SERVER)
        return;/*from  w  w w .ja va  2s. com*/
    try {
        Throwable throwable = null;
        if (event.getThrowableInformation() != null) {
            String[] throwableStringRep = event.getThrowableStrRep();
            StringBuffer stackTrace = new StringBuffer();
            for (String stackTraceString : throwableStringRep) {
                stackTrace.append(stackTraceString);
            }
            throwable = new Throwable(stackTrace.toString());
        }

        LoggingEvent newLoggingEvent = new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(),
                event.getLevel(), getConfig().getHostname() + ": " + event.getMessage(), throwable);

        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);

        String logURL = config.getServletURL(SUBMIT_SERVER_HANDLEBUILDSERVERLOGMESSAGE_PATH);

        MultipartPostMethod post = new MultipartPostMethod(logURL);
        // add password

        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(sink);

        out.writeObject(newLoggingEvent);
        out.flush();
        // add serialized logging event object
        post.addPart(new FilePart("event", new ByteArrayPartSource("event.out", sink.toByteArray())));

        int status = client.executeMethod(post);
        if (status != HttpStatus.SC_OK) {
            throw new IOException("Couldn't contact server: " + status);
        }
    } catch (IOException e) {
        // TODO any way to log these without an infinite loop?
        System.err.println(e.getMessage());
        e.printStackTrace(System.err);
    }
}

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;/*from  ww  w. ja v  a  2 s. 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 reportTestResults(ProjectSubmission<?> projectSubmission)
        throws MissingConfigurationPropertyException {

    dumpOutcomes(projectSubmission);//ww  w  .  j  a  va2 s.com

    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.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 .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 = 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   w  ww .  jav a2  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 = 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

public void setPixels(long pixelsID, byte[] buf, boolean bigEndian) throws ImageServerException {
    MultipartPostMethod post = startCall();
    try {//  w  ww  .ja v  a2  s.c  om
        post.addParameter("Method", "SetPixels");
        post.addParameter("PixelsID", Long.toString(pixelsID));
        post.addParameter("UploadSize", Long.toString(buf.length));
        post.addParameter("BigEndian", bigEndian ? "1" : "0");
        post.addPart(new FilePart("Pixels", new ByteArrayPartSource("pixels", buf)));
        executeCall(post);

        return;
    } finally {
        finishCall(post);
    }
}