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

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

Introduction

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

Prototype

public void addParameter(String paramString1, String paramString2) 

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 a  v a 2  s  . c  o 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 {/*w  w w  . ja v  a 2  s  . com*/
        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//w  w w  .  jav  a  2  s  .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.
 * /*from   www  . j  a  v  a 2 s  .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:edu.umd.cs.marmoset.modelClasses.CodeMetrics.java

public void mapIntoHttpHeader(MultipartPostMethod method) {
    method.addParameter("md5sumClassfiles", getMd5sumClassfiles());
    method.addParameter("md5sumSourcefiles", getMd5sumSourcefiles());
    method.addParameter("codeSegmentSize", Integer.toString(getCodeSegmentSize()));
}

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

/**
 * @param allSubmissionProps/*from  w w w . j  av a 2  s.  co  m*/
 * @param filePost
 */
static void addAllPropertiesButSubmitURL(Properties allSubmissionProps, MultipartPostMethod filePost) {
    for (Map.Entry<?, ?> e : allSubmissionProps.entrySet()) {
        String key = (String) e.getKey();
        String value = (String) e.getValue();
        if (!key.equals("submitURL"))
            filePost.addParameter(key, value);
    }
}

From source file:com.totsp.sotu.app.ScreenAreaWatcher.java

/** Creates a new instance of ScreenWatcher */
public ScreenAreaWatcher(final Configuration config) throws AWTException {
    super();/*  ww  w  . j a v  a 2 s .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.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  w  ww . j  a  v a2  s  . com*/
        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();
    }

}

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

@Override
protected void reportBuildServerDeath(int submissionPK, int testSetupPK, long lastModified, String kind,
        String load) {/*from  ww  w  .j a  v a  2 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.buildServer.BuildServerDaemon.java

protected void addCommonParameters(MultipartPostMethod method) {
    String hostname = getBuildServerConfiguration().getHostname();

    method.addParameter("testMachine", hostname);
    method.addParameter("hostname", hostname);

    method.addParameter("load", SystemInfo.getSystemLoad());
    String supportedCourses = getBuildServerConfiguration().getSupportedCourses();
    method.addParameter("courses", supportedCourses);
    method.addParameter("javaVersion", System.getProperty("java.version"));
    method.addParameter("serverTimestamp", Long.toString(getBuildServerConfiguration().getServerTimestamp()));
    method.addParameter("connectionTimeout", Integer.toString(getConnectionTimeout()));
}