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:com.discursive.jccook.httpclient.MultipartPostFileExample.java

public static void main(String[] args) throws HttpException, IOException {
    // Configure Logging
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");

    HttpClient client = new HttpClient();

    // Create POST method
    String weblintURL = "http://ats.nist.gov/cgi-bin/cgi.tcl/echo.cgi";
    MultipartPostMethod method = new MultipartPostMethod(weblintURL);

    File file = new File("data", "test.txt");
    File file2 = new File("data", "sample.txt");
    method.addParameter("test.txt", file);
    method.addPart(new FilePart("sample.txt", file2, "text/plain", "ISO-8859-1"));

    // Execute and print response
    client.executeMethod(method);/* w  w  w.  j  ava2  s  .  co  m*/
    String response = method.getResponseBodyAsString();
    System.out.println(response);

    method.releaseConnection();
}

From source file:it.iit.genomics.cru.simsearch.bundle.utils.PantherBridge.java

public static Collection<String[]> getEnrichment(String organism, String fileName, double threshold) {
    ArrayList<String[]> results = new ArrayList<>();

    ArrayListMultimap<String, String> genes = ArrayListMultimap.create();
    ArrayListMultimap<Double, String> pvalues = ArrayListMultimap.create();

    HashSet<String> uniqueGenes = new HashSet<>();

    try {/*from   w  w  w .j  a  v  a 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  www.ja  v  a 2  s . com*/
 * 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.util.ServletAppender.java

@Override
protected void append(LoggingEvent event) {
    if (!APPEND_TO_SUBMIT_SERVER)
        return;//from   w w w .  ja  v  a2s . c  o m
    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:com.totsp.sotu.app.ScreenAreaWatcher.java

/** Creates a new instance of ScreenWatcher */
public ScreenAreaWatcher(final Configuration config) throws AWTException {
    super();/*from ww  w  . ja va  2s  .  c  o  m*/
    this.config = config;
    System.out.println(config.getWidth() + "x" + config.getHeight());
    JPanel jp = null;

    JWindow top = new JWindow();
    top.setBackground(GREEN);
    top.setLocation(0, 0);
    top.setAlwaysOnTop(true);
    jp = new JPanel();
    jp.setBackground(GREEN);
    top.add(jp);
    top.pack();
    top.setSize(config.getWidth(), config.getBorderSize());

    JWindow bottom = new JWindow();
    bottom.setBackground(GREEN);
    bottom.setLocation(0, config.getHeight() - config.getBorderSize());
    bottom.setAlwaysOnTop(true);
    jp = new JPanel();
    jp.setBackground(GREEN);
    bottom.add(jp);
    bottom.pack();
    bottom.setSize(config.getWidth(), config.getBorderSize());

    JWindow left = new JWindow();
    left.setBackground(GREEN);
    left.setLocation(0, 0);
    left.setAlwaysOnTop(true);
    jp = new JPanel();
    jp.setBackground(GREEN);
    left.add(jp);
    left.pack();
    left.setSize(config.getBorderSize(), config.getHeight());

    JWindow right = new JWindow();
    right.setLocation(config.getWidth() - config.getBorderSize(), 0);
    right.setAlwaysOnTop(true);
    jp = new JPanel();
    jp.setBackground(GREEN);
    right.add(jp);
    right.pack();
    right.setSize(config.getBorderSize(), config.getHeight());

    top.setVisible(true);
    bottom.setVisible(true);
    left.setVisible(true);
    right.setVisible(true);

    windows = new JWindow[4];
    windows[0] = top;
    windows[1] = bottom;
    windows[2] = left;
    windows[3] = right;

    MouseInputAdapter adapter = new Adapter(windows);

    top.addMouseListener(adapter);
    top.addMouseMotionListener(adapter);
    bottom.addMouseListener(adapter);
    bottom.addMouseMotionListener(adapter);
    left.addMouseListener(adapter);
    left.addMouseMotionListener(adapter);
    right.addMouseListener(adapter);
    right.addMouseMotionListener(adapter);

    timer.schedule(new ImageUpdateTimerTask(this), 0, config.getMaxUpdateInterval());

    this.addPropertyChangeListener("image", new PropertyChangeListener() {
        HttpClient client = new HttpClient();

        public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
            BufferedImage img = (BufferedImage) propertyChangeEvent.getNewValue();
            try {
                File outputFile = File.createTempFile("save-" + System.currentTimeMillis(), ".png");
                JAI.create("filestore", img, outputFile.getCanonicalPath(), "PNG", null);
                System.out.println("Temp File:  " + outputFile.getCanonicalPath());
                MultipartPostMethod method = new MultipartPostMethod(
                        config.getServerUrl() + "/ImagePublishingServlet");
                method.addParameter("adminPassword", config.getAdminPassword());
                method.addParameter("conversation", config.getConversationName());
                method.addParameter("image", outputFile);
                client.executeMethod(method);

            } catch (Exception e) {
                System.err.println("Error handling image");
                e.printStackTrace();
            }
        }

    });
}

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

/**
 * @param p//from   ww  w. j a v a2s  .  com
 * @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.eclipse.courseProjectManager.EclipseLaunchEventLog.java

/**
 * Uploads a String containing eclipse launch events to the server.
 * // w w w  . ja  v a  2 s.  co 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:edu.umd.cs.buildServer.BuildServerDaemon.java

@Override
protected void doWelcome() throws MissingConfigurationPropertyException, IOException {
    if (!isQuiet()) {
        System.out.println(/*from ww  w .j a  v  a  2s .  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 ProjectSubmission<?> getProjectSubmission()
        throws MissingConfigurationPropertyException, IOException {

    try {//w w w  . jav  a 2 s .  com
        String url = getRequestSubmissionURL();
        MultipartPostMethod method = new MultipartPostMethod(url);

        String supportedCoursePKList = getBuildServerConfiguration().getSupportedCourses();

        String specificProjectNum = getConfig().getOptionalProperty(DEBUG_SPECIFIC_PROJECT);
        String specificCourse = getConfig().getOptionalProperty(DEBUG_SPECIFIC_COURSE);
        if (specificCourse != null)
            supportedCoursePKList = specificCourse;

        String specificSubmission = getConfig().getOptionalProperty(DEBUG_SPECIFIC_SUBMISSION);
        String specificTestSetup = getConfig().getOptionalProperty(DEBUG_SPECIFIC_TESTSETUP);

        if (specificSubmission != null) {
            method.addParameter("submissionPK", specificSubmission);
            if (!isQuiet())
                System.out.printf("Requesting submissionPK %s%n", specificSubmission);
        }
        if (specificTestSetup != null) {
            method.addParameter("testSetupPK", specificTestSetup);
            if (!isQuiet())
                System.out.printf("Requesting testSetupPK %s%n", specificTestSetup);
        }

        if (specificProjectNum != null) {
            method.addParameter("projectNumber", specificProjectNum);
        }

        addCommonParameters(method);

        BuildServer.printURI(getLog(), method);

        int responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK) {
            if (responseCode == HttpStatus.SC_SERVICE_UNAVAILABLE) {
                getLog().trace("Server returned 503 (no work)");
            } else {
                String msg = "HTTP server returned non-OK response: " + responseCode + ": "
                        + method.getStatusText();
                getLog().error(msg);
                getLog().error(" for URI: " + method.getURI());

                getLog().error("Full error message: " + method.getResponseBodyAsString());
                if (responseCode == HttpStatus.SC_BAD_REQUEST) {
                    if (!isQuiet()) {
                        System.err.println(msg);
                        System.out.println(msg);
                    }
                    System.exit(1);
                }
            }
            return null;
        }

        getLog().debug("content-type: " + method.getResponseHeader("Content-type"));
        getLog().debug("content-length: " + method.getResponseHeader("content-length"));
        // Ensure we have a submission PK.
        String submissionPK = getRequiredHeaderValue(method, HttpHeaders.HTTP_SUBMISSION_PK_HEADER);
        if (submissionPK == null) {
            if (specificSubmission != null)
                getLog().error("Server did not return submission " + specificSubmission);
            return null;
        }

        // Ensure we have a project PK.
        String testSetupPK = specificTestSetup != null ? specificTestSetup : getTestSetupPK(method);
        if (testSetupPK == null)
            return null;

        // This is a boolean value specifying whether the project jar file
        // is NEW, meaning that it needs to be tested against the
        // canonical project solution. The build server doesn't need
        // to do anything with this value except pass it back to
        // the submit server when reporting test outcomes.
        String isNewTestSetup = getIsNewTestSetup(method);
        if (isNewTestSetup == null)
            return null;

        // Opaque boolean value representing whether this was a
        // "background retest".
        // The BuildServer doesn't need to do anything with this except pass it
        // back to the SubmitServer.
        String isBackgroundRetest = getRequiredHeaderValue(method, HttpHeaders.HTTP_BACKGROUND_RETEST);
        if (isBackgroundRetest == null)
            isBackgroundRetest = "no";

        ServletAppender servletAppender = (ServletAppender) getLog().getAppender("servletAppender");
        if (isBackgroundRetest.equals("yes"))
            servletAppender.setThreshold(Level.FATAL);
        else
            servletAppender.setThreshold(Level.INFO);

        String kind = method.getResponseHeader(HttpHeaders.HTTP_KIND_HEADER).getValue();
        String logMsg = "Got submission " + submissionPK + ", testSetup " + testSetupPK + ", kind: " + kind;
        getLog().info(logMsg);

        ProjectSubmission<?> projectSubmission = new ProjectSubmission<TestProperties>(
                getBuildServerConfiguration(), getLog(), submissionPK, testSetupPK, isNewTestSetup,
                isBackgroundRetest, kind);

        projectSubmission.setMethod(method);

        getCurrentFile().delete();
        writeToCurrentFile(submissionPK + "\n" + testSetupPK + "\n" + kind + "\n" + SystemInfo.getSystemLoad()
                + "\n" + logMsg);

        return projectSubmission;
    } catch (ConnectException e) {
        getLog().warn("Unable to connect to " + getBuildServerConfiguration().getSubmitServerURL());
        return null;
    }
}

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

@Override
protected void downloadProjectJarFile(ProjectSubmission<?> projectSubmission)
        throws MissingConfigurationPropertyException, HttpException, IOException, BuilderException {
    // FIXME: We should cache these

    MultipartPostMethod method = new MultipartPostMethod(getTestSetupURL());
    method.addParameter("testSetupPK", projectSubmission.getTestSetupPK());
    method.addParameter("projectJarfilePK", projectSubmission.getTestSetupPK());
    String supportedCourses = getBuildServerConfiguration().getSupportedCourses();
    method.addParameter("courses", supportedCourses);

    BuildServer.printURI(getLog(), method);

    try {//from   ww w . j  av  a2s  .  c o  m
        int responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK) {
            throw new BuilderException("Could not download project test setup from " + getTestSetupURL() + ": "
                    + responseCode + ": " + method.getStatusText());
        }

        getLog().trace("Downloading test setup file");
        IO.download(projectSubmission.getTestSetup(), method);

        // We're passing the project_jarfile_pk so we don't need to read it
        // from
        // the headers

        // wait for a while in case the files have not "settled"
        // TODO: Verify that this is still necessary; should be OK unless
        // run on NFS
        pause(10);

        getLog().trace("Done.");
    } finally {
        method.releaseConnection();
    }

}