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:com.alibaba.stonelab.toolkit.misc.Misc.java

public static void main(String[] args) throws Exception {
    PostMethod post = new PostMethod(URL_BOOK);
    post.addParameter("__VIEWSTATE", PARAM_VIEWSTATE);
    post.addParameter("__EVENTVALIDATION", PARAM_EVENTVALIDATION);
    post.addParameter("ctl00%24ContentPlaceHolder1%24tb_bookdate", "2010-08-12");
    post.addParameter("ctl00%24ContentPlaceHolder1%24DropDownList1", "10");
    post.addParameter("ctl00%24ContentPlaceHolder1%24DropDownList2", "00");
    post.addParameter("ctl00%24ContentPlaceHolder1%24DropDownList3", "21");
    post.addParameter("ctl00%24ContentPlaceHolder1%24DropDownList4", "00");
    post.addParameter("ctl00%24ContentPlaceHolder1%24rbl_ProjectorSelect", "");
    post.addParameter("ctl00%24ContentPlaceHolder1%24tb_comments", "");
    post.addParameter("ctl00%24ContentPlaceHolder1%24btn_booking", "");
    httpClient.executeMethod(post);//from  w w w. ja va2 s  .  c  o m
    System.out.println(post.getResponseBodyAsString());
    post.releaseConnection();
}

From source file:com.chiral.oauth.OAuthLoginUtil.java

public static void main(String[] args) throws Exception {
    // Step 0: Connect to SalesForce.
    OAuthConfiguration config;/*from w ww.j a  v a2  s. com*/
    File configFile = new File(args[0]);
    config = OAuthConfiguration.fromYaml(new FileInputStream(configFile));
    System.out.println("Getting a token");
    String tokenUrl = config.environment + "/services/oauth2/token";
    //TODO hparry use JAX-RS instead of Apache commons
    HttpClient httpclient = new HttpClient();
    PostMethod post = new PostMethod(tokenUrl);
    post.addParameter("grant_type", "password");
    post.addParameter("client_id", config.clientId);
    post.addParameter("client_secret", config.secret);
    post.addParameter("redirect_uri", config.redirectUri);
    post.addParameter("username", config.username);
    post.addParameter("password", config.password);

    try {
        httpclient.executeMethod(post);
        System.out.println(post.getResponseBodyAsString());
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        post.releaseConnection();
    }
}

From source file:com.discursive.jccook.httpclient.PostExample.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://www.discursive.com/cgi-bin/jccook/param_list.cgi";
    PostMethod method = new PostMethod(weblintURL);

    // Set parameters on POST   
    method.setParameter("test1", "Hello World");
    method.addParameter("test2", "This is a Form Submission");
    method.addParameter("Blah", "Whoop");
    method.addParameter(new NameValuePair("Blah", "Whoop2"));

    // Execute and print response
    client.executeMethod(method);//w  w  w  .j a v  a  2 s  .  com
    String response = method.getResponseBodyAsString();
    System.out.println(response);

    method.releaseConnection();
}

From source file:com.era7.bioinfo.annotation.AutomaticQualityControl.java

public static void main(String[] args) {

    if (args.length != 4) {
        System.out.println("This program expects four parameters: \n" + "1. Gene annotation XML filename \n"
                + "2. Reference protein set (.fasta)\n" + "3. Output TXT filename\n"
                + "4. Initial Blast XML results filename (the one used at the very beginning of the semiautomatic annotation process)\n");
    } else {/*from  w  w w .j av a 2 s .  c o  m*/

        BufferedWriter outBuff = null;

        try {

            File inFile = new File(args[0]);
            File fastaFile = new File(args[1]);
            File outFile = new File(args[2]);
            File blastFile = new File(args[3]);

            //Primero cargo todos los datos del archivo xml del blast
            BufferedReader buffReader = new BufferedReader(new FileReader(blastFile));
            StringBuilder stBuilder = new StringBuilder();
            String line = null;

            while ((line = buffReader.readLine()) != null) {
                stBuilder.append(line);
            }

            buffReader.close();
            System.out.println("Creating blastoutput...");
            BlastOutput blastOutput = new BlastOutput(stBuilder.toString());
            System.out.println("BlastOutput created! :)");
            stBuilder.delete(0, stBuilder.length());

            HashMap<String, String> blastProteinsMap = new HashMap<String, String>();
            ArrayList<Iteration> iterations = blastOutput.getBlastOutputIterations();
            for (Iteration iteration : iterations) {
                blastProteinsMap.put(iteration.getQueryDef().split("\\|")[1].trim(), iteration.toString());
            }
            //freeing some memory
            blastOutput = null;
            //------------------------------------------------------------------------

            //Initializing writer for output file
            outBuff = new BufferedWriter(new FileWriter(outFile));

            //reading gene annotation xml file.....
            buffReader = new BufferedReader(new FileReader(inFile));
            stBuilder = new StringBuilder();
            line = null;
            while ((line = buffReader.readLine()) != null) {
                stBuilder.append(line);
            }
            buffReader.close();

            XMLElement genesXML = new XMLElement(stBuilder.toString());
            //freeing some memory I don't need anymore
            stBuilder.delete(0, stBuilder.length());

            //reading file with the reference proteins set
            ArrayList<String> proteinsReferenceSet = new ArrayList<String>();
            buffReader = new BufferedReader(new FileReader(fastaFile));
            while ((line = buffReader.readLine()) != null) {
                if (line.charAt(0) == '>') {
                    proteinsReferenceSet.add(line.split("\\|")[1]);
                }
            }
            buffReader.close();

            Element pGenes = genesXML.asJDomElement().getChild(PredictedGenes.TAG_NAME);

            List<Element> contigs = pGenes.getChildren(ContigXML.TAG_NAME);

            System.out.println("There are " + contigs.size() + " contigs to be checked... ");

            outBuff.write("There are " + contigs.size() + " contigs to be checked... \n");
            outBuff.write("Proteins reference set: \n");
            for (String st : proteinsReferenceSet) {
                outBuff.write(st + ",");
            }
            outBuff.write("\n");

            for (Element elem : contigs) {
                ContigXML contig = new ContigXML(elem);

                //escribo el id del contig en el que estoy
                outBuff.write("Checking contig: " + contig.getId() + "\n");
                outBuff.flush();

                List<XMLElement> geneList = contig.getChildrenWith(PredictedGene.TAG_NAME);
                System.out.println("geneList.size() = " + geneList.size());

                int numeroDeGenesParaAnalizar = geneList.size() / FACTOR;
                if (numeroDeGenesParaAnalizar == 0) {
                    numeroDeGenesParaAnalizar++;
                }

                ArrayList<Integer> indicesUtilizados = new ArrayList<Integer>();

                outBuff.write("\nThe contig has " + geneList.size() + " predicted genes, let's analyze: "
                        + numeroDeGenesParaAnalizar + "\n");

                for (int j = 0; j < numeroDeGenesParaAnalizar; j++) {
                    int geneIndex;

                    boolean geneIsDismissed = false;
                    do {
                        geneIsDismissed = false;
                        geneIndex = (int) Math.round(Math.floor(Math.random() * geneList.size()));
                        PredictedGene tempGene = new PredictedGene(geneList.get(geneIndex).asJDomElement());
                        if (tempGene.getStatus().equals(PredictedGene.STATUS_DISMISSED)) {
                            geneIsDismissed = true;
                        }
                    } while (indicesUtilizados.contains(new Integer(geneIndex)) && geneIsDismissed);

                    indicesUtilizados.add(geneIndex);
                    System.out.println("geneIndex = " + geneIndex);

                    //Ahora hay que sacar el gen correspondiente al indice y hacer el control de calidad
                    PredictedGene gene = new PredictedGene(geneList.get(geneIndex).asJDomElement());

                    outBuff.write("\nAnalyzing gene with id: " + gene.getId() + " , annotation uniprot id: "
                            + gene.getAnnotationUniprotId() + "\n");
                    outBuff.write("eValue: " + gene.getEvalue() + "\n");

                    //--------------PETICION POST HTTP BLAST----------------------
                    PostMethod post = new PostMethod(BLAST_URL);
                    post.addParameter("program", "blastx");
                    post.addParameter("sequence", gene.getSequence());
                    post.addParameter("database", "uniprotkb");
                    post.addParameter("email", "ppareja@era7.com");
                    post.addParameter("exp", "1e-10");
                    post.addParameter("stype", "dna");

                    // execute the POST
                    HttpClient client = new HttpClient();
                    int status = client.executeMethod(post);
                    System.out.println("status post = " + status);
                    InputStream inStream = post.getResponseBodyAsStream();

                    String fileName = "jobid.txt";
                    FileOutputStream outStream = new FileOutputStream(new File(fileName));
                    byte[] buffer = new byte[1024];
                    int len;

                    while ((len = inStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();

                    //Once the file is created I just have to read one line in order to extract the job id
                    buffReader = new BufferedReader(new FileReader(new File(fileName)));
                    String jobId = buffReader.readLine();
                    buffReader.close();

                    System.out.println("jobId = " + jobId);

                    //--------------HTTP CHECK JOB STATUS REQUEST----------------------
                    GetMethod get = new GetMethod(CHECK_JOB_STATUS_URL + jobId);
                    String jobStatus = "";
                    do {

                        try {
                            Thread.sleep(1000);//sleep for 1000 ms                                
                        } catch (InterruptedException ie) {
                            //If this thread was intrrupted by nother thread
                        }

                        status = client.executeMethod(get);
                        //System.out.println("status get = " + status);

                        inStream = get.getResponseBodyAsStream();

                        fileName = "jobStatus.txt";
                        outStream = new FileOutputStream(new File(fileName));

                        while ((len = inStream.read(buffer)) != -1) {
                            outStream.write(buffer, 0, len);
                        }
                        outStream.close();

                        //Once the file is created I just have to read one line in order to extract the job id
                        buffReader = new BufferedReader(new FileReader(new File(fileName)));
                        jobStatus = buffReader.readLine();
                        //System.out.println("jobStatus = " + jobStatus);
                        buffReader.close();

                    } while (!jobStatus.equals(FINISHED_JOB_STATUS));

                    //Once I'm here the blast should've already finished

                    //--------------JOB RESULTS HTTP REQUEST----------------------
                    get = new GetMethod(JOB_RESULT_URL + jobId + "/out");

                    status = client.executeMethod(get);
                    System.out.println("status get = " + status);

                    inStream = get.getResponseBodyAsStream();

                    fileName = "jobResults.txt";
                    outStream = new FileOutputStream(new File(fileName));

                    while ((len = inStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();

                    //--------parsing the blast results file-----

                    TreeSet<GeneEValuePair> featuresBlast = new TreeSet<GeneEValuePair>();

                    buffReader = new BufferedReader(new FileReader(new File(fileName)));
                    while ((line = buffReader.readLine()) != null) {
                        if (line.length() > 3) {
                            String prefix = line.substring(0, 3);
                            if (prefix.equals("TR:") || prefix.equals("SP:")) {
                                String[] columns = line.split(" ");
                                String id = columns[1];
                                //System.out.println("id = " + id);

                                String e = "";

                                String[] arraySt = line.split("\\.\\.\\.");
                                if (arraySt.length > 1) {
                                    arraySt = arraySt[1].trim().split(" ");
                                    int contador = 0;
                                    for (int k = 0; k < arraySt.length && contador <= 2; k++) {
                                        String string = arraySt[k];
                                        if (!string.equals("")) {
                                            contador++;
                                            if (contador == 2) {
                                                e = string;
                                            }
                                        }

                                    }
                                } else {
                                    //Number before e-
                                    String[] arr = arraySt[0].split("e-")[0].split(" ");
                                    String numeroAntesE = arr[arr.length - 1];
                                    String numeroDespuesE = arraySt[0].split("e-")[1].split(" ")[0];
                                    e = numeroAntesE + "e-" + numeroDespuesE;
                                }

                                double eValue = Double.parseDouble(e);
                                //System.out.println("eValue = " + eValue);
                                GeneEValuePair g = new GeneEValuePair(id, eValue);
                                featuresBlast.add(g);
                            }
                        }
                    }

                    GeneEValuePair currentGeneEValuePair = new GeneEValuePair(gene.getAnnotationUniprotId(),
                            gene.getEvalue());

                    System.out.println("currentGeneEValuePair.id = " + currentGeneEValuePair.id);
                    System.out.println("currentGeneEValuePair.eValue = " + currentGeneEValuePair.eValue);
                    boolean blastContainsGene = false;
                    for (GeneEValuePair geneEValuePair : featuresBlast) {
                        if (geneEValuePair.id.equals(currentGeneEValuePair.id)) {
                            blastContainsGene = true;
                            //le pongo la e que tiene en el wu-blast para poder comparar
                            currentGeneEValuePair.eValue = geneEValuePair.eValue;
                            break;
                        }
                    }

                    if (blastContainsGene) {
                        outBuff.write("The protein was found in the WU-BLAST result.. \n");
                        //Una vez que se que esta en el blast tengo que ver que sea la mejor
                        GeneEValuePair first = featuresBlast.first();
                        outBuff.write("Protein with best eValue according to the WU-BLAST result: " + first.id
                                + " , " + first.eValue + "\n");
                        if (first.id.equals(currentGeneEValuePair.id)) {
                            outBuff.write("Proteins with best eValue match up \n");
                        } else {
                            if (first.eValue == currentGeneEValuePair.eValue) {
                                outBuff.write(
                                        "The one with best eValue is not the same protein but has the same eValue \n");
                            } else if (first.eValue > currentGeneEValuePair.eValue) {
                                outBuff.write(
                                        "The one with best eValue is not the same protein but has a worse eValue :) \n");
                            } else {
                                outBuff.write(
                                        "The best protein from BLAST has an eValue smaller than ours, checking if it's part of the reference set...\n");
                                //System.exit(-1);
                                if (proteinsReferenceSet.contains(first.id)) {
                                    //The protein is in the reference set and that shouldn't happen
                                    outBuff.write(
                                            "The protein was found on the reference set, checking if it belongs to the same contig...\n");
                                    String iterationSt = blastProteinsMap.get(gene.getAnnotationUniprotId());
                                    if (iterationSt != null) {
                                        outBuff.write(
                                                "The protein was found in the BLAST used at the beginning of the annotation process.\n");
                                        Iteration iteration = new Iteration(iterationSt);
                                        ArrayList<Hit> hits = iteration.getIterationHits();
                                        boolean contigFound = false;
                                        Hit errorHit = null;
                                        for (Hit hit : hits) {
                                            if (hit.getHitDef().indexOf(contig.getId()) >= 0) {
                                                contigFound = true;
                                                errorHit = hit;
                                                break;
                                            }
                                        }
                                        if (contigFound) {
                                            outBuff.write(
                                                    "ERROR: A hit from the same contig was find in the Blast file: \n"
                                                            + errorHit.toString() + "\n");
                                        } else {
                                            outBuff.write("There is no hit with the same contig! :)\n");
                                        }
                                    } else {
                                        outBuff.write(
                                                "The protein is NOT in the BLAST used at the beginning of the annotation process.\n");
                                    }

                                } else {
                                    //The protein was not found on the reference set so everything's ok
                                    outBuff.write(
                                            "The protein was not found on the reference, everything's ok :)\n");
                                }
                            }
                        }

                    } else {
                        outBuff.write("The protein was NOT found on the WU-BLAST !! :( \n");

                        //System.exit(-1);
                    }

                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                //closing outputfile
                outBuff.close();
            } catch (IOException ex) {
                Logger.getLogger(AutomaticQualityControl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
}

From source file:com.mogotest.ci.TestRunFactory.java

public static void create(final String apiKey, final String testPlanId, final String source) {
    final HttpClient client = new HttpClient();
    final String url = String.format("https://mogotest.com/api/v1/test_plans/%s/tests.json", testPlanId);
    final PostMethod post = new PostMethod(url);

    try {//  www .j  a  va 2s  .c o  m
        post.addParameter("user_credentials", apiKey);
        post.addParameter("source", source);
        client.executeMethod(post);
    } catch (final Exception e) {
        logger.log(Level.SEVERE, "Error creating Mogotest test run.", e);
    } finally {
        post.releaseConnection();
    }
}

From source file:com.swdouglass.joid.server.ReCaptcha.java

/**
 * This method posts the four parameters necessary to solve a
 * <a href="http://recaptcha.net/apidocs/captcha/">captcha</a>.
 * //  ww  w  .j a v a 2  s  . c o  m
 * @param privateKey Your recaptcha private key
 * @param remoteAddr The IP address of the end user
 * @param challenge The mangled text displayed
 * @param response Then end-user's interpretation of that text
 * @return null if successful, error message if not
 */
public static String check(String privateKey, String remoteAddr, String challenge, String response) {
    String message = null;
    String str = null;
    if (challenge == null || response == null) {
        message = "Challenge and response strings can't be null!";
    } else {
        try {

            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(VERIFY_URL);
            post.addParameter("privatekey", privateKey);
            post.addParameter("remoteip", remoteAddr);
            post.addParameter("challenge", challenge);
            post.addParameter("response", response);
            client.executeMethod(post);
            BufferedReader in = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
            str = in.readLine(); // read the first line of the response
            if (str == null) {
                message = "Null read from server."; // treat this as not verfied
            } else {
                boolean valid = "true".equals(str);
                if (!valid) {
                    str = in.readLine(); // get next line which has message
                    if (str.length() > 1) {
                        message = str;
                    } else {
                        message = "missing error message?";
                    }
                }
            }

        } catch (IOException ex) {
            log.error(ex);
            ex.printStackTrace();
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Response: " + str);
    }
    return message;
}

From source file:com.cisco.tbd.stec.client.ServerConnection.java

public static void pushDetectedThreat(AttackLogEntry logEntry) throws IOException {

    String request = "http://10.154.244.56/stec/insert_threats.php";
    HttpClient client = new HttpClient();

    PostMethod method = new PostMethod(request);

    // Add POST parameters
    method.addParameter("token", Runner.DEVICE_ID);

    method.addParameter("exchange", Runner.EXCHANGE_ID);

    method.addParameter("ip", logEntry.getAttackIp());

    method.addParameter("descr", logEntry.toString());

    method.addParameter("type", "dos");

    method.addParameter("level", logEntry.getPriorityLevel());

    // Send POST request
    int statusCode = client.executeMethod(method);
    ////w w w . j a v a2  s .com
    //        InputStream rstream = null;
    //
    //        rstream = method.getResponseBodyAsStream();
    //
    //        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    //
    //        String line;
    //
    //        while ((line = br.readLine()) != null) {
    //
    //            System.out.println(line);
    //
    //        }

    //        br.close();
    // Get the response body

}

From source file:de.mpg.imeji.presentation.util.LoginHelper.java

/**
 * Get handle of System administrator of eSciDoc instance.
 * //ww  w.  ja  va 2s .c  om
 * @return
 */
//    public static String loginSystemAdmin()
//    {
//        String handle = null;
//        try
//        {
//            handle = login(PropertyReader.getProperty("framework.admin.username"),
//                    PropertyReader.getProperty("framework.admin.password"));
//        }
//        catch (Exception e)
//        {
//            sessionBean = (SessionBean)BeanHelper.getSessionBean(SessionBean.class);
//            BeanHelper
//                    .info(sessionBean.getLabel("error") + ", wrong administrator user. Check config file or FW: " + e);
//            logger.error("Error escidoc admin login", e);
//        }
//        return handle;
//    }

public static String login(String userName, String password) throws Exception {
    String frameworkUrl = PropertyReader.getProperty("escidoc.framework_access.framework.url");
    StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//");
    tokens.nextToken();
    StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":");
    String host = hostPort.nextToken();
    int port = 80;
    if (hostPort.hasMoreTokens()) {
        port = Integer.parseInt(hostPort.nextToken());
    }
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().closeIdleConnections(1000);
    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", userName);
    login.addParameter("j_password", password);
    try {
        client.executeMethod(login);
    } catch (Exception e) {
        throw new RuntimeException("Error login in " + frameworkUrl + "  status: " + login.getStatusCode()
                + " - " + login.getStatusText());
    }
    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());
    Cookie sessionCookie = logoncookies[0];
    PostMethod postMethod = new PostMethod("/aa/login");
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);
    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + postMethod.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:net.duckling.ddl.web.bean.ClbHelper.java

public static String getClbToken(int docId, int version, Properties properties) {
    HttpClient client = HttpClientUtil.getHttpClient(LOGGER);
    PostMethod method = new PostMethod(getClbTokenUrl(properties));
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    method.addParameter("appname", properties.getProperty("duckling.clb.aone.user"));
    method.addParameter("docid", docId + "");
    method.addParameter("version", version + "");
    try {//  w  w w .  j  a va  2  s  .  c  o  m
        method.addParameter("password",
                Base64.encodeBytes(properties.getProperty("duckling.clb.aone.password").getBytes("utf-8")));
    } catch (IllegalArgumentException | UnsupportedEncodingException e) {

    }
    try {
        int status = client.executeMethod(method);
        String responseString = null;
        if (status < 400) {
            responseString = method.getResponseBodyAsString();
            org.json.JSONObject j = new org.json.JSONObject(responseString);
            Object st = j.get("status");
            if ("failed".equals(st)) {
                LOGGER.error("?clb token?");
                return null;
            } else {
                return j.get("pf").toString();
            }
        } else {
            LOGGER.error("STAUTS:" + status + ";MESSAGE:" + responseString);
        }
    } catch (HttpException e) {
        LOGGER.error("", e);
    } catch (IOException e) {
        LOGGER.error("", e);
    } catch (ParseException e) {
        LOGGER.error("", e);
    }
    return null;
}

From source file:de.mpg.mpdl.inge.util.AdminHelper.java

/**
 * Logs in the given user with the given password.
 * //from w w w  .  j a v a2  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
 */
public static String loginUser(String userid, String password)
        throws HttpException, IOException, ServiceException, URISyntaxException {
    String frameworkUrl = PropertyReader.getLoginUrl();

    int delim1 = frameworkUrl.indexOf("//");
    int delim2 = frameworkUrl.indexOf(":", delim1);

    String host;
    int port;

    if (delim2 > 0) {
        host = frameworkUrl.substring(delim1 + 2, delim2);
        port = Integer.parseInt(frameworkUrl.substring(delim2 + 1));
    } else {
        host = frameworkUrl.substring(delim1 + 2);
        port = 80;
    }
    HttpClient client = new HttpClient();

    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);

    ProxyHelper.executeMethod(client, 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(frameworkUrl + "/aa/login");
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    ProxyHelper.executeMethod(client, 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.getDecoder().decode(location.substring(index + 1, location.length())));
            // System.out.println("location: "+location);
            // System.out.println("handle: "+userHandle);
        }
    }

    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}