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

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

Introduction

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

Prototype

public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException 

Source Link

Usage

From source file:JiraWebClient.java

public void updateIssue(final JiraIssue issue, final String comment, IProgressMonitor monitor)
        throws JiraException {
    doInSession(monitor, new JiraWebSessionCallback() {
        @Override/*  w ww . jav  a  2  s .  c  o  m*/
        public void run(JiraClient client, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder rssUrlBuffer = new StringBuilder(baseUrl);
            rssUrlBuffer.append("/secure/EditIssue.jspa"); //$NON-NLS-1$

            PostMethod post = new PostMethod(rssUrlBuffer.toString());
            post.setRequestHeader("Content-Type", getContentType(monitor)); //$NON-NLS-1$
            prepareSecurityToken(post);
            post.addParameter("summary", issue.getSummary()); //$NON-NLS-1$
            post.addParameter("issuetype", issue.getType().getId()); //$NON-NLS-1$
            if (issue.getPriority() != null) {
                post.addParameter("priority", issue.getPriority().getId()); //$NON-NLS-1$
            }
            addFields(client, issue, post, new String[] { "duedate" }); //$NON-NLS-1$
            post.addParameter("timetracking", Long.toString(issue.getEstimate() / 60) + "m"); //$NON-NLS-1$ //$NON-NLS-2$

            Component[] components = issue.getComponents();
            if (components != null) {
                if (components.length == 0) {
                    post.addParameter("components", "-1"); //$NON-NLS-1$ //$NON-NLS-2$
                } else {
                    for (Component component : components) {
                        post.addParameter("components", component.getId()); //$NON-NLS-1$
                    }
                }
            }

            Version[] versions = issue.getReportedVersions();
            if (versions != null) {
                if (versions.length == 0) {
                    post.addParameter("versions", "-1"); //$NON-NLS-1$ //$NON-NLS-2$
                } else {
                    for (Version version : versions) {
                        post.addParameter("versions", version.getId()); //$NON-NLS-1$
                    }
                }
            }

            Version[] fixVersions = issue.getFixVersions();
            if (fixVersions != null) {
                if (fixVersions.length == 0) {
                    post.addParameter("fixVersions", "-1"); //$NON-NLS-1$ //$NON-NLS-2$
                } else {
                    for (Version fixVersion : fixVersions) {
                        post.addParameter("fixVersions", fixVersion.getId()); //$NON-NLS-1$
                    }
                }
            }

            // TODO need to be able to choose unassigned and automatic
            if (issue.getAssignee() != null) {
                post.addParameter("assignee", issue.getAssignee()); //$NON-NLS-1$
            } else {
                post.addParameter("assignee", "-1"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            if (issue.getReporter() != null) {
                post.addParameter("reporter", issue.getReporter()); //$NON-NLS-1$
            }
            if (issue.getEnvironment() != null) {
                post.addParameter("environment", issue.getEnvironment()); //$NON-NLS-1$
            }
            post.addParameter("description", issue.getDescription()); //$NON-NLS-1$

            if (comment != null) {
                post.addParameter("comment", comment); //$NON-NLS-1$
            }
            post.addParameter("commentLevel", ""); //$NON-NLS-1$ //$NON-NLS-2$
            post.addParameter("id", issue.getId()); //$NON-NLS-1$

            if (issue.getSecurityLevel() != null) {
                post.addParameter("security", issue.getSecurityLevel().getId()); //$NON-NLS-1$
            }

            addCustomFields(client, issue, post);

            try {
                execute(post);
                if (!expectRedirect(post, issue)) {
                    handleErrorMessage(post);
                }
            } finally {
                post.releaseConnection();
            }
        }

    });
}

From source file:JiraWebClient.java

private void addFields(JiraClient client, JiraIssue issue, PostMethod post, String[] fields) {
    for (String field : fields) {
        if ("duedate".equals(field)) { //$NON-NLS-1$
            if (issue.getDue() != null) {
                DateFormat format = client.getLocalConfiguration().getDateFormat();
                post.addParameter("duedate", format.format(issue.getDue())); //$NON-NLS-1$
            } else {
                post.addParameter("duedate", ""); //$NON-NLS-1$ //$NON-NLS-2$
            }/*  www  .j a  v  a 2  s .c  o m*/
        } else if (field.startsWith("customfield_")) { //$NON-NLS-1$
            for (CustomField customField : issue.getCustomFields()) {
                addCustomField(client, post, customField);
            }
        } else {
            String[] values = issue.getFieldValues(field);
            if (values == null) {
                // method.addParameter(field, "");
            } else {
                for (String value : values) {
                    post.addParameter(field, value);
                }
            }
        }
    }
}

From source file:com.denimgroup.threadfix.service.remoteprovider.QualysRemoteProvider.java

private InputStream httpPost(String request, String[] paramNames, String[] paramVals) {

    PostMethod post = new PostMethod(request);

    post.setRequestHeader("Content-type", "text/xml; charset=UTF-8");

    if (username != null && password != null) {
        String login = username + ":" + password;
        String encodedLogin = new String(Base64.encodeBase64(login.getBytes()));

        post.setRequestHeader("Authorization", "Basic " + encodedLogin);
    }/*  ww w. j  a  v  a  2 s .  co  m*/

    try {
        for (int i = 0; i < paramNames.length; i++) {
            post.addParameter(paramNames[i], paramVals[i]);
        }

        HttpClient client = new HttpClient();

        int status = client.executeMethod(post);

        if (status != 200) {
            log.warn("Status was not 200.");
            log.warn("Status : " + status);
        }

        InputStream responseStream = post.getResponseBodyAsStream();

        if (responseStream != null) {
            return responseStream;
        }

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    log.warn("There was an error and the POST request was not finished.");
    return null;
}

From source file:JiraWebClient.java

private String createIssue(final String url, final JiraIssue issue, IProgressMonitor monitor)
        throws JiraException {
    final String[] issueKey = new String[1];
    doInSession(monitor, new JiraWebSessionCallback() {
        @Override/*from  ww w  .  j  av a 2  s  .  co m*/
        public void run(JiraClient client, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder attachFileURLBuffer = new StringBuilder(baseUrl);
            attachFileURLBuffer.append(url);

            PostMethod post = new PostMethod(attachFileURLBuffer.toString());
            post.setRequestHeader("Content-Type", getContentType(monitor)); //$NON-NLS-1$
            prepareSecurityToken(post);

            post.addParameter("pid", issue.getProject().getId()); //$NON-NLS-1$
            post.addParameter("issuetype", issue.getType().getId()); //$NON-NLS-1$
            post.addParameter("summary", issue.getSummary()); //$NON-NLS-1$
            if (issue.getPriority() != null) {
                post.addParameter("priority", issue.getPriority().getId()); //$NON-NLS-1$
            }
            addFields(client, issue, post, new String[] { "duedate" }); //$NON-NLS-1$
            post.addParameter("timetracking", Long.toString(issue.getEstimate() / 60) + "m"); //$NON-NLS-1$ //$NON-NLS-2$

            if (issue.getComponents() != null) {
                for (int i = 0; i < issue.getComponents().length; i++) {
                    post.addParameter("components", issue.getComponents()[i].getId()); //$NON-NLS-1$
                }
            } else {
                post.addParameter("components", "-1"); //$NON-NLS-1$ //$NON-NLS-2$
            }

            if (issue.getReportedVersions() != null) {
                for (int i = 0; i < issue.getReportedVersions().length; i++) {
                    post.addParameter("versions", issue.getReportedVersions()[i].getId()); //$NON-NLS-1$
                }
            } else {
                post.addParameter("versions", "-1"); //$NON-NLS-1$ //$NON-NLS-2$
            }

            if (issue.getFixVersions() != null) {
                for (int i = 0; i < issue.getFixVersions().length; i++) {
                    post.addParameter("fixVersions", issue.getFixVersions()[i].getId()); //$NON-NLS-1$
                }
            } else {
                post.addParameter("fixVersions", "-1"); //$NON-NLS-1$ //$NON-NLS-2$
            }

            if (issue.getAssignee() == null) {
                post.addParameter("assignee", "-1"); // Default assignee //$NON-NLS-1$ //$NON-NLS-2$
            } else if (issue.getAssignee().length() == 0) {
                post.addParameter("assignee", ""); // nobody //$NON-NLS-1$ //$NON-NLS-2$
            } else {
                post.addParameter("assignee", issue.getAssignee()); //$NON-NLS-1$
            }

            post.addParameter("reporter", client.getUserName()); //$NON-NLS-1$

            post.addParameter("environment", issue.getEnvironment() != null ? issue.getEnvironment() : ""); //$NON-NLS-1$ //$NON-NLS-2$
            post.addParameter("description", issue.getDescription() != null ? issue.getDescription() : ""); //$NON-NLS-1$ //$NON-NLS-2$

            if (issue.getParentId() != null) {
                post.addParameter("parentIssueId", issue.getParentId()); //$NON-NLS-1$
            }

            if (issue.getSecurityLevel() != null) {
                post.addParameter("security", issue.getSecurityLevel().getId()); //$NON-NLS-1$
            }

            addCustomFields(client, issue, post);

            try {
                execute(post);
                if (!expectRedirect(post, "/browse/", false)) { //$NON-NLS-1$
                    handleErrorMessage(post);
                } else {
                    final Header locationHeader = post.getResponseHeader("location"); //$NON-NLS-1$
                    // parse issue key from issue URL
                    String location = locationHeader.getValue();
                    int i = location.lastIndexOf("/"); //$NON-NLS-1$
                    if (i != -1) {
                        issueKey[0] = location.substring(i + 1);
                    } else {
                        throw new JiraException(
                                "The server redirected to an unexpected location while creating an issue: " //$NON-NLS-1$
                                        + location);
                    }
                }
            } finally {
                post.releaseConnection();
            }
        }
    });
    assert issueKey[0] != null;
    return issueKey[0];
}

From source file:de.mpg.mpdl.inge.pubman.web.sword.SwordUtil.java

/**
 * Logs in the given user with the given password.
 * /* w  w  w . jav a 2 s  .  c om*/
 * @param userid The id of the user to log in.
 * @param password The password of the user to log in.
 * @return The handle for the logged in user.
 * @throws HttpException
 * @throws IOException
 * @throws ServiceException
 * @throws URISyntaxException
 */
@Deprecated
public String loginUser(String userid, String password)
        throws HttpException, IOException, ServiceException, URISyntaxException {
    String frameworkUrl = PropertyReader.getFrameworkUrl();
    StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//");
    if (tokens.countTokens() != NUMBER_OF_URL_TOKENS) {
        throw new IOException(
                "Url in the config file is in the wrong format, needs to be http://<host>:<port>");
    }
    tokens.nextToken();
    StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":");

    if (hostPort.countTokens() != NUMBER_OF_URL_TOKENS) {
        throw new IOException(
                "Url in the config file is in the wrong format, needs to be http://<host>:<port>");
    }
    String host = hostPort.nextToken();
    int port = Integer.parseInt(hostPort.nextToken());

    HttpClient client = new HttpClient();

    client.getHostConfiguration().setHost(host, port, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userid);
    login.addParameter("j_password", password);

    client.executeMethod(login);

    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());

    Cookie sessionCookie = logoncookies[0];

    PostMethod postMethod = new PostMethod(LOGIN_URL);
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);

    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + login.getStatusCode());
    }

    String userHandle = null;
    Header[] headers = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(Base64.decode(location.substring(index + 1, location.length())));
        }
    }
    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}

From source file:de.mpg.escidoc.pubman.sword.SwordUtil.java

/**
 * Logs in the given user with the given password.
 * @param userid The id of the user to log in.
 * @param password The password of the user to log in.
 * @return The handle for the logged in user.
 * @throws HttpException//w  w  w. j  a  va2s  .  c o  m
 * @throws IOException
 * @throws ServiceException
 * @throws URISyntaxException
 */
@Deprecated
public String loginUser(String userid, String password)
        throws HttpException, IOException, ServiceException, URISyntaxException {
    String frameworkUrl = ServiceLocator.getFrameworkUrl();
    StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//");
    if (tokens.countTokens() != NUMBER_OF_URL_TOKENS) {
        throw new IOException(
                "Url in the config file is in the wrong format, needs to be http://<host>:<port>");
    }
    tokens.nextToken();
    StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":");

    if (hostPort.countTokens() != NUMBER_OF_URL_TOKENS) {
        throw new IOException(
                "Url in the config file is in the wrong format, needs to be http://<host>:<port>");
    }
    String host = hostPort.nextToken();
    int port = Integer.parseInt(hostPort.nextToken());

    HttpClient client = new HttpClient();

    client.getHostConfiguration().setHost(host, port, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userid);
    login.addParameter("j_password", password);

    client.executeMethod(login);

    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());

    Cookie sessionCookie = logoncookies[0];

    PostMethod postMethod = new PostMethod(LOGIN_URL);
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);

    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + login.getStatusCode());
    }

    String userHandle = null;
    Header[] headers = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(Base64.decode(location.substring(index + 1, location.length())));
        }
    }
    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}

From source file:com.testmax.uri.HttpRestWithXmlBody.java

public String handleHTTPPostPerformance() throws Exception {
    String resp = null;//from w  w w  .  j a  v a 2 s  .c o  m
    int startcount = 5;
    boolean isItemIdReplaced = false;
    String replacedParam = "";
    // Create a method instance.
    PostMethod method = new PostMethod(this.url);
    System.out.println(this.url);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    URLConfig urlConf = this.page.getPageURL().getUrlConfig(this.action);
    List<Element> globalItemList = urlConf.getItemListElement();
    if (globalItemList.size() > 0) {
        urlConf.setItemList();
        isItemIdReplaced = true;
    }
    Set<String> s = urlConf.getUrlParamset();

    for (String param : s) {
        if (!isItemIdReplaced) {
            //nvps.add(new BasicNameValuePair(param,urlConf.getUrlParamValue(param)));              
            method.addParameter(param, urlConf.getUrlParamValue(param));

        } else {
            replacedParam = urlConf.getUrlReplacedItemIdParamValue(param);
            method.addParameter(param, replacedParam);
            //System.out.println(replacedParam);              
            //nvps.add(new BasicNameValuePair(param,replacedParam));
        }

    }
    org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();

    this.startRecording();
    long starttime = this.getCurrentTime();
    int statusCode = 0;
    try {

        // Execute the method.
        statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            WmLog.printMessage("Auth Server response received, but there was a ParserConfigurationException: ");
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        resp = new String(responseBody, "UTF-8");

        // log the response
        WmLog.printMessage("MDE Request  : " + resp);

    } catch (HttpException e) {
        WmLog.printMessage("Unable to retrieve response from MDE webservice : " + e.getMessage());
        return null;
    } catch (IOException e) {
        WmLog.printMessage("Unable to retrieve response from MDE webservice : " + e.getMessage());
        return null;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    // Measure the time passed between response
    long elaspedTime = this.getElaspedTime(starttime);
    this.stopMethodRecording(statusCode, elaspedTime, startcount);

    //System.out.println(resp);
    System.out.println("ElaspedTime: " + elaspedTime);
    WmLog.printMessage("Response XML: " + resp);
    WmLog.printMessage("ElaspedTime: " + elaspedTime);
    this.printMethodRecording(statusCode, this.url);
    this.printMethodLog(statusCode, this.url);
    if (statusCode == 200 || statusCode == 400) {
        this.addThreadActionMonitor(this.action, true, elaspedTime);
    } else {
        this.addThreadActionMonitor(this.action, false, elaspedTime);
        WmLog.printMessage("Input XML: " + replacedParam);
        WmLog.printMessage("Response XML: " + resp);
    }

    return (resp);

}

From source file:edu.ucuenca.authorsdisambiguation.Distance.java

public synchronized String Http2(String s, Map<String, String> mp) throws SQLException, IOException {
    String md = s + mp.toString();
    Statement stmt = conn.createStatement();
    String sql;//from www . j  a  v a  2s.co  m
    sql = "SELECT * FROM cache where cache.key='" + getMD5(md) + "'";
    java.sql.ResultSet rs = stmt.executeQuery(sql);
    String resp = "";
    if (rs.next()) {
        resp = rs.getString("value");
        rs.close();
        stmt.close();
    } else {
        rs.close();
        stmt.close();

        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(s);

        //Add any parameter if u want to send it with Post req.
        for (Entry<String, String> mcc : mp.entrySet()) {
            method.addParameter(mcc.getKey(), mcc.getValue());
        }

        int statusCode = client.executeMethod(method);

        if (statusCode != -1) {
            InputStream in = method.getResponseBodyAsStream();
            final Scanner reader = new Scanner(in, "UTF-8");
            while (reader.hasNextLine()) {
                final String line = reader.nextLine();
                resp += line + "\n";
            }
            reader.close();

            try {
                JsonParser parser = new JsonParser();
                parser.parse(resp);
                PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO cache (key, value) values (?, ?)");
                stmt2.setString(1, getMD5(md));
                stmt2.setString(2, resp);
                stmt2.executeUpdate();
                stmt2.close();

            } catch (Exception e) {
                System.out.printf("Error al insertar en la DB: " + e);
            }

        }

    }

    return resp;
}

From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java

/**
 * @param fileName/*w w  w . j  ava  2 s. co  m*/
 * @param isThumb
 * @return
 */
private boolean deleteFileFromWeb(final String fileName, final boolean isThumb) {
    try {
        //String     targetURL  = String.format("http://localhost/cgi-bin/filedelete.php?filename=%s;disp=%s", targetName, discipline.getName());
        //String     targetURL  = subAllExtraData(delURLStr, fileName, isThumb, null, null);
        fillValuesArray();
        PostMethod postMethod = new PostMethod(delURLStr);
        postMethod.addParameter("filename", fileName);
        postMethod.addParameter("token", generateToken(fileName));
        postMethod.addParameter("coll", values[0]);
        postMethod.addParameter("disp", values[1]);
        postMethod.addParameter("div", values[2]);
        postMethod.addParameter("inst", values[3]);
        //log.debug("Deleting " + fileName + " from " + targetURL );

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

        int status = client.executeMethod(postMethod);
        updateServerTimeDelta(postMethod);

        //log.debug(getMethod.getResponseBodyAsString());

        return status == HttpStatus.SC_OK || status == HttpStatus.SC_NOT_FOUND;

    } catch (Exception ex) {
        //log.debug("Error: " + ex.getMessage());
        ex.printStackTrace();
    }
    return false;
}

From source file:com.epam.wilma.gepard.testclient.MultiStubHttpPostRequestSender.java

private void createRequest(final MultiStubRequestParameters requestParameters, final PostMethod httpPost)
        throws IOException, ParserConfigurationException, SAXException {
    InputStream inputStream = requestParameters.getInputStream();
    if (requestParameters.getContentType().contains("fastinfoset")) {
        inputStream = fastInfosetCompressor.compress(inputStream);
    }/*from   w  w w.j  ava 2  s  . com*/
    if (requestParameters.getContentEncoding().contains("gzip")) {
        inputStream = gzipCompressor.compress(inputStream);
        httpPost.setRequestHeader("Content-Encoding", requestParameters.getContentEncoding());
    }
    final InputStreamRequestEntity entity = new InputStreamRequestEntity(inputStream,
            requestParameters.getContentType());
    httpPost.setRequestEntity(entity);
    httpPost.setRequestHeader("Accept", requestParameters.getAcceptHeader());
    httpPost.addRequestHeader("Accept-Encoding", requestParameters.getAcceptEncoding());
    if (requestParameters.getSpecialHeader() != null) {
        httpPost.addRequestHeader("Special-Header", requestParameters.getSpecialHeader());
    }
    httpPost.addParameter("nextstatus", requestParameters.getStatus());
    httpPost.addParameter("direction", requestParameters.getDirection());
    httpPost.addParameter("groupname", requestParameters.getGroupName());
}