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

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

Introduction

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

Prototype

@Override
public String getResponseBodyAsString() throws IOException 

Source Link

Document

Returns the response body of the HTTP method, if any, as a String .

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  ww .j a v a2s.co  m
    String response = method.getResponseBodyAsString();
    System.out.println(response);

    method.releaseConnection();
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

public static void main(String[] args) {
    try {/*from ww  w  .j ava  2s .c  o  m*/
        Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        File home = args.length > 0 ? new File(args[0]) : new File(".");

        Protocol.registerProtocol("easyhttps", easyhttps);
        File submitFile = new File(home, ".submit");
        File submitUserFile = new File(home, ".submitUser");
        File submitIgnoreFile = new File(home, ".submitIgnore");
        File cvsIgnoreFile = new File(home, ".cvsignore");

        if (!submitFile.canRead()) {
            System.out.println("Must perform submit from a directory containing a \".submit\" file");
            System.out.println("No such file found at " + submitFile.getCanonicalPath());
            System.exit(1);
        }

        Properties p = new Properties();
        p.load(new FileInputStream(submitFile));
        String submitURL = p.getProperty("submitURL");
        if (submitURL == null) {
            System.out.println(".submit file does not contain a submitURL");
            System.exit(1);
        }
        String courseName = p.getProperty("courseName");
        String courseKey = p.getProperty("courseKey");
        String semester = p.getProperty("semester");
        String projectNumber = p.getProperty("projectNumber");
        String authenticationType = p.getProperty("authentication.type");
        String baseURL = p.getProperty("baseURL");

        System.out.println("Submitting contents of " + home.getCanonicalPath());
        System.out.println(" as project " + projectNumber + " for course " + courseName);
        FilesToIgnore ignorePatterns = new FilesToIgnore();
        addIgnoredPatternsFromFile(cvsIgnoreFile, ignorePatterns);
        addIgnoredPatternsFromFile(submitIgnoreFile, ignorePatterns);

        FindAllFiles find = new FindAllFiles(home, ignorePatterns.getPattern());
        Collection<File> files = find.getAllFiles();

        boolean createdSubmitUser = false;
        Properties userProps = new Properties();
        if (submitUserFile.canRead()) {
            userProps.load(new FileInputStream(submitUserFile));
        }
        if (userProps.getProperty("cvsAccount") == null && userProps.getProperty("classAccount") == null
                || userProps.getProperty("oneTimePassword") == null) {
            System.out.println();
            System.out.println(
                    "We need to authenticate you and create a .submitUser file so you can submit your project");

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            createdSubmitUser = true;
            userProps.load(new FileInputStream(submitUserFile));
        }

        MultipartPostMethod filePost = createFilePost(p, find, files, userProps);
        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);
        int status = client.executeMethod(filePost);
        System.out.println(filePost.getResponseBodyAsString());
        if (status == 500 && !createdSubmitUser) {
            System.out.println("Let's try reauthenticating you");
            System.out.println();

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            userProps.load(new FileInputStream(submitUserFile));
            filePost = createFilePost(p, find, files, userProps);
            client = new HttpClient();
            client.setConnectionTimeout(HTTP_TIMEOUT);
            status = client.executeMethod(filePost);
            System.out.println(filePost.getResponseBodyAsString());
        }
        if (status != HttpStatus.SC_OK) {
            System.out.println("Status code: " + status);
            System.exit(1);
        }
        System.out.println("Submission accepted");
    } catch (Exception e) {
        System.out.println();
        System.out.println("An Error has occured during submission!");
        System.out.println();
        System.out.println("[DETAILS]");
        System.out.println(e.getMessage());
        e.printStackTrace(System.out);
        System.out.println();
    }
}

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

/**
 * Uploads a String containing eclipse launch events to the server.
 * /*  www  .  j  av  a  2s.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 {//www.  j  a va 2  s .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:at.tuwien.minimee.emulation.EmulationService.java

/**
 * Currently not exposed as a web service since miniMEE
 * has been integrated with Plato./*from  ww w.j ava2  s .co  m*/
 * This starts a session with GRATE
 * @param samplename filename of the object to be rendered remotely
 * @param data the file to be rendered remotely
 * @param toolID pointing to the corresponding minimee configuration
 * @return a URL to be posted to the browser for opening a GRATE session.
 * This URL points to a GRATE session that contains the object readily waiting
 * to be rendered, already injected into the appropriate environment.
 * @throws PlatoServiceException if the connection to the GRATE server failed
 */
public String startSession(String samplename, byte[] data, String toolID) throws PlatoServiceException {
    ToolConfig config = getToolConfig(toolID);

    String response;
    try {
        HttpClient client = new HttpClient();
        MultipartPostMethod mPost = new MultipartPostMethod(config.getTool().getExecutablePath());
        client.setConnectionTimeout(8000);

        // MultipartPostMethod needs a file instance
        File sample = File.createTempFile(samplename + System.nanoTime(), "tmp");
        OutputStream out = new BufferedOutputStream(new FileOutputStream(sample));
        out.write(data);
        out.close();

        mPost.addParameter("datei", samplename, sample);

        int statusCode = client.executeMethod(mPost);

        response = mPost.getResponseBodyAsString();

        return response + config.getParams();

    } catch (HttpException e) {
        throw new PlatoServiceException("Could not connect to GRATE.", e);
    } catch (FileNotFoundException e) {
        throw new PlatoServiceException("Could not create temp file.", e);
    } catch (IOException e) {
        throw new PlatoServiceException("Could not connect to GRATE.", e);
    }

}

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

@Override
protected void doWelcome() throws MissingConfigurationPropertyException, IOException {
    if (!isQuiet()) {
        System.out.println(//ww w  .j  a  va2 s.  c om
                "Connecting to submit server at " + getBuildServerConfiguration().getSubmitServerURL());
        String hostname = getBuildServerConfiguration().getHostname();
        System.out.println("Hostname: " + hostname);
        System.out.println("System load: " + SystemInfo.getSystemLoad());
        System.out.println("Java version: " + System.getProperty("java.version"));
        System.out.println("connection timeout: " + getConnectionTimeout());
        System.out.println();

    }
    String url = getWelcomeURL();
    MultipartPostMethod method = new MultipartPostMethod(url);

    addCommonParameters(method);

    BuildServer.printURI(getLog(), method);
    int responseCode;
    try {
        responseCode = client.executeMethod(method);
    } catch (IOException e) {
        throw new IOException("Buildserver unable to connect to submitserver at " + url, e);
    }
    if (!isQuiet())
        System.out.println(method.getResponseBodyAsString());

    if (responseCode != HttpStatus.SC_OK) {

        getLog().error("HTTP server returned non-OK response: " + responseCode + ": " + method.getStatusText());
        getLog().error(" for URI: " + method.getURI());
        getLog().error("Full error message: " + method.getStatusText());
        throw new IOException("Buildserver unable to connect to submitserver at " + url + ", Status "
                + responseCode + ": " + method.getStatusText());
    }

}

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

@Override
protected void reportBuildServerDeath(int submissionPK, int testSetupPK, long lastModified, String kind,
        String load) {/*from  w  w  w . j  ava2  s .  c  o  m*/

    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.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 w w w.  j  ava2  s .  co 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 .jav a  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  w  w .ja v a  2  s .  c  om*/
        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;
    }
}