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.esgf.legacydatacart.LegacyOldFileTemplateController.java

/** (String id)
 * This method extracts all file records for a given dataset id and assembles them in json format
 * //from w  ww . j  a  v  a 2 s  .  c  o m
 * @param id        Dataset Id
 * @return          Solr response for all files given the dataset id
 */

private static String getResponseBody(String queryString, String dataset_id) {

    //System.out.println("In getResponseBody");

    String responseBody = null;

    // create an http client
    HttpClient client = new HttpClient();

    //attact the dataset id to the query string
    GetMethod method = null;
    String combinedQueryStr = "";

    combinedQueryStr += queryString + "&fq=dataset_id:" + dataset_id + "&wt=json";
    method = new GetMethod(solrURL);

    method.setQueryString(combinedQueryStr);

    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    try {
        // execute the method
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());

        }

        // read the response
        responseBody = method.getResponseBodyAsString();
    } catch (HTTPException e) {
        LOG.error("Fatal protocol violation");
        e.printStackTrace();
    } catch (IOException e) {
        LOG.error("Fatal transport error");
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }

    return responseBody;
}

From source file:org.geefive.salesforce.soqleditor.RESTfulQuery.java

public void executeQuery() throws Exception {
    Vector soqlResults = new Vector();

    HttpClient restClient = new HttpClient();
    restClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    restClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);

    //      String restfulURLTarget = serverDomain + REST_LOGIN;
    String restfulURLTarget = serverDomain + REST_QUERY;
    System.out.println("RESTful URL Target: " + restfulURLTarget);
    GetMethod method = null;
    try {//from w  w w. ja va2s  . com
        method = new GetMethod(restfulURLTarget);
        System.out.println("Setting authorization header with SID [" + SID + "]");
        method.setRequestHeader("Authorization", "OAuth " + SID);

        NameValuePair[] params = new NameValuePair[1];
        params[0] = new NameValuePair("q", "SELECT Name, Id, Phone, CreatedById from Account LIMIT 100");
        method.setQueryString(params);

        int httpResponseCode = restClient.executeMethod(method);
        System.out.println("HTTP_RESPONSE_CODE [" + httpResponseCode + "]");
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        System.out
                .println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXECUTING QUERY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        if (httpResponseCode == HttpStatus.SC_OK) {
            try {
                JSONObject response = new JSONObject(
                        new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream())));
                System.out.println("_____________________________________");
                System.out.println("RESPONSE [" + response + "]");
                //               Iterator itr = response.keys();
                //               while(itr.hasNext()){
                //                  String key = (String)itr.next();
                //                  System.out.println("KEY: " + (String)itr.next());
                //               }

                JSONArray resultArray = response.getJSONArray("records");
                StringBuffer soqlQueryResults = new StringBuffer();
                String token = "";
                JSONObject inner = null;
                System.out.println(resultArray.getString(0));
                inner = resultArray.getJSONObject(0);

                Iterator keys = inner.keys();
                HashMap columnNames = new HashMap();
                while (keys.hasNext()) {
                    String column = (String) keys.next();
                    System.out.println("KEY>> " + column);
                    columnNames.put(column, "");
                    soqlQueryResults.append(token + column);
                    token = " * ";
                }
                soqlResults.add(soqlQueryResults.toString());

                //System.out.println("******* UNCOMMENT ME FOR RELEASE *******");

                Iterator keyset = null;
                JSONArray results = response.getJSONArray("records");
                for (int i = 0; i < results.length(); i++) {
                    soqlQueryResults.setLength(0);
                    keyset = columnNames.keySet().iterator();
                    token = "";
                    while (keyset.hasNext()) {
                        String columnName = (String) keyset.next();
                        if (!columnName.equalsIgnoreCase("attributes")) {
                            soqlQueryResults.append(token + results.getJSONObject(i).getString(columnName));
                            token = " * ";
                        }
                    }

                    //                  System.out.println("=====>>>>>>> " + soqlQueryResults.toString());
                    soqlResults.add(soqlQueryResults.toString());

                    //                  System.out.println(results.getJSONObject(i).getString("Id") + ", "
                    //                        + results.getJSONObject(i).getString("Name") + ", "
                    //                        + results.getJSONObject(i).getString("Phone")
                    //                        + ", " + results.getJSONObject(i).getString("CreatedById"));
                } //end for
            } catch (JSONException jsonex) {
                throw jsonex;
            }
        }
    } finally {
        method.releaseConnection();
    }

    Iterator finalData = soqlResults.iterator();
    while (finalData.hasNext()) {
        System.out.println("-||=========>> " + (String) finalData.next());
    }

    System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXIT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
}

From source file:org.geefive.salesforce.soqleditor.SOQLQueryEngine.java

public QueryResultContainer executeQuery(String soql) throws Exception {
    HttpClient restClient = new HttpClient();
    restClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    restClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);

    String restfulURLTarget = sfdcOauth.getServerURL() + sfdcOauth.getQueryURI();
    GetMethod method = null;
    QueryResultContainer soqlResults = new QueryResultContainer();
    try {//ww  w .  j  a  v  a2s .  c o  m
        method = new GetMethod(restfulURLTarget);
        //         updateStatus("Setting authorization header with SID [" + sfdcOauth.getSecureID() + "]");
        method.setRequestHeader("Authorization", "OAuth " + sfdcOauth.getSecureID());

        NameValuePair[] params = new NameValuePair[1];
        //         params[0] = new NameValuePair("q","SELECT Name, Id, Phone, CreatedById from Account LIMIT 100");
        params[0] = new NameValuePair("q", soql);
        method.setQueryString(params);

        int httpResponseCode = restClient.executeMethod(method);
        //         updateStatus("HTTP_RESPONSE_CODE [" + httpResponseCode + "]");
        //         updateStatus("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        //         updateStatus("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXECUTING QUERY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        if (httpResponseCode == HttpStatus.SC_OK) {
            try {

                JSONObject response = new JSONObject(
                        new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream())));

                JSONArray results = response.getJSONArray("records");
                Vector<HashMap<String, String>> resies = getResults(results, new HashMap<String, String>(),
                        new Vector<HashMap<String, String>>(), "");
                soqlResults = createOutput(resies);

            } catch (JSONException jsonex) {
                throw jsonex;
            }
        }
    } finally {
        method.releaseConnection();
    }
    return soqlResults;
}

From source file:org.geowebcache.layer.wms.WMSHttpHelper.java

/**
 * sets up a HTTP GET request to a URL and configures authentication.
 * // ww  w  .  j  a va 2s  .  co m
 * @param url
 *            endpoint to talk to
 * @param queryParams
 *            parameters for the query string
 * @param backendTimeout
 *            timeout to use in seconds
 * @return executed GetMethod (that has to be closed after reading the response!)
 * @throws HttpException
 * @throws IOException
 */
public GetMethod executeRequest(final URL url, final Map<String, String> queryParams,
        final Integer backendTimeout) throws HttpException, IOException {
    // grab the client
    HttpClient httpClient = getHttpClient();

    // prepare the request
    GetMethod getMethod = new GetMethod(url.toString());
    if (queryParams != null && queryParams.size() > 0) {
        NameValuePair[] params = new NameValuePair[queryParams.size()];
        int i = 0;
        for (Map.Entry<String, String> e : queryParams.entrySet()) {
            params[i] = new NameValuePair(e.getKey(), e.getValue());
            i++;
        }
        getMethod.setQueryString(params);
    }
    getMethod.setDoAuthentication(doAuthentication);

    // fire!
    if (log.isDebugEnabled()) {
        log.trace(getMethod.getURI().getURI());
    }
    httpClient.executeMethod(getMethod);
    return getMethod;
}

From source file:org.glite.authz.common.http.JettyAdminServiceCLI.java

/**
 * Executes the service command. Also checks to ensure the HTTP return code was 200.
 * //from w w w  . j  av a 2 s.c om
 * @param host host to which to connect
 * @param port port to which to connect
 * @param command command sent to the admin service
 * @param password admin command password, may be null
 */
private static void executeCommand(String host, int port, String command, String password) {
    HttpClientBuilder clientBuilder = new HttpClientBuilder();
    HttpClient httpClient = clientBuilder.buildClient();

    GetMethod getMethod = new GetMethod("http://" + host + ":" + port + "/" + command);
    if (password != null) {
        getMethod.setQueryString(new NameValuePair[] {
                new NameValuePair(PasswordProtectFilter.PASSWORD_PARAM_NAME, password), });
    }

    try {
        httpClient.executeMethod(getMethod);
        String response = Strings.safeTrimOrNullString(getMethod.getResponseBodyAsString());
        if (response != null) {
            System.out.println(response);
        }
    } catch (ConnectException e) {
        exit("Unable to connect to " + host + ":" + port + ", perhaps the service is not running", RC_CTX);
    } catch (IOException e) {
        exit("Error executing service command:\n" + e.getMessage(), RC_CTX);
    }

    int statusCode = getMethod.getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        return;
    } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        exit("you are not authorized to execute admin commands; invalid password", RC_UNAUTHORIZED);
    } else {
        exit("Service returned unexpected HTTP status code; " + statusCode, RC_UNKNOWN);
    }
}

From source file:org.iavante.sling.gad.administration.impl.AbstractHttpOperation.java

/**
 * Retrieve the contents of given URL and assert its content type
 * /*from   ww  w .j ava 2  s  . c om*/
 * @param expectedContentType
 *          use CONTENT_TYPE_DONTCARE if must not be checked
 * @throws IOException
 * @throws HttpException
 */
protected String getAuthenticatedContent(Credentials creds, String url, String expectedContentType,
        List<NameValuePair> params, int expectedStatusCode) throws IOException {

    URL baseUrl = new URL(HTTP_BASE_URL);

    List authPrefs = new ArrayList(2);
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);

    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setAuthenticationPreemptive(true);
    httpClient.getState().setCredentials(AuthScope.ANY, creds);
    httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    GetMethod get = new GetMethod(url);

    try {

        if (params != null) {
            final NameValuePair[] nvp = new NameValuePair[0];
            get.setQueryString(params.toArray(nvp));
        }
        final int status = httpClient.executeMethod(get);
        final InputStream is = get.getResponseBodyAsStream();
        final StringBuffer content = new StringBuffer();
        final String charset = get.getResponseCharSet();
        final byte[] buffer = new byte[16384];
        int n = 0;
        while ((n = is.read(buffer, 0, buffer.length)) > 0) {
            content.append(new String(buffer, 0, n, charset));
        }
        assertEquals("Expected status " + expectedStatusCode + " for " + url + " (content=" + content + ")",
                expectedStatusCode, status);
        final Header h = get.getResponseHeader("Content-Type");
        if (expectedContentType == null) {
            if (h != null) {
                fail("Expected null Content-Type, got " + h.getValue());
            }
        } else if (CONTENT_TYPE_DONTCARE.equals(expectedContentType)) {
            // no check
        } else if (h == null) {
            fail("Expected Content-Type that starts with '" + expectedContentType
                    + " but got no Content-Type header at " + url);
        } else {
            assertTrue("Expected Content-Type that starts with '" + expectedContentType + "' for " + url
                    + ", got '" + h.getValue() + "'", h.getValue().startsWith(expectedContentType));
        }
        return content.toString();

    } finally {
        get.releaseConnection();
    }
}

From source file:org.iavante.sling.gad.channel.ChannelToolsIT.java

@org.junit.Test
public void test_get_channel_embed_request() {

    try {/*  w  w  w.  j  av a 2  s  .  co  m*/
        Thread.sleep(2000);
    } catch (InterruptedException e1) {

        e1.printStackTrace();
    }

    // Get the revision
    GetMethod get_revision_simple = new GetMethod(
            SLING_URL + CHANNEL_URL + channel_slug + "/" + CONTENTS_FOLDER + "/" + content_title);

    try {
        client.executeMethod(get_revision_simple);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String body = "";
    try {
        body = get_revision_simple.getResponseBodyAsString();
    } catch (IOException e) {

        e.printStackTrace();
    }

    assertTrue(body.contains("width='400'"));
    assertTrue(body.contains("height='400'"));

    // Edit ds custom props
    PostMethod post_edit_channel = new PostMethod(
            SLING_URL + CHANNEL_URL + channel_slug + "/" + DS_CUSTOM_PROPS_FOLDER);
    post_edit_channel.setDoAuthentication(true);

    NameValuePair[] data_edit_channel = { new NameValuePair("player_width", "1000"),
            new NameValuePair("player_height", "800") };
    new NameValuePair("player_playlist_layout", "top");
    post_edit_channel.setRequestBody(data_edit_channel);

    try {
        client.executeMethod(post_edit_channel);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    post_edit_channel.releaseConnection();

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e1) {

        e1.printStackTrace();
    }

    // Get the revision
    GetMethod get_revision = new GetMethod(
            SLING_URL + CHANNEL_URL + channel_slug + "/" + CONTENTS_FOLDER + "/" + content_title);

    try {
        client.executeMethod(get_revision);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    body = "";
    try {
        body = get_revision.getResponseBodyAsString();
    } catch (IOException e) {

        e.printStackTrace();
    }

    assertTrue(body.contains("width='1000'"));
    assertTrue(body.contains("height='800'"));
    assertTrue(body.contains("playlist=none"));

    get_revision.releaseConnection();

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e1) {

        e1.printStackTrace();
    }

    // Get the revision
    GetMethod get_revision_override = new GetMethod(
            SLING_URL + CHANNEL_URL + channel_slug + "/" + CONTENTS_FOLDER + "/" + content_title);

    NameValuePair[] get_params = { new NameValuePair("player_width", "200"),
            new NameValuePair("player_height", "200"), new NameValuePair("player_repeat", "true"),
            new NameValuePair("player_playlist_layout", "left"),
            new NameValuePair("player_autostart", "true") };

    get_revision_override.setQueryString(get_params);

    try {

        client.executeMethod(get_revision_override);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    body = "";
    try {
        body = get_revision_override.getResponseBodyAsString();
    } catch (IOException e) {

        e.printStackTrace();
    }

    assertTrue(body.contains("width='200'"));
    assertTrue(body.contains("height='200'"));
    assertTrue(body.contains("repeat=true"));
    assertTrue(body.contains("playlist=left"));
    assertTrue(body.contains("autostart=true"));

    get_revision_override.releaseConnection();
}

From source file:org.iavante.sling.gad.channel.ChannelToolsIT.java

@org.junit.Test
public void test_get_show_list_api() {

    try {/*w w  w  .  j a v  a  2 s.  co  m*/
        Thread.sleep(2000);
    } catch (InterruptedException e1) {

        e1.printStackTrace();
    }

    // Get the list from ids
    GetMethod get_list = new GetMethod(
            SLING_URL + CHANNEL_URL + channel_slug + "/" + CONTENTS_FOLDER + ".show.list/");

    NameValuePair[] get_params = { new NameValuePair("path", content_title),
            new NameValuePair("path", "not-exists") };

    get_list.setQueryString(get_params);

    try {
        client.executeMethod(get_list);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String body = "";
    try {
        body = get_list.getResponseBodyAsString();
    } catch (IOException e) {

        e.printStackTrace();
    }

    assertTrue(body.contains("<title>" + content_title + "</title>"));
    assertTrue(body.contains("<title>not-exists</title>"));
    assertTrue(body.contains("<path>404</path>"));

    get_list.releaseConnection();
}

From source file:org.iavante.sling.gad.channel.ChannelToolsIT.java

@org.junit.Test
public void test_get_xspf_public() {

    try {/*  ww  w .  j a  v a  2  s.  c  o  m*/
        Thread.sleep(2000);
    } catch (InterruptedException e1) {

        e1.printStackTrace();
    }

    // Get revision
    GetMethod get_revision = new GetMethod(
            SLING_URL + CHANNEL_URL + channel_slug + "/" + CONTENTS_FOLDER + "/" + content_title + ".xspf.xml");

    NameValuePair[] get_params = { new NameValuePair("ticket", "abcd") };
    get_revision.setQueryString(get_params);

    try {
        client.executeMethod(get_revision);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    assertEquals(get_revision.getStatusCode(), 200);
    get_revision.releaseConnection();

    // Edit channel. Public read = 0
    PostMethod post_edit_channel = new PostMethod(
            SLING_URL + CHANNEL_URL + channel_slug + "/" + DS_CUSTOM_PROPS_FOLDER);
    NameValuePair[] data_custom_props = { new NameValuePair("public_read", "0"), };

    post_edit_channel.setDoAuthentication(true);
    post_edit_channel.setRequestBody(data_custom_props);

    try {
        client.executeMethod(post_edit_channel);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    assertEquals(200, post_edit_channel.getStatusCode());
    post_edit_channel.releaseConnection();

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e1) {

        e1.printStackTrace();
    }

    // Get revision again
    GetMethod get_revision_again = new GetMethod(
            SLING_URL + CHANNEL_URL + channel_slug + "/" + CONTENTS_FOLDER + "/" + content_title + ".xspf.xml");

    NameValuePair[] get_params_again = { new NameValuePair("ticket", "abcd") };
    get_revision_again.setQueryString(get_params_again);

    try {
        client.executeMethod(get_revision_again);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    assertEquals(get_revision_again.getStatusCode(), 403);
    get_revision_again.releaseConnection();
}

From source file:org.intalio.tempo.workflow.tas.nuxeo.NuxeoStorageStrategy.java

/**
 * Create a file reference in nuxeo, which does not contain the file, but
 * creates a file container so we can upload
 *///from  ww w .j ava 2 s. c  om
private OMElement getCreateFileEle(String uri, String repoId, String fileName) throws IOException {
    String newUri = uri + "/" + repoId + REST_CREATE;
    GetMethod method = new GetMethod(newUri);

    NameValuePair[] pairs = new NameValuePair[2];
    pairs[0] = new NameValuePair(NUXEO_DOC_TYPE, NUXEO_FILE);
    String encodedName = URLEncoder.encode(fileName, "utf-8");
    pairs[1] = new NameValuePair(NUXEO_DUBLINCORE_TITLE, encodedName);

    method.setQueryString(pairs);
    httpclient.executeMethod(method);
    String value = method.getResponseBodyAsString();

    method.releaseConnection();
    return buildOMElement(value);
}