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:org.intalio.tempo.workflow.tas.nuxeo.NuxeoStorageStrategy.java

/**
 * Creates a folder in nuxeo. We could expand that to create other things
 * like comments, ... This takes the place where to create the folder, and
 * the name of the folder to create, stored as dublin:core metadata
 *//*from  w  w  w .  jav  a  2  s .c o  m*/
private String createFolder(String repoUri, String repoName) throws Exception {
    GetMethod method = new GetMethod(repoUri + REST_CREATE);
    log.debug("NUXEO CREATE FOLDER " + repoUri + " " + repoName);
    NameValuePair[] pairs = new NameValuePair[2];
    pairs[0] = new NameValuePair(NUXEO_DOC_TYPE, NUXEO_FOLDER);
    pairs[1] = new NameValuePair(NUXEO_DUBLINCORE_TITLE, repoName);
    method.setQueryString(pairs);
    httpclient.executeMethod(method);
    String value = method.getResponseBodyAsString();
    method.releaseConnection();
    OMElement omEle = buildOMElement(value);
    String docRef = omEle.getFirstChildWithName(new QName(STRING_EMPTY, NUXEO_DOC_REF)).getText();
    return docRef;
}

From source file:org.isisaddons.wicket.gmap3.cpt.service.LocationLookupService.java

@Programmatic
public Location lookup(final String description) {

    final GetMethod get = new GetMethod(BASEURL + MODE);
    try {//from  w  w  w .j  ava 2  s .co m
        final String query = URIUtil.encodeQuery("?address=" + description + "&sensor=false");
        get.setQueryString(query);

        httpclient.executeMethod(get);

        final String xml = get.getResponseBodyAsString();
        final SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(new StringReader(xml));
        Element root = doc.getRootElement();
        String lat = root.getChild("result").getChild("geometry").getChild("location").getChildTextTrim("lat");
        String lon = root.getChild("result").getChild("geometry").getChild("location").getChildTextTrim("lng");
        return Location.fromString(lat + ";" + lon);
    } catch (Exception ex) {
        return null;
    }
}

From source file:org.jahia.services.translation.microsoft.MicrosoftTranslationProvider.java

/**
 * Calls the Microsoft Translator Translate GET method to translate a single text.
 *
 *
 * @param text a text to translate//from ww w.ja  va  2s .c o m
 * @param srcLanguage the source language code
 * @param destLanguage the destination language code
 * @param isHtml is the text html or plain text
 * @param site the site
 * @param uiLocale
 * @return the translated text
 * @throws TranslationException
 */
public String translate(String text, String srcLanguage, String destLanguage, boolean isHtml, JCRSiteNode site,
        Locale uiLocale) throws TranslationException {
    String accessToken = authenticate(site, uiLocale);
    if (accessToken == null) {
        throw new TranslationException(
                Messages.get(module, "siteSettings.translation.microsoft.failedToAuthenticate", uiLocale));
    }
    GetMethod method = new GetMethod(translateUrl);
    method.setRequestHeader("Authorization", "Bearer " + accessToken);
    method.setQueryString(new NameValuePair[] { new NameValuePair("text", text),
            new NameValuePair("from", srcLanguage), new NameValuePair("to", destLanguage),
            new NameValuePair("contentType", isHtml ? "text/html" : "text/plain") });
    int returnCode;
    String translatedText;
    try {
        try {
            returnCode = httpClientService.getHttpClient().executeMethod(method);
        } catch (Exception e) {
            throw new TranslationException(
                    Messages.get(module, "siteSettings.translation.microsoft.failedToCallService", uiLocale));
        }
        if (returnCode != HttpStatus.SC_OK) {
            throw new TranslationException(
                    Messages.getWithArgs(ResourceBundles.get(module, uiLocale),
                            "siteSettings.translation.microsoft.errorWithCode", returnCode),
                    getResponseBodyAsStringQuietly(method));
        }
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(method.getResponseBodyAsStream());
            translatedText = document.getElementsByTagName("string").item(0).getTextContent();
        } catch (Exception e) {
            throw new TranslationException(
                    Messages.get(module, "siteSettings.translation.microsoft.failedToParse", uiLocale));
        }
    } finally {
        method.releaseConnection();
    }
    return translatedText;
}

From source file:org.jboss.as.quickstarts.resteasyspring.test.ResteasySpringTest.java

@Test
public void testHelloSpringResource() throws Exception {
    HttpClient client = new HttpClient();

    {//from   ww  w  . jav a2s  . c o m
        GetMethod method = new GetMethod("http://localhost:8080/jboss-spring-resteasy/hello");
        NameValuePair[] params = { new NameValuePair("name", "JBoss Developer") };
        method.setQueryString(params);
        int status = client.executeMethod(method);
        Assert.assertEquals(HttpResponseCodes.SC_OK, status);
        Assert.assertTrue(method.getResponseBodyAsString().contains("JBoss Developer"));
        method.releaseConnection();
    }
    {
        GetMethod method = new GetMethod("http://localhost:8080/jboss-spring-resteasy/basic");
        int status = client.executeMethod(method);
        Assert.assertEquals(HttpResponseCodes.SC_OK, status);
        Assert.assertEquals("basic", method.getResponseBodyAsString());
        method.releaseConnection();
    }
    {
        PutMethod method = new PutMethod("http://localhost:8080/jboss-spring-resteasy/basic");
        method.setRequestEntity(new StringRequestEntity("basic", "text/plain", null));
        int status = client.executeMethod(method);
        Assert.assertEquals(204, status);
        method.releaseConnection();
    }
    {
        GetMethod method = new GetMethod("http://localhost:8080/jboss-spring-resteasy/queryParam");
        NameValuePair[] params = { new NameValuePair("param", "hello world") };
        method.setQueryString(params);
        int status = client.executeMethod(method);
        Assert.assertEquals(HttpResponseCodes.SC_OK, status);
        Assert.assertEquals("hello world", method.getResponseBodyAsString());
        method.releaseConnection();
    }
    {
        GetMethod method = new GetMethod(
                "http://localhost:8080/jboss-spring-resteasy/matrixParam;param=matrix");
        int status = client.executeMethod(method);
        Assert.assertEquals(HttpResponseCodes.SC_OK, status);
        Assert.assertEquals("matrix", method.getResponseBodyAsString());
        method.releaseConnection();
    }
    {
        GetMethod method = new GetMethod("http://localhost:8080/jboss-spring-resteasy/uriParam/1234");
        int status = client.executeMethod(method);
        Assert.assertEquals(HttpResponseCodes.SC_OK, status);
        Assert.assertEquals("1234", method.getResponseBodyAsString());
        method.releaseConnection();
    }
}

From source file:org.jboss.as.quickstarts.resteasyspring.test.ResteasySpringTest.java

@Test
public void testLocatingResource() throws Exception {
    HttpClient client = new HttpClient();

    {//from w ww. j a v a 2 s. c  o m
        GetMethod method = new GetMethod("http://localhost:8080/jboss-spring-resteasy/locating/hello");
        NameValuePair[] params = { new NameValuePair("name", "JBoss Developer") };
        method.setQueryString(params);
        int status = client.executeMethod(method);
        Assert.assertEquals(HttpResponseCodes.SC_OK, status);
        Assert.assertTrue(method.getResponseBodyAsString().contains("JBoss Developer"));
        method.releaseConnection();
    }
    {
        GetMethod method = new GetMethod("http://localhost:8080/jboss-spring-resteasy/locating/basic");
        int status = client.executeMethod(method);
        Assert.assertEquals(HttpResponseCodes.SC_OK, status);
        Assert.assertEquals("basic", method.getResponseBodyAsString());
        method.releaseConnection();
    }
    {
        PutMethod method = new PutMethod("http://localhost:8080/jboss-spring-resteasy/locating/basic");
        method.setRequestEntity(new StringRequestEntity("basic", "text/plain", null));
        int status = client.executeMethod(method);
        Assert.assertEquals(204, status);
        method.releaseConnection();
    }
    {
        GetMethod method = new GetMethod("http://localhost:8080/jboss-spring-resteasy/locating/queryParam");
        NameValuePair[] params = { new NameValuePair("param", "hello world") };
        method.setQueryString(params);
        int status = client.executeMethod(method);
        Assert.assertEquals(HttpResponseCodes.SC_OK, status);
        Assert.assertEquals("hello world", method.getResponseBodyAsString());
        method.releaseConnection();
    }
    {
        GetMethod method = new GetMethod(
                "http://localhost:8080/jboss-spring-resteasy/locating/matrixParam;param=matrix");
        int status = client.executeMethod(method);
        Assert.assertEquals(HttpResponseCodes.SC_OK, status);
        Assert.assertEquals("matrix", method.getResponseBodyAsString());
        method.releaseConnection();
    }
    {
        GetMethod method = new GetMethod("http://localhost:8080/jboss-spring-resteasy/locating/uriParam/1234");
        int status = client.executeMethod(method);
        Assert.assertEquals(HttpResponseCodes.SC_OK, status);
        Assert.assertEquals("1234", method.getResponseBodyAsString());
        method.releaseConnection();
    }
}

From source file:org.jboss.test.web.test.FormAuthUnitTestCase.java

/** Test form authentication of a secured servlet and validate that there is
 * a SecurityAssociation setting Subject. 
 * /* ww  w.j ava2 s  . c  o m*/
 * @throws Exception
 */
public void testFormAuthSubject() throws Exception {
    log.info("+++ testFormAuthSubject");
    // Start by accessing the secured index.html of war1
    HttpClient httpConn = new HttpClient();
    GetMethod indexGet = new GetMethod(baseURLNoAuth + "form-auth/restricted/SecuredServlet");
    indexGet.setQueryString("validateSubject=true");
    int responseCode = httpConn.executeMethod(indexGet);
    String body = indexGet.getResponseBodyAsString();
    assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
    assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);

    HttpState state = httpConn.getState();
    Cookie[] cookies = state.getCookies();
    String sessionID = null;
    for (int c = 0; c < cookies.length; c++) {
        Cookie k = cookies[c];
        if (k.getName().equalsIgnoreCase("JSESSIONID"))
            sessionID = k.getValue();
    }
    getLog().debug("Saw JSESSIONID=" + sessionID);

    // Submit the login form
    PostMethod formPost = new PostMethod(baseURLNoAuth + "form-auth/j_security_check");
    formPost.addRequestHeader("Referer", baseURLNoAuth + "form-auth/restricted/login.html");
    formPost.addParameter("j_username", "jduke");
    formPost.addParameter("j_password", "theduke");
    responseCode = httpConn.executeMethod(formPost.getHostConfiguration(), formPost, state);
    String response = formPost.getStatusText();
    log.debug("responseCode=" + responseCode + ", response=" + response);
    assertTrue("Saw HTTP_MOVED_TEMP", responseCode == HttpURLConnection.HTTP_MOVED_TEMP);

    //  Follow the redirect to the SecureServlet
    Header location = formPost.getResponseHeader("Location");
    String indexURI = location.getValue();
    GetMethod war1Index = new GetMethod(indexURI);
    responseCode = httpConn.executeMethod(war1Index.getHostConfiguration(), war1Index, state);
    response = war1Index.getStatusText();
    log.debug("responseCode=" + responseCode + ", response=" + response);
    assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
    body = war1Index.getResponseBodyAsString();
    if (body.indexOf("j_security_check") > 0)
        fail("get of " + indexURI + " redirected to login page");
}

From source file:org.lnicholls.galleon.apps.weather.WeatherData.java

public void determineFip() {

    if (mFip != null)

        return;//w w  w.j  a v  a2  s.com

    try {

        HttpClient httpclient = new HttpClient();

        httpclient.getParams().setParameter("http.socket.timeout", new Integer(30000));

        httpclient.getParams().setParameter("http.useragent", System.getProperty("http.agent"));

        //Get location/county mapping from census bureau:

        // http://quickfacts.census.gov/cgi-bin/qfd/lookup?state=33000&place=nashua,nh,03060

        GetMethod get = new GetMethod("http://quickfacts.census.gov/cgi-bin/qfd/lookup");

        get.setFollowRedirects(true);

        NameValuePair state = new NameValuePair("state", StateData.getFipFromSymbol(mState));

        NameValuePair place = new NameValuePair("place", mCity + "," + mState + "," + mZip);

        get.setQueryString(new NameValuePair[] { state, place });

        try {

            int iGetResultCode = httpclient.executeMethod(get);

            final String strGetResponseBody = get.getResponseBodyAsString();

            //log.debug(strGetResponseBody);

            if (strGetResponseBody != null) {

                String REGEX = "href=\"/qfd/states/[0-9]*/([0-9]*).html\">([^<]*)</a>";

                Pattern p = Pattern.compile(REGEX);

                Matcher m = p.matcher(strGetResponseBody);

                if (m.find()) {

                    if (log.isDebugEnabled())

                        log.debug("FIP: " + m.group(1) + "(" + m.group(2) + ")");

                    mFip = m.group(1);

                    PersistentValueManager.savePersistentValue(this.getClass().getName() + "." + "fip", mFip);

                    return;

                }

            }

        } catch (Exception ex) {

            log.error("Could not determine FIP", ex);

        } finally {

            get.releaseConnection();

        }

        get = new GetMethod("http://quickfacts.census.gov/cgi-bin/qfd/lookup");

        get.setFollowRedirects(true);

        get.setQueryString(new NameValuePair[] { state, place });

        try {

            int iGetResultCode = httpclient.executeMethod(get);

            final String strGetResponseBody = get.getResponseBodyAsString();

            log.debug(strGetResponseBody);

            if (strGetResponseBody != null) {

                String REGEX = "href=\"/qfd/states/[0-9]*/([0-9]*).html\">([^<]*)</a>";

                Pattern p = Pattern.compile(REGEX);

                Matcher m = p.matcher(strGetResponseBody);

                if (m.find()) {

                    if (log.isDebugEnabled())

                        log.debug("FIP: " + m.group(1) + "(" + m.group(2) + ")");

                    mFip = m.group(1);

                    PersistentValueManager.savePersistentValue(this.getClass().getName() + "." + "fip", mFip);

                    return;

                } else {

                    mFip = StateData.getFipFromSymbol(mState);

                    log.info("Could not find county, using state FIP");

                    return;

                }

            }

        } catch (Exception ex) {

            log.error("Could not determine FIP", ex);

        } finally {

            get.releaseConnection();

        }

    } catch (Exception ex) {

        Tools.logException(WeatherData.class, ex);

    }

    mFip = "000";

    log.error("Could not find FIP for: " + mCity + "," + mState + "," + mZip);

}

From source file:org.mskcc.pathdb.protocol.ProtocolRequest.java

private String createUri(GetMethod method) {
    String uri;//from   w  w  w.jav  a  2  s. c  o  m
    List list = new ArrayList();
    if (version != null) {
        list.add(new NameValuePair(ARG_VERSION, version));
    }
    if (command != null) {
        list.add(new NameValuePair(ARG_COMMAND, command));
    }
    if (query != null) {
        list.add(new NameValuePair(ARG_QUERY, query));
    }
    if (format != null) {
        list.add(new NameValuePair(ARG_FORMAT, format));
    }
    if (startIndex != 0) {
        list.add(new NameValuePair(ARG_START_INDEX, Long.toString(startIndex)));
    }
    if (organism != null) {
        list.add(new NameValuePair(ARG_ORGANISM, organism));
    }
    if (maxHits != null) {
        list.add(new NameValuePair(ARG_MAX_HITS, maxHits));
    }

    if (checkXmlCache == false) {
        list.add(new NameValuePair(ARG_CHECK_XML_CACHE, "0"));
    }
    if (useOptimizedCode == false) {
        list.add(new NameValuePair(ARG_USE_OPTIMIZED_CODE, "0"));
    }

    if (inputIDType != null) {
        list.add(new NameValuePair(ARG_INPUT_ID_TYPE, inputIDType));
    }
    if (fullyConnected != null) {
        list.add(new NameValuePair(ARG_FULLY_CONNECTED, fullyConnected));
    }
    if (binaryInteractionRule != null) {
        list.add(new NameValuePair(ARG_BINARY_INTERACTION_RULE, binaryInteractionRule));
    }
    if (output != null) {
        list.add(new NameValuePair(ARG_OUTPUT, output));
    }
    if (outputIDType != null) {
        list.add(new NameValuePair(ARG_OUTPUT_ID_TYPE, outputIDType));
    }
    if (dataSource != null) {
        list.add(new NameValuePair(ARG_DATA_SOURCE, dataSource));
    }

    NameValuePair nvps[] = (NameValuePair[]) list.toArray(new NameValuePair[list.size()]);
    method.setQueryString(nvps);
    try {
        uri = method.getURI().getEscapedURI();
        uri = uri.replaceAll("&", "&amp;");
    } catch (URIException e) {
        uri = null;
    }
    return uri;
}

From source file:org.mskcc.pathdb.test.web.TestProtocol.java

/**
 * Tests Invalid Request.//from w  ww .  ja v  a  2  s  .  c om
 *
 * @throws Exception All Errors.
 */
public void testInvalidRequest() throws Exception {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(TestConstants.LOCAL_HOST_URL);
    NameValuePair nvps[] = new NameValuePair[2];
    nvps[0] = new NameValuePair(ProtocolRequest.ARG_COMMAND, "get_invalid");
    nvps[1] = new NameValuePair(ProtocolRequest.ARG_FORMAT, ProtocolConstantsVersion1.FORMAT_XML);
    method.setQueryString(nvps);
    int statusCode = client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    int index = response.indexOf("<error_code>450</error_code>");
    assertTrue(index > 0);
}

From source file:org.n52.oxf.util.IOHelper.java

public static InputStream sendGetMessage(String serviceURL, List<NameValuePair> parameters) throws IOException {
    InputStream is = null;/* w w  w .j a va2  s.c  o m*/

    HttpClient httpClient = new HttpClient();
    GetMethod method = new GetMethod(serviceURL);

    NameValuePair[] paramArray = new NameValuePair[parameters.size()];
    for (int i = 0; i < parameters.size(); i++) {
        paramArray[i] = parameters.get(i);
    }
    method.setQueryString(paramArray);

    httpClient.executeMethod(method);

    LOGGER.info("GET-method sended to: " + method.getURI());

    is = method.getResponseBodyAsStream();

    return is;
}