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

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

Introduction

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

Prototype

public void setParameter(String paramString1, String paramString2) 

Source Link

Usage

From source file:com.twinsoft.convertigo.eclipse.wizards.setup.SetupWizard.java

public void register(final String username, final String password, final String firstname,
        final String lastname, final String email, final String country, final String company,
        final String companyHeadcount, final RegisterCallback callback) {
    Thread th = new Thread(new Runnable() {

        public void run() {
            synchronized (SetupWizard.this) {
                boolean success = false;
                String message;/*from w w w  . j  av  a 2s .co  m*/

                try {
                    String[] url = { registrationServiceUrl };
                    HttpClient client = prepareHttpClient(url);
                    PostMethod method = new PostMethod(url[0]);
                    HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value());
                    // set parameters for POST method
                    method.setParameter("__sequence", "checkEmail");
                    method.setParameter("username", username);
                    method.setParameter("password", password);
                    method.setParameter("firstname", firstname);
                    method.setParameter("lastname", lastname);
                    method.setParameter("email", email);
                    method.setParameter("country", country);
                    method.setParameter("company", company);
                    method.setParameter("companyHeadcount", companyHeadcount);

                    // execute HTTP post with parameters
                    int statusCode = client.executeMethod(method);
                    if (statusCode == HttpStatus.SC_OK) {
                        Document document = XMLUtils.parseDOM(method.getResponseBodyAsStream());
                        NodeList nd = document.getElementsByTagName("errorCode");

                        if (nd.getLength() > 0) {
                            Node node = nd.item(0);
                            String errorCode = node.getTextContent();

                            if ("0".equals(errorCode)) {
                                success = true;
                                message = "Registration submited, please check your email.";
                            } else {
                                method = new PostMethod(registrationServiceUrl);

                                // set parameters for POST method to get the
                                // details of error messages
                                method.setParameter("__sequence", "getErrorMessages");
                                client.executeMethod(method);
                                document = XMLUtils.parseDOM(method.getResponseBodyAsStream());
                                nd = document.getElementsByTagName("label");
                                Node nodeDetails = nd.item(Integer.parseInt(errorCode));

                                ConvertigoPlugin.logError(nodeDetails.getTextContent());
                                message = "Failed to register: " + nodeDetails.getTextContent();
                            }
                        } else {
                            success = true;
                            message = "debug";
                        }
                    } else {
                        message = "Unexpected HTTP status: " + statusCode;
                    }
                } catch (Exception e) {
                    message = "Generic failure: " + e.getClass().getSimpleName() + ", " + e.getMessage();
                    ConvertigoPlugin.logException(e, "Error while trying to send registration");
                }
                callback.onRegister(success, message);
            }
        }

    });
    th.setDaemon(true);
    th.setName("SetupWizard.register");
    th.start();
}

From source file:edu.indiana.d2i.htrc.portal.HTRCExperimentalAnalysisServiceClient.java

public void stopVM(String vmId, Http.Session session) throws IOException {
    String stopVMUrl = PlayConfWrapper.sloanWsEndpoint() + PlayConfWrapper.stopVMUrl();
    PostMethod post = new PostMethod(stopVMUrl);
    post.addRequestHeader("Authorization", "Bearer " + session.get(PortalConstants.SESSION_TOKEN));
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.addRequestHeader("htrc-remote-user", session.get(PortalConstants.SESSION_USERNAME));
    post.addRequestHeader("htrc-remote-user-email", session.get(PortalConstants.SESSION_EMAIL));
    post.setParameter("vmid", vmId);

    int response = client.executeMethod(post);
    this.responseCode = response;
    if (response == 200) {
        log.info("Stoped VM Id: " + vmId);
        log.info(Arrays.toString(post.getRequestHeaders()));
    } else {//from w  ww.  j  ava2  s.  c o  m
        log.error(post.getResponseBodyAsString());
    }
}

From source file:edu.indiana.d2i.htrc.portal.HTRCExperimentalAnalysisServiceClient.java

public void startVM(String vmId, Http.Session session) throws IOException {
    String launchVMUrl = PlayConfWrapper.sloanWsEndpoint() + PlayConfWrapper.startVMUrl();
    PostMethod post = new PostMethod(launchVMUrl);
    post.addRequestHeader("Authorization", "Bearer " + session.get(PortalConstants.SESSION_TOKEN));
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.addRequestHeader("htrc-remote-user", session.get(PortalConstants.SESSION_USERNAME));
    post.addRequestHeader("htrc-remote-user-email", session.get(PortalConstants.SESSION_EMAIL));
    post.setParameter("vmid", vmId);

    int response = client.executeMethod(post);
    this.responseCode = response;
    if (response == 200) {
        log.info("Started VM Id: " + vmId);
        log.info(Arrays.toString(post.getRequestHeaders()));
    } else {/*from  w ww . jav a  2 s .c  o  m*/
        log.error(post.getResponseBodyAsString());
    }
}

From source file:mapbuilder.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Post request// ww  w  . j a v a 2s  .  co m
 */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
        if (log.isDebugEnabled()) {
            Enumeration e = request.getHeaderNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                String value = request.getHeader(name);
                log.debug("request header:" + name + ":" + value);
            }
        }

        String serverUrl = request.getHeader("serverUrl");
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            PostMethod httppost = new PostMethod(serverUrl);

            // Transfer bytes from in to out
            log.info("HTTP POST transfering..." + serverUrl);
            String body = inputStreamAsString(request.getInputStream());

            HttpClient client = new HttpClient();

            httppost.setRequestBody(body);
            if (0 == httppost.getParameters().length) {
                log.debug("No Name/Value pairs found ... pushing as raw_post_data");
                httppost.setParameter("raw_post_data", body);
            }
            if (log.isDebugEnabled()) {
                log.debug("Body = " + body);
                NameValuePair[] nameValuePairs = httppost.getParameters();
                log.debug("NameValuePairs found: " + nameValuePairs.length);
                for (int i = 0; i < nameValuePairs.length; ++i) {
                    log.debug("parameters:" + nameValuePairs[i].toString());
                }
            }
            //httppost.setRequestContentLength(PostMethod.CONTENT_LENGTH_CHUNKED);

            client.executeMethod(httppost);
            if (log.isDebugEnabled()) {
                Header[] respHeaders = httppost.getResponseHeaders();
                for (int i = 0; i < respHeaders.length; ++i) {
                    String headerName = respHeaders[i].getName();
                    String headerValue = respHeaders[i].getValue();
                    log.debug("responseHeaders:" + headerName + "=" + headerValue);
                }
            }

            if (httppost.getStatusCode() == HttpStatus.SC_OK) {
                response.setContentType("text/xml");
                String responseBody = httppost.getResponseBodyAsString();
                // use encoding of the request or UTF8
                String encoding = request.getCharacterEncoding();
                if (encoding == null)
                    encoding = "UTF-8";
                response.setCharacterEncoding(encoding);
                log.info("responseEncoding:" + encoding);
                // do not set a content-length of the response (string length might not match the response byte size)
                //response.setContentLength(responseBody.length());
                log.info("responseBody:" + responseBody);
                PrintWriter out = response.getWriter();
                out.print(responseBody);
            } else {
                log.error("Unexpected failure: " + httppost.getStatusLine().toString());
            }
            httppost.releaseConnection();
        } else {
            throw new ServletException("only HTTP(S) protocol supported");
        }

    } catch (Throwable e) {
        throw new ServletException(e);
    }
}

From source file:edu.indiana.d2i.htrc.portal.HTRCExperimentalAnalysisServiceClient.java

public void deleteVM(String vmId, Http.Session session) throws IOException {
    String deleteVMUrl = PlayConfWrapper.sloanWsEndpoint() + PlayConfWrapper.deleteVMUrl();
    PostMethod post = new PostMethod(deleteVMUrl);
    post.addRequestHeader("Authorization", "Bearer " + session.get(PortalConstants.SESSION_TOKEN));
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.addRequestHeader("htrc-remote-user", session.get(PortalConstants.SESSION_USERNAME));
    post.addRequestHeader("htrc-remote-user-email", session.get(PortalConstants.SESSION_EMAIL));
    post.setParameter("vmid", vmId);

    int response = client.executeMethod(post);
    this.responseCode = response;
    if (response == 200) {
        log.info("Deleted VM Id: " + vmId);
        log.info(Arrays.toString(post.getRequestHeaders()));
    } else {/*from   w w  w.ja v a 2s . c om*/
        log.error(post.getResponseBodyAsString());
    }

}

From source file:edu.indiana.d2i.htrc.portal.HTRCExperimentalAnalysisServiceClient.java

public void switchVMMode(String vmId, String mode, Http.Session session) throws IOException {
    String switchVMModeUrl = PlayConfWrapper.sloanWsEndpoint() + PlayConfWrapper.switchVMUrl();
    PostMethod post = new PostMethod(switchVMModeUrl);
    post.addRequestHeader("Authorization", "Bearer " + session.get(PortalConstants.SESSION_TOKEN));
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.addRequestHeader("htrc-remote-user", session.get(PortalConstants.SESSION_USERNAME));
    post.addRequestHeader("htrc-remote-user-email", session.get(PortalConstants.SESSION_EMAIL));
    post.setParameter("vmid", vmId);
    post.setParameter("mode", mode);

    int response = client.executeMethod(post);
    this.responseCode = response;
    if (response == 200) {
        log.info("Switch to " + mode + " mode.");
        log.info(Arrays.toString(post.getRequestHeaders()));
    } else {/*from  w w  w. j a v a2s  . co  m*/
        log.error(post.getResponseBodyAsString());
    }
}

From source file:edu.indiana.d2i.htrc.portal.HTRCExperimentalAnalysisServiceClient.java

public String createVM(String imageName, String loginUerName, String loginPassword, String memory, String vcpu,
        Http.Session session) throws IOException {
    String createVMUrl = PlayConfWrapper.sloanWsEndpoint() + PlayConfWrapper.createVMUrl();

    PostMethod post = new PostMethod(createVMUrl);
    post.addRequestHeader("Authorization", "Bearer " + session.get(PortalConstants.SESSION_TOKEN));
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.addRequestHeader("htrc-remote-user", session.get(PortalConstants.SESSION_USERNAME));
    post.addRequestHeader("htrc-remote-user-email", session.get(PortalConstants.SESSION_EMAIL));
    post.setParameter("imagename", imageName);
    post.setParameter("loginusername", loginUerName);
    post.setParameter("loginpassword", loginPassword);
    post.setParameter("memory", memory);
    post.setParameter("vcpu", vcpu);
    //        post.setRequestBody((org.apache.commons.httpclient.NameValuePair[]) urlParameters);

    int response = client.executeMethod(post);
    this.responseCode = response;
    if (response == 200) {
        String jsonStr = post.getResponseBodyAsString();
        log.info(Arrays.toString(post.getRequestHeaders()));
        JSONParser parser = new JSONParser();
        try {//from   ww w  .j  a  v  a  2 s .  c  o m
            Object obj = parser.parse(jsonStr);
            JSONObject jsonObject = (JSONObject) obj;
            return ((String) jsonObject.get("vmid"));

        } catch (ParseException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    } else {
        this.responseCode = response;
        log.error(post.getResponseBodyAsString());
        throw new IOException("Response code " + response + " for " + createVMUrl + " message: \n "
                + post.getResponseBodyAsString());
    }
    return null;

}

From source file:edu.indiana.d2i.htrc.portal.HTRCExperimentalAnalysisServiceClient.java

public VMStatus showVM(String vmId, Http.Session session) throws IOException {
    String showVMUrl = PlayConfWrapper.sloanWsEndpoint() + PlayConfWrapper.showVMUrl();
    VMStatus vmStatus = new VMStatus();
    PostMethod post = new PostMethod(showVMUrl);
    post.addRequestHeader("Authorization", "Bearer " + session.get(PortalConstants.SESSION_TOKEN));
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.addRequestHeader("htrc-remote-user", session.get(PortalConstants.SESSION_USERNAME));
    post.addRequestHeader("htrc-remote-user-email", session.get(PortalConstants.SESSION_EMAIL));
    post.setParameter("vmid", vmId);

    int response = client.executeMethod(post);
    this.responseCode = response;
    if (response == 200) {
        String jsonStr = post.getResponseBodyAsString();
        log.info(Arrays.toString(post.getRequestHeaders()));
        JSONParser parser = new JSONParser();
        try {//from   w  ww.  ja v  a2  s  . c  o m
            Object obj = parser.parse(jsonStr);
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray jsonArray = (JSONArray) jsonObject.get("status");
            log.info(String.valueOf(jsonArray));

            for (Object aJsonArray : jsonArray) {
                JSONObject infoObject = (JSONObject) aJsonArray;

                vmStatus.setVmId((String) infoObject.get("vmid"));
                vmStatus.setMode((String) infoObject.get("mode"));
                vmStatus.setState((String) infoObject.get("state"));
                vmStatus.setVncPort((Long) infoObject.get("vncport"));
                vmStatus.setSshPort((Long) infoObject.get("sshport"));
                vmStatus.setPublicIp((String) infoObject.get("publicip"));
                vmStatus.setVcpu((Long) infoObject.get("vcpus"));
                vmStatus.setMemory((Long) infoObject.get("memSize"));
                vmStatus.setVolumeSize((Long) infoObject.get("volumeSize"));
                vmStatus.setImageName((String) infoObject.get("imageName"));
                vmStatus.setVmIntialLogingId((String) infoObject.get("vmInitialLoginId"));
                vmStatus.setVmInitialLogingPassword((String) infoObject.get("vmInitialLoginPassword"));
            }

        } catch (ParseException e) {

            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
        return vmStatus;

    } else {
        this.responseCode = response;
        log.error(post.getResponseBodyAsString());
        throw new IOException("Response code " + response + " for " + showVMUrl + " message: \n "
                + post.getResponseBodyAsString());
    }

}

From source file:hk.hku.cecid.corvus.http.EnvelopQuerySender.java

/** 
 * [@EVENT] This method is invoked when the sender is required to create a HTTP Request from configuration.
 * <br/><br/>//w w w. j  av  a  2  s .c o m
 * It generates a form-url-encoded content embedded in the HTTP POST request. It contains 
 * two parameters, message_id and message_box. The value of these parameters are  
 * extracted from {@link #getMessageIdToDownload()} and {@link #getMessageBoxToDownload()} 
 * respectively.
 * <br/><br/>
 * <b>NOTE</b>: The values of message_box parameter may differ to what you see because it
 * may transform {@link #getMessageBoxMapping()}. 
 * 
 * @throws NullPointerException
 *          When {@link #getMessageIdToDownload()} return null.<br/>
 *          When {@link #getMessageBoxToDownload()} return empty or null.
 * @throws IllegalArgumentException          
 *          When {@link #getMessageBoxToDownload()} return string not equal to 'INBOX' and 'OUTBOX'
 */
protected HttpMethod onCreateRequest() throws Exception {
    this.checkArguments(this.messageIdToDownload, this.messageBoxToDownload);
    // Create HTTP Form POST method 
    PostMethod post = new PostMethod(this.getServiceEndPoint().toExternalForm());

    // transform the message box value.
    String mappedMsgBox;
    Map messageBoxMapping = this.getMessageBoxMapping();

    if (messageBoxMapping == null) {
        this.log.warn("No Message Box mapping found, use NO-OP mapping.");
        mappedMsgBox = this.messageBoxToDownload;
    } else {
        mappedMsgBox = (String) messageBoxMapping.get(this.messageBoxToDownload);
    }
    // Assign the message_id, message_box as the post parameter.
    post.setParameter(MSGID_FORM_PARAM, this.messageIdToDownload);
    post.setParameter(MSGBOX_FORM_PARAM, mappedMsgBox);
    return post;
}

From source file:application.draw.SaveButtonDebuggFrame.java

private void updateButtonActionPerformed(ActionEvent evt) {
    // System.out.println("updateButton.actionPerformed, event="+evt);
    //TODO add your code for updateButton.actionPerformed

    /* make the body (fig) */
    String fig = this.applet.frm.editdispatch.getFigString();
    /*/*from ww w.  j  a  v a2  s . c  o m*/
    try{
       fig=new String(fig.getBytes("UTF-8"),  "UTF-8");
    }
    catch(Exception e){
       return;
    }
    */
    this.updateText = this.updateText + "\n " + insertSpaceAfterNewLine(fig);

    this.urlField.setText(this.actionUrl);
    String url = this.urlField.getText();
    this.messageTextArea.setText(url + "\n");
    //      this.messageTextArea.append(this.updateText);
    BufferedReader br = null;
    //      System.out.println("updateText="+this.updateText);
    System.out.println("editWriteValue=" + this.editWriteValue);
    System.out.println("editCmd=" + this.editCmd);
    System.out.println("editPage=" + this.editPage);
    System.out.println("digest=" + this.editDigest);
    try {
        PostMethod method = new PostMethod(url);
        if (this.client == null)
            return;
        method.getParams().setContentCharset(this.pageCharSet);
        method.setParameter("msg", this.updateText);
        //          method.setParameter("encode_hint",this.editEncodeHint);
        method.addParameter("write", this.editWriteValue);
        method.addParameter("cmd", this.editCmd);
        method.addParameter("page", this.editPage);
        method.addParameter("digest", this.editDigest);
        int status = client.executeMethod(method);
        if (status != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
            method.getResponseBodyAsString();
        } else {
            br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            String readLine;
            while (((readLine = br.readLine()) != null)) {
                System.err.println(readLine);
            }
        }
        method.releaseConnection();
    } catch (Exception e) {
        //         this.messageTextArea.append(e.toString()+"\n");
        System.out.println("" + e);
        e.printStackTrace();
    }

}