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.apache.asterix.aoya.Utils.java

/**
 * Simple test via the AsterixDB Javascript API to determine if an instance is truly live or not.
 * Queries the Metadata dataset and returns true if the query completes successfully, false otherwise.
 *
 * @param host/*from  w w w.j a v a  2s  .c  o m*/
 *            The host to run the query against
 * @return
 *         True if the instance is OK, false otherwise.
 * @throws IOException
 */
public static boolean probeLiveness(String host, int port) throws IOException {
    final String url = "http://" + host + ":" + port + "/query";
    final String test = "for $x in dataset Metadata.Dataset return $x;";
    GetMethod method = new GetMethod(url);
    method.setQueryString(new NameValuePair[] { new NameValuePair("query", test) });
    InputStream response;
    try {
        response = executeHTTPCall(method);
    } catch (ConnectException e) {
        return false;
    }
    if (response == null) {
        return false;
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(response));
    String result = br.readLine();
    if (result == null) {
        return false;
    }
    if (method.getStatusCode() != HttpStatus.SC_OK) {
        return false;
    }
    return true;
}

From source file:org.apache.cloudstack.network.opendaylight.api.resources.Action.java

public String executeGet(final String uri, final Map<String, String> parameters)
        throws NeutronRestApiException {
    try {//from  www  .  ja v a2s.  co  m
        validateCredentials();
    } catch (NeutronInvalidCredentialsException e) {
        throw new NeutronRestApiException("Invalid credentials!", e);
    }

    NeutronRestFactory factory = NeutronRestFactory.getInstance();

    NeutronRestApi neutronRestApi = factory.getNeutronApi(GetMethod.class);
    GetMethod getMethod = (GetMethod) neutronRestApi.createMethod(url, uri);

    try {
        getMethod.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);

        String encodedCredentials = encodeCredentials();
        getMethod.setRequestHeader("Authorization", "Basic " + encodedCredentials);

        if (parameters != null && !parameters.isEmpty()) {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
            for (Entry<String, String> e : parameters.entrySet()) {
                nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue()));
            }
            getMethod.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
        }

        neutronRestApi.executeMethod(getMethod);

        if (getMethod.getStatusCode() != HttpStatus.SC_OK) {
            String errorMessage = responseToErrorMessage(getMethod);
            getMethod.releaseConnection();
            s_logger.error("Failed to retrieve object : " + errorMessage);
            throw new NeutronRestApiException("Failed to retrieve object : " + errorMessage);
        }

        return getMethod.getResponseBodyAsString();

    } catch (NeutronRestApiException e) {
        s_logger.error(
                "NeutronRestApiException caught while trying to execute HTTP Method on the Neutron Controller",
                e);
        throw new NeutronRestApiException("API call to Neutron Controller Failed", e);
    } catch (IOException e) {
        throw new NeutronRestApiException(e);
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.apache.falcon.logging.v1.TaskLogRetrieverV1.java

private String getHistoryFile(Configuration conf, String jobId) throws IOException {
    String jtAddress = "scheme://" + conf.get("mapred.job.tracker");
    String jtHttpAddr = "scheme://" + conf.get("mapred.job.tracker.http.address");
    try {/*from w  w w  . j a  v  a 2 s. c  o m*/
        String host = new URI(jtAddress).getHost();
        int port = new URI(jtHttpAddr).getPort();
        HttpClient client = new HttpClient();
        String jobUrl = "http://" + host + ":" + port + "/jobdetails.jsp";
        GetMethod get = new GetMethod(jobUrl);
        get.setQueryString("jobid=" + jobId);
        get.setFollowRedirects(false);
        int status = client.executeMethod(get);
        String file = null;
        if (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY) {
            file = get.getResponseHeader("Location").toString();
            file = file.substring(file.lastIndexOf('=') + 1);
            file = JobHistory.JobInfo.decodeJobHistoryFileName(file);
        } else {
            LOG.warn("JobURL {} for id: {} returned {}", jobUrl, jobId, status);
        }
        return file;
    } catch (URISyntaxException e) {
        throw new IOException("JT Address: " + jtAddress + ", http Address: " + jtHttpAddr, e);
    }
}

From source file:org.apache.oodt.cas.filemgr.catalog.solr.SolrClient.java

/**
 * Method to execute a GET request to the given URL with the given parameters.
 * @param url/*from   w w w  .jav a  2 s .  c om*/
 * @param parameters
 * @return
 */
private String doGet(String url, Map<String, String[]> parameters, String mimeType)
        throws IOException, CatalogException {

    // build HTTP/GET request
    GetMethod method = new GetMethod(url);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String[]> key : parameters.entrySet()) {
        for (String value : key.getValue()) {
            nvps.add(new NameValuePair(key.getKey(), value));
        }
    }
    // request results in JSON format
    if (mimeType.equals(Parameters.MIME_TYPE_JSON)) {
        nvps.add(new NameValuePair("wt", "json"));
    }
    method.setQueryString(nvps.toArray(new NameValuePair[nvps.size()]));
    LOG.info("GET url: " + url + " query string: " + method.getQueryString());

    // send HTTP/GET request, return response
    return doHttp(method);

}

From source file:org.apache.sling.launchpad.webapp.integrationtest.accessManager.AbstractAccessManagerTest.java

/** retrieve the contents of given URL and assert its content type
 * @param expectedContentType use CONTENT_TYPE_DONTCARE if must not be checked 
 * @throws IOException//from  w  ww.  jav  a2s. co m
 * @throws HttpException */
protected String getAuthenticatedContent(Credentials creds, String url, String expectedContentType,
        List<NameValuePair> params, int expectedStatusCode) throws IOException {
    final GetMethod get = new GetMethod(url);

    URL baseUrl = new URL(HTTP_BASE_URL);
    AuthScope authScope = new AuthScope(baseUrl.getHost(), baseUrl.getPort(), AuthScope.ANY_REALM);
    get.setDoAuthentication(true);
    Credentials oldCredentials = httpClient.getState().getCredentials(authScope);
    try {
        httpClient.getState().setCredentials(authScope, creds);

        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 {
        httpClient.getState().setCredentials(authScope, oldCredentials);
    }
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.AuthenticatedTestUtil.java

/** retrieve the contents of given URL and assert its content type
 * @param expectedContentType use CONTENT_TYPE_DONTCARE if must not be checked
 * @throws IOException/* w  ww  . ja v  a2  s. co  m*/
 * @throws HttpException */
public String getAuthenticatedContent(Credentials creds, String url, String expectedContentType,
        List<NameValuePair> params, int expectedStatusCode) throws IOException {
    final GetMethod get = new GetMethod(url);

    URL baseUrl = new URL(HTTP_BASE_URL);
    AuthScope authScope = new AuthScope(baseUrl.getHost(), baseUrl.getPort(), AuthScope.ANY_REALM);
    get.setDoAuthentication(true);
    Credentials oldCredentials = httpClient.getState().getCredentials(authScope);
    try {
        httpClient.getState().setCredentials(authScope, creds);

        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 {
        httpClient.getState().setCredentials(authScope, oldCredentials);
    }
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.login.RedirectOnLogoutTest.java

/**
 * Test SLING-1847/*from www . ja  v  a 2  s  .c o m*/
 * @throws Exception
 */
@Test
public void testRedirectToResourceAfterLogout() throws Exception {
    //login
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "admin"));
    params.add(new NameValuePair("j_password", "admin"));
    H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_MOVED_TEMPORARILY,
            params, null);

    //...and then...logout with a resource redirect
    String locationAfterLogout = HttpTest.SERVLET_CONTEXT + "/system/sling/info.sessionInfo.json";
    final GetMethod get = new GetMethod(HttpTest.HTTP_BASE_URL + "/system/sling/logout");
    NameValuePair[] logoutParams = new NameValuePair[1];
    logoutParams[0] = new NameValuePair("resource", locationAfterLogout);
    get.setQueryString(logoutParams);

    get.setFollowRedirects(false);
    final int status = H.getHttpClient().executeMethod(get);
    assertEquals("Expected redirect", HttpServletResponse.SC_MOVED_TEMPORARILY, status);
    Header location = get.getResponseHeader("Location");
    assertEquals(HttpTest.HTTP_BASE_URL + locationAfterLogout, location.getValue());
}

From source file:org.apache.wink.itest.version.VersioningTest.java

public void testVersionByAccept() {
    try {/* ww w.  jav a2s . c  om*/
        GetMethod httpMethod = new GetMethod();
        httpMethod.setURI(new URI(getBaseURI(), false));
        httpMethod.setQueryString("form=1040");
        System.out.println(Arrays.asList(httpMethod.getRequestHeaders()));
        httpclient = new HttpClient();

        try {
            httpMethod.setRequestHeader("Accept", "application/taxform+2007");
            int result = httpclient.executeMethod(httpMethod);
            System.out.println("Response status code: " + result);
            System.out.println("Response body: ");
            String responseBody = httpMethod.getResponseBodyAsString();
            System.out.println(responseBody);
            assertTrue("Response does not contain expected 'deductions' element",
                    responseBody.contains("<deductions>"));
            assertEquals(200, result);

            httpMethod.setRequestHeader("Accept", "application/taxform+2008");
            result = httpclient.executeMethod(httpMethod);
            System.out.println("Response status code: " + result);
            System.out.println("Response body: ");
            responseBody = httpMethod.getResponseBodyAsString();
            System.out.println(responseBody);
            assertFalse("Response contains unexpected 'deductions' element",
                    responseBody.contains("<deductions>"));
            assertEquals(200, result);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail(ioe.getMessage());
        } finally {
            httpMethod.releaseConnection();
        }
    } catch (URIException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:org.apache.wink.itest.version.VersioningTest.java

public void testVersionByQueryString() {
    try {// w  w w.  ja  v  a 2  s.c  o m
        GetMethod httpMethod = new GetMethod();
        httpMethod.setURI(new URI(getBaseURI() + "/1040", false));
        httpMethod.setQueryString("version=2007");
        System.out.println(Arrays.asList(httpMethod.getRequestHeaders()));
        httpclient = new HttpClient();

        try {
            int result = httpclient.executeMethod(httpMethod);
            System.out.println("Response status code: " + result);
            System.out.println("Response body: ");
            String responseBody = httpMethod.getResponseBodyAsString();
            System.out.println(responseBody);
            assertTrue("Response does not contain expected 'deductions' element",
                    responseBody.contains("<deductions>"));
            assertEquals(200, result);

            httpMethod.setURI(new URI(getBaseURI() + "/1040", false));
            httpMethod.setQueryString("version=2008");
            result = httpclient.executeMethod(httpMethod);
            System.out.println("Response status code: " + result);
            System.out.println("Response body: ");
            responseBody = httpMethod.getResponseBodyAsString();
            System.out.println(responseBody);
            assertFalse("Response contains unexpected 'deductions' element",
                    responseBody.contains("<deductions>"));
            assertEquals(200, result);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail(ioe.getMessage());
        } finally {
            httpMethod.releaseConnection();
        }
    } catch (URIException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:org.apache.wookie.tests.functional.ParticipantsControllerTest.java

@Test
public void addParticipant() {
    try {//from  ww w . ja  va  2s . c o m
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(TEST_PARTICIPANTS_SERVICE_URL_VALID);
        post.setQueryString("api_key=" + API_KEY_VALID + "&widgetid=" + WIDGET_ID_VALID
                + "&userid=test&shareddatakey=participantstest&participant_id=1&participant_display_name=bob&participant_thumbnail_url=http://www.test.org");
        client.executeMethod(post);
        int code = post.getStatusCode();
        assertEquals(201, code);
        post.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        fail("post failed");
    }
    // Now lets GET it to make sure it was added OK
    try {
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod(TEST_PARTICIPANTS_SERVICE_URL_VALID);
        get.setQueryString("api_key=" + API_KEY_VALID + "&widgetid=" + WIDGET_ID_VALID
                + "&userid=test&shareddatakey=participantstest");
        client.executeMethod(get);
        int code = get.getStatusCode();
        assertEquals(200, code);
        String response = get.getResponseBodyAsString();
        assertTrue(response.contains(
                "<participant id=\"1\" display_name=\"bob\" thumbnail_url=\"http://www.test.org\" />"));
        get.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        fail("get failed");
    }
}