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

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

Introduction

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

Prototype

public PostMethod(String paramString) 

Source Link

Usage

From source file:com.mycompany.jaxrsexample.client.Client.java

public static void main(String args[]) throws Exception {
    // Sent HTTP GET request to query all students info

    System.out.println("Invoking server through HTTP GET to query all students info");
    URL url = new URL("http://localhost:9000/studentservice/students");
    InputStream in = url.openStream();
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP GET request to query student info
    System.out.println("Sent HTTP GET request to query customer info");
    url = new URL("http://localhost:9000/studentservice/students/1");
    in = url.openStream();// w  w w. jav a 2 s  . c o m
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP PUT request to update student info
    System.out.println("\n");
    System.out.println("Sent HTTP PUT request to update student info");
    Client client = new Client();
    String inputFile = client.getClass().getResource("/update_student.xml").getFile();
    URIResolver resolver = new URIResolver(inputFile);
    File input = new File(resolver.getURI());
    PutMethod put = new PutMethod("http://localhost:9000/studentservice/students");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(put);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    // Sent HTTP POST request to add student
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add student");
    inputFile = client.getClass().getResource("/add_student.xml").getFile();
    resolver = new URIResolver(inputFile);
    input = new File(resolver.getURI());
    PostMethod post = new PostMethod("http://localhost:9000/studentservice/students");
    post.addRequestHeader("Accept", "text/xml");
    entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(post);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }

    System.out.println("\n");
    System.exit(0);
}

From source file:edu.techseekers.training.client.Client.java

public static void main(String args[]) throws Exception {
    // Sent HTTP GET request to query all customer info
    /*//from www  . j  a  v a  2  s .  c o m
     * URL url = new URL("http://localhost:9000/customers");
     * System.out.println("Invoking server through HTTP GET to query all
     * customer info"); InputStream in = url.openStream(); StreamSource
     * source = new StreamSource(in); printSource(source);
     */

    // Sent HTTP GET request to query customer info
    System.out.println("Sent HTTP GET request to query customer info");
    URL url = new URL("http://localhost:9000/customerservice/customers/123");
    InputStream in = url.openStream();
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP GET request to query sub resource product info
    System.out.println("\n");
    System.out.println("Sent HTTP GET request to query sub resource product info");
    url = new URL("http://localhost:9000/customerservice/orders/223/products/323");
    in = url.openStream();
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP PUT request to update customer info
    System.out.println("\n");
    System.out.println("Sent HTTP PUT request to update customer info");
    Client client = new Client();
    String inputFile = client.getClass().getResource("/update_customer.xml").getFile();
    URIResolver resolver = new URIResolver(inputFile);
    File input = new File(resolver.getURI());
    PutMethod put = new PutMethod("http://localhost:9000/customerservice/customers");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(put);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    // Sent HTTP POST request to add customer
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add customer");
    inputFile = client.getClass().getResource("/add_customer.xml").getFile();
    resolver = new URIResolver(inputFile);
    input = new File(resolver.getURI());
    PostMethod post = new PostMethod("http://localhost:9000/customerservice/customers");
    post.addRequestHeader("Accept", "text/xml");
    entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(post);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }

    System.out.println("\n");
    System.exit(0);
}

From source file:main.java.demo.jaxrs.client.Client.java

public static void main(String args[]) throws Exception {
    // Sent HTTP GET request to query all customer info
    /*//from w  w  w  .jav a 2 s. co m
     * URL url = new URL("http://localhost:9000/customers");
     * System.out.println("Invoking server through HTTP GET to query all
     * customer info"); InputStream in = url.openStream(); StreamSource
     * source = new StreamSource(in); printSource(source);
     */

    // Sent HTTP GET request to query customer info
    System.out.println("Sent HTTP GET request to query customer info");
    URL url = new URL("http://localhost:8989/RestFull/service1/customerservice/customers/123");
    InputStream in = url.openStream();
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP GET request to query sub resource product info
    System.out.println("\n");
    System.out.println("Sent HTTP GET request to query sub resource product info");
    url = new URL("http://localhost:9000/customerservice/orders/223/products/323");
    in = url.openStream();
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP PUT request to update customer info
    System.out.println("\n");
    System.out.println("Sent HTTP PUT request to update customer info");
    Client client = new Client();
    String inputFile = client.getClass().getResource("update_customer.xml").getFile();
    URIResolver resolver = new URIResolver(inputFile);
    File input = new File(resolver.getURI());
    PutMethod put = new PutMethod("http://localhost:9000/customerservice/customers");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(put);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    // Sent HTTP POST request to add customer
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add customer");
    inputFile = client.getClass().getResource("add_customer.xml").getFile();
    resolver = new URIResolver(inputFile);
    input = new File(resolver.getURI());
    PostMethod post = new PostMethod("http://localhost:9000/customerservice/customers");
    post.addRequestHeader("Accept", "text/xml");
    entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(post);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }

    System.out.println("\n");
    System.exit(0);
}

From source file:main.java.client.Client.java

public static void main(String args[]) throws Exception {
    // Sent HTTP GET request to query all customer info
    /*/*from   w ww.j av  a2 s  .  c  o  m*/
     * URL url = new URL("http://localhost:9000/customers");
     * System.out.println("Invoking server through HTTP GET to query all
     * customer info"); InputStream in = url.openStream(); StreamSource
     * source = new StreamSource(in); printSource(source);
     */

    // Sent HTTP GET request to query customer info
    System.out.println("Sent HTTP GET request to query customer info");
    URL url = new URL("http://localhost:8080/authenticate/customers/123");
    InputStream in = url.openStream();
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP GET request to query sub resource product info
    System.out.println("\n");
    System.out.println("Sent HTTP GET request to query sub resource product info");
    url = new URL("http://localhost:9000/authenticate/orders/223/products/323");
    in = url.openStream();
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP PUT request to update customer info
    System.out.println("\n");
    System.out.println("Sent HTTP PUT request to update customer info");
    Client client = new Client();
    String inputFile = client.getClass().getResource("/update_customer.xml").getFile();
    URIResolver resolver = new URIResolver(inputFile);
    File input = new File(resolver.getURI());
    PutMethod put = new PutMethod("http://localhost:9000/authenticate/customers");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(put);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    // Sent HTTP POST request to add customer
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add customer");
    inputFile = client.getClass().getResource("/add_customer.xml").getFile();
    resolver = new URIResolver(inputFile);
    input = new File(resolver.getURI());
    PostMethod post = new PostMethod("http://localhost:9000/authenticate/customers");
    post.addRequestHeader("Accept", "text/xml");
    entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(post);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }

    // Sent HTTP POST request to add json customer
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add json customer");
    String inputFilej = client.getClass().getResource("/add_customer.json").getFile();
    URIResolver resolverj = new URIResolver(inputFilej);
    File inputj = new File(resolverj.getURI());
    PostMethod postj = new PostMethod("http://localhost:9000/authenticate/customersjson");
    postj.addRequestHeader("Accept", "application/json");
    RequestEntity entityj = new FileRequestEntity(inputj, "application/json; charset=ISO-8859-1");
    postj.setRequestEntity(entityj);
    HttpClient httpclientj = new HttpClient();

    try {
        int resultj = httpclientj.executeMethod(postj);
        System.out.println("Response status code json: " + resultj);
        System.out.println("Response body json: ");
        System.out.println(postj.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        postj.releaseConnection();
    }
    System.out.println("\n");
    System.exit(0);
}

From source file:com.djimenez.tuenti.example.FormLoginDemo.java

public static void main(final String[] args) throws Exception {

    final HttpClient client = new HttpClient();

    client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    // 'developer.java.sun.com' has cookie compliance problems
    // Their session cookie's domain attribute is in violation of the RFC2109
    // We have to resort to using compatibility cookie policy

    final GetMethod authget = new GetMethod(LOGON_PATH);
    authget.setFollowRedirects(true);/*from w  w  w  .j  av a2 s  . c o  m*/

    client.executeMethod(authget);
    System.out.println("Login form get: " + authget.getStatusLine().toString());
    // release any connection resources used by the method
    authget.releaseConnection();
    // See if we got any cookies
    final CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    final Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
            client.getState().getCookies());
    System.out.println("Initial set of cookies:");

    checkCookies(initcookies);

    final PostMethod authpost = new PostMethod(LOGON_PATH);

    // Prepare login parameters
    final NameValuePair action = new NameValuePair("action", "do_login");
    final NameValuePair url = new NameValuePair("url", "/?m=Login&func=do_login");
    final NameValuePair userid = new NameValuePair("email", "david.jimenez19%40gmail.com");
    final NameValuePair password = new NameValuePair("input_password", "linda1");
    final NameValuePair timeZone = new NameValuePair("timezone", "1");
    final NameValuePair timeStamp = new NameValuePair("timezone", "13034395121");

    authpost.setRequestBody(new NameValuePair[] { action, url, userid, password, timeZone, timeStamp });

    client.executeMethod(authpost);

    System.out.println("Login form post: " + authpost.getStatusLine().toString());
    // release any connection resources used by the method
    authpost.releaseConnection();
    // See if we got any cookies
    // The only way of telling whether logon succeeded is
    // by finding a session cookie
    final Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
            client.getState().getCookies());
    System.out.println("Logon cookies:" + logoncookies);

    checkCookies(logoncookies);

    manageRequest(client, authpost);
}

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 ww  w. j  a  v a 2 s  .c om

        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:dk.statsbiblioteket.doms.licensemodule.integrationtest.HttpClientPoster.java

public static String postJSON(String url, String content) throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Dokumentleveringweb XML client");

    BufferedReader br = null;/*from   w  ww.j  ava 2  s  .  c  o  m*/

    //TODO property
    PostMethod method = new PostMethod(url);

    method.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
    method.setRequestBody(content); // How to do this a non-deprecated way?

    try {
        int httpCode = client.executeMethod(method);
        br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));

        String readLine;
        StringBuilder response = new StringBuilder();
        while (((readLine = br.readLine()) != null)) {
            response.append(readLine);

        }
        return response.toString();

    } catch (Exception e) {
        throw e;
    } finally {
        method.releaseConnection();
        if (br != null)
            try {
                br.close();
            } catch (Exception fe) {
                fe.printStackTrace();
            }
    }

}

From source file:com.leosys.core.utils.SendMessage.java

public static String postMessage(String phoneNo, String sendText) throws IOException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("http://sms.webchinese.cn/web_api/");
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");// ?    
    NameValuePair[] data = { new NameValuePair("Uid", "fanyy"), // ??    
            new NameValuePair("Key", "694de3e5ca9f7015eaef"), // ??,    
            new NameValuePair("smsMob", phoneNo), // ??    
            new NameValuePair("smsText", sendText + "??") };//  
    post.setRequestBody(data);/*w  w w .j a v a2  s.co  m*/

    client.executeMethod(post);
    Header[] headers = post.getResponseHeaders();
    int statusCode = post.getStatusCode();
    System.out.println("statusCode:" + statusCode);
    for (Header h : headers) {
        System.out.println(h.toString());
    }
    String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
    System.out.println(result);
    post.releaseConnection();
    return result;
}

From source file:com.oneapm.base.tools.UrlPostMethod.java

public static void urlPostMethod(String url, String json) {

    HttpClient httpClient = new HttpClient();
    PostMethod method = new PostMethod(url);
    try {/* ww w .j av  a  2  s  . c  o m*/
        if (json != null && !json.trim().equals("")) {
            RequestEntity requestEntity = new StringRequestEntity(json, "application/x-www-form-urlencoded",
                    "utf-8");
            method.setRequestEntity(requestEntity);
        }
        long startTime = System.currentTimeMillis();
        int x = httpClient.executeMethod(method);
        long elapsedTime = System.currentTimeMillis();

        System.out.println(x + ":" + (elapsedTime - startTime));

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
}

From source file:com.pieframework.runtime.utils.CampfireNotifier.java

public static boolean notify(String msg, String url, String user, String password) {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(url);

    // stuff the Authorization request header
    byte[] encodedPassword = (user + ":" + password).getBytes();
    BASE64Encoder encoder = new BASE64Encoder();
    post.setRequestHeader("Authorization", "Basic " + encoder.encode(encodedPassword));

    try {/*  w  w w .j  av a2  s.c  o  m*/
        RequestEntity entity = new StringRequestEntity("<message><body>" + msg + "</body></message>",
                "application/xml", "UTF-8");
        post.setRequestEntity(entity);
        client.executeMethod(post);
        String responseMsg = "httpStatus: " + post.getStatusCode() + " " + "Content-type: "
                + post.getResponseHeader("Content-Type") + " " + post.getResponseBodyAsString();
        Configuration.log().info(responseMsg);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return true;
}