Example usage for org.apache.commons.httpclient.methods GetMethod setQueryString

List of usage examples for org.apache.commons.httpclient.methods GetMethod setQueryString

Introduction

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

Prototype

public void setQueryString(String queryString) 

Source Link

Usage

From source file:de.laeubisoft.tools.ant.validation.W3CCSSValidationTask.java

/**
 * Creates the actual request to the validation server for a given
 * {@link URL} and returns an inputstream the result can be read from
 * /* w w  w  . j ava2s.c  o  m*/
 * @param uriToCheck
 *            the URL to check (or <code>null</code> if text or file should
 *            be used as input
 * @return the stream to read the response from
 * @throws IOException
 *             if unrecoverable communication error occurs
 * @throws BuildException
 *             if server returned unexspected results
 */
private InputStream buildConnection(final URL uriToCheck) throws IOException, BuildException {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("output", VALIDATOR_FORMAT_OUTPUT));
    if (uriToCheck != null) {
        params.add(new NameValuePair("uri", uriToCheck.toString()));
    } else {
        if (text != null) {
            params.add(new NameValuePair("text", text));
        }
    }
    if (usermedium != null) {
        params.add(new NameValuePair("usermedium", usermedium));
    }
    if (profile != null) {
        params.add(new NameValuePair("profile", profile));
    }
    if (lang != null) {
        params.add(new NameValuePair("lang", lang));
    }
    if (warning != null) {
        params.add(new NameValuePair("warning", warning));
    }
    HttpClient httpClient = new HttpClient();
    HttpMethodBase method;
    if (uriToCheck != null) {
        //URIs must be checked via traditonal GET...
        GetMethod getMethod = new GetMethod(validator);
        getMethod.setQueryString(params.toArray(new NameValuePair[0]));
        method = getMethod;
    } else {
        PostMethod postMethod = new PostMethod(validator);
        if (text != null) {
            //Text request must be multipart encoded too...
            postMethod.setRequestEntity(new MultipartRequestEntity(Tools.nvToParts(params).toArray(new Part[0]),
                    postMethod.getParams()));
        } else {
            //Finally files must be checked with multipart-forms....
            postMethod.setRequestEntity(
                    Tools.createFileUpload(file, "file", null, params, postMethod.getParams()));
        }
        method = postMethod;
    }
    int result = httpClient.executeMethod(method);
    if (result == HttpStatus.SC_OK) {
        return method.getResponseBodyAsStream();
    } else {
        throw new BuildException("Server returned " + result + " " + method.getStatusText());
    }

}

From source file:com.gisgraphy.servlet.FulltextServletTest.java

@Test
public void testFulltextServletShouldReturnCorrectStatusCode() {
    String url = fulltextServletUrl + FULLTEXT_SERVLET_CONTEXT + "/fulltextsearch";

    // String result;
    String queryString;//  w  ww.  ja  v  a2  s  . co m
    GetMethod get = null;
    try {
        queryString = "q=&format=" + OutputFormat.JSON.toString();
        HttpClient client = new HttpClient();
        get = new GetMethod(url);

        get.setQueryString(queryString);
        client.executeMethod(get);
        // result = get.getResponseBodyAsString();

        assertEquals("status code is not correct ", 500, get.getStatusCode());

    } catch (IOException e) {
        fail("An exception has occured " + e.getMessage());
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }

}

From source file:com.gisgraphy.servlet.FulltextServletTest.java

@Test
public void testFulltextServletShouldReturnCorrectXMLError() {

    String url = fulltextServletUrl + FULLTEXT_SERVLET_CONTEXT + "/fulltextsearch";

    String result;//from  w  w w  . ja v a2s .c o  m
    String queryString;
    OutputFormat format = OutputFormat.XML;
    GetMethod get = null;
    try {
        queryString = "q=&format=" + format.getParameterValue();
        HttpClient client = new HttpClient();
        get = new GetMethod(url);

        get.setQueryString(queryString);
        client.executeMethod(get);
        result = get.getResponseBodyAsString().trim();

        // JsTester
        String expected = ResourceBundle.getBundle(Constants.BUNDLE_ERROR_KEY).getString("error.emptyQuery");
        FeedChecker.checkFulltextErrorXML(result, expected);
    } catch (IOException e) {
        fail("An exception has occured " + e.getMessage());
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }

}

From source file:com.gisgraphy.servlet.FulltextServletTest.java

@Test
public void testFulltextServletShouldReturnCorrectContentType() {
    String url = fulltextServletUrl + FULLTEXT_SERVLET_CONTEXT + "/fulltextsearch";

    // String result;
    String queryString;//from  w w  w. j  a v  a  2s. co m
    for (OutputFormat format : OutputFormat.values()) {
        GetMethod get = null;
        try {
            queryString = "q=test&format=" + format.toString();
            HttpClient client = new HttpClient();
            get = new GetMethod(url);

            get.setQueryString(queryString);
            client.executeMethod(get);
            // result = get.getResponseBodyAsString();

            Header contentType = get.getResponseHeader("Content-Type");
            if (OutputFormatHelper.isFormatSupported(format, GisgraphyServiceType.FULLTEXT)) {
                assertTrue(contentType.getValue().equals(format.getContentType()));
            }
        } catch (IOException e) {
            fail("An exception has occured " + e.getMessage());
        } finally {
            if (get != null) {
                get.releaseConnection();
            }
        }
    }

}

From source file:com.gisgraphy.servlet.GeolocServletTest.java

@Test
public void testShouldReturnCorrectXMLError() {

    String url = geolocServletUrl + GEOLOC_SERVLET_CONTEXT + "/fulltextsearch";

    String result;/*from w w w  .  ja  va 2 s .c  o m*/
    String queryString;
    OutputFormat format = OutputFormat.XML;
    GetMethod get = null;
    try {
        queryString = "format=" + format.getParameterValue();
        HttpClient client = new HttpClient();
        get = new GetMethod(url);

        get.setQueryString(queryString);
        client.executeMethod(get);
        result = get.getResponseBodyAsString().trim();

        String expected = ResourceBundle.getBundle(Constants.BUNDLE_ERROR_KEY).getString("error.emptyLatLong");
        FeedChecker.assertQ("The XML error is not correct", result, "//error[.='" + expected + "']");
    } catch (IOException e) {
        fail("An exception has occured " + e.getMessage());
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }

}

From source file:com.gisgraphy.servlet.ReverseGeocodingServletTest.java

@Test
public void testShouldReturnCorrectXMLError() {

    String url = reverseGeocodingServletUrl + REVERSE_GECODOING_SERVLET_CONTEXT + "/search";

    String result;//  w w w. ja v a 2 s  .c o m
    String queryString;
    OutputFormat format = OutputFormat.XML;
    GetMethod get = null;
    try {
        queryString = "format=" + format.getParameterValue();
        HttpClient client = new HttpClient();
        get = new GetMethod(url);

        get.setQueryString(queryString);
        client.executeMethod(get);
        result = get.getResponseBodyAsString().trim();

        String expected = ResourceBundle.getBundle(Constants.BUNDLE_ERROR_KEY).getString("error.emptyLatLong");
        FeedChecker.assertQ("The XML error is not correct", result, "//error[.='" + expected + "']");
    } catch (IOException e) {
        fail("An exception has occured " + e.getMessage());
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }

}

From source file:net.neurowork.cenatic.centraldir.workers.xml.XmlTokenImporter.java

public String getXmlToken() {
    String token = null;/*w w  w  . java  2 s .com*/
    HttpClient httpclient = XMLRestWorker.getHttpClient();
    GetMethod get = new GetMethod(restUrl.getTokenUrl());
    get.addRequestHeader("Accept", "application/xml");

    NameValuePair userParam = new NameValuePair(XMLRestWorker.USERNAME_PARAM, satelite.getUser());
    NameValuePair passwordParam = new NameValuePair(XMLRestWorker.PASSWORD_PARAM, satelite.getPassword());
    NameValuePair[] params = new NameValuePair[] { userParam, passwordParam };

    get.setQueryString(params);
    try {
        int statusCode = httpclient.executeMethod(get);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: " + get.getStatusLine());
        }
        token = XMLRestWorker.parseToken(get.getResponseBodyAsString());
    } catch (HttpException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
        logger.error(e.getMessage());
    } catch (SAXException e) {
        logger.error(e.getMessage());
    } finally {
        get.releaseConnection();
    }
    return token;
}

From source file:eu.learnpad.core.impl.mv.XwikiBridgeInterfaceRestResource.java

@Override
public VerificationId startVerification(String modelSetId, String verificationType) throws LpRestException {
    HttpClient httpClient = this.getHttpClient();
    String uri = String.format("%s/learnpad/mv/bridge/startverification", this.restPrefix);
    GetMethod getMethod = new GetMethod(uri);
    getMethod.addRequestHeader("Accept", "application/xml");

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("modelsetid", modelSetId);
    queryString[1] = new NameValuePair("verificationtype", verificationType);

    getMethod.setQueryString(queryString);

    try {//from w  w w .j  av  a  2  s  .  c o m
        httpClient.executeMethod(getMethod);
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }

    VerificationId verificationId = null;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(VerificationId.class);
        InputStream retIs = getMethod.getResponseBodyAsStream();
        verificationId = (VerificationId) jaxbContext.createUnmarshaller().unmarshal(retIs);
    } catch (Exception e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }

    return verificationId;
}

From source file:net.neurowork.cenatic.centraldir.workers.XMLPushTest.java

@Test
public void testPushOrganizacion() {
    GetMethod get = new GetMethod(restUrl.getTokenUrl());
    get.addRequestHeader("Accept", "application/xml");

    NameValuePair userParam = new NameValuePair(USERNAME_PARAM, user);
    NameValuePair passwordParam = new NameValuePair(PASSWORD_PARAM, password);
    NameValuePair[] params = new NameValuePair[] { userParam, passwordParam };

    get.setQueryString(params);

    try {/*from   w  w w  .j a  v a  2s.  co  m*/
        int result = httpclient.executeMethod(get);
        logger.info("Response status code: " + result);
        logger.info("Response body: ");
        logger.info(get.getResponseBodyAsString());

        String token = XMLRestWorker.parseToken(get.getResponseBodyAsString());
        if (token != null) {
            pushOrganization(token);
        }
    } catch (HttpException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
        logger.error(e.getMessage());
    } catch (SAXException e) {
        logger.error(e.getMessage());
    } finally {
        get.releaseConnection();
    }

}

From source file:com.adobe.translation.google.impl.TranslationServiceImpl.java

public String translate(String text, String src, String dst) {
    GetMethod get = new GetMethod(GOOGLE_API_V2_URI);
    List<NameValuePair> query = new LinkedList<NameValuePair>();
    query.add(new NameValuePair("key", key));
    if (src != null && src.length() > 0) {
        query.add(new NameValuePair("source", src));
    }/*from   w  w  w.ja  v a 2s .com*/
    query.add(new NameValuePair("target", dst));
    query.add(new NameValuePair("q", text));
    get.setQueryString(query.toArray(new NameValuePair[query.size()]));
    try {
        int code = httpClient.executeMethod(get);
        if (code != 200) {
            log.error("Unable to translate text. Server responded {}.", code);
            log.error("Response body: {}", get.getResponseBodyAsString());
        } else {
            // we just concatenate the texts
            StringBuilder ret = new StringBuilder();
            JSONObject json = new JSONObject(get.getResponseBodyAsString());
            JSONObject data = json.getJSONObject("data");
            JSONArray translations = data.getJSONArray("translations");
            for (int i = 0; i < translations.length(); i++) {
                JSONObject translation = translations.getJSONObject(i);
                ret.append(translation.getString("translatedText"));
            }
            return ret.toString();
        }
    } catch (HttpException e) {
        log.error("Error while translating.", e);
    } catch (JSONException e) {
        log.error("Error while translating.", e);
    } catch (IOException e) {
        log.error("Error while translating.", e);
    } finally {
        get.releaseConnection();
    }
    return "";
}