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:com.rallydev.integration.build.rest.RallyRestService.java

public String findWorkspaceFlag(String workspaceName) throws IOException {
    NameValuePair wsParam, fetchParam;
    NameValuePair[] pairs;//w w  w. j a v a2s . c om
    String response, workspaceRef = null, workspaceOid = null;

    workspaceRef = findWorkspace(workspaceName);
    workspaceOid = extractId(workspaceRef);
    if (workspaceOid != null) {
        response = getObject("workspace", workspaceOid);
        if (response == null || !isValidResponse(response)) {
            return null;
        }
    } else {
        return null;
    }

    String reqUrl = getUrl() + "/workspaceconfiguration";
    GetMethod get = new GetMethod(reqUrl);
    wsParam = new NameValuePair("workspace", workspaceRef);
    fetchParam = new NameValuePair("fetch", "true");
    pairs = new NameValuePair[] { wsParam, fetchParam };

    get.setQueryString(pairs);
    response = doGet(new HttpClient(), get);
    if (response == null || !isValidResponse(response)) {
        return null;
    } else {
        return extractFlagFromResponse(response);
    }
}

From source file:net.mojodna.searchable.solr.SolrSearcher.java

public ResultSet search(final String query, final Integer start, final Integer count) throws IndexException {
    try {//ww  w. j  ava2  s  .  c  om
        final GetMethod get = new GetMethod(solrPath);
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("q", query));
        if (null != start) {
            params.add(new NameValuePair("start", start.toString()));
        }
        if (null != count) {
            params.add(new NameValuePair("rows", count.toString()));
        }
        params.add(new NameValuePair("version", "2.1"));
        params.add(new NameValuePair("indent", "on"));
        get.setQueryString(params.toArray(new NameValuePair[] {}));
        final int responseCode = getHttpClient().executeMethod(get);

        final SAXBuilder builder = new SAXBuilder();
        final Document response = builder.build(get.getResponseBodyAsStream());
        final Element resultNode = response.getRootElement().getChild("result");

        final ResultSetImpl resultSet = new ResultSetImpl(
                new Integer(resultNode.getAttributeValue("numFound")));
        resultSet.setOffset(new Integer(resultNode.getAttributeValue("start")));
        List<Element> docs = resultNode.getChildren("doc");
        for (int i = 0; i < docs.size(); i++) {
            final Element doc = docs.get(i);
            Result result = null;

            // load the class name
            String className = null;
            String id = null;
            String idType = null;
            for (final Iterator it = doc.getChildren("str").iterator(); it.hasNext();) {
                final Element str = (Element) it.next();
                final String name = str.getAttributeValue("name");
                if (IndexSupport.TYPE_FIELD_NAME.equals(name)) {
                    className = str.getTextTrim();
                } else if (IndexSupport.ID_FIELD_NAME.equals(name)) {
                    id = str.getTextTrim();
                } else if (IndexSupport.ID_TYPE_FIELD_NAME.equals(name)) {
                    idType = str.getTextTrim();
                }
            }

            try {
                // attempt to instantiate an instance of the specified class
                try {
                    if (null != className) {
                        final Object o = Class.forName(className).newInstance();
                        if (o instanceof Result) {
                            log.debug("Created new instance of: " + className);
                            result = (Result) o;
                        }
                    }
                } catch (final ClassNotFoundException e) {
                    // class was invalid, or something
                }

                // fall back to a GenericResult as a container
                if (null == result)
                    result = new GenericResult();

                if (result instanceof Searchable) {
                    // special handling for searchables
                    final String idField = SearchableBeanUtils
                            .getIdPropertyName(((Searchable) result).getClass());

                    // attempt to load the id and set the id property on the Searchable appropriately
                    if (null != id) {
                        log.debug("Setting id to '" + id + "' of type " + idType);
                        try {
                            final Object idValue = ConvertUtils.convert(id, Class.forName(idType));
                            PropertyUtils.setSimpleProperty(result, idField, idValue);
                        } catch (final ClassNotFoundException e) {
                            log.warn("Id type was not a class that could be found: " + idType);
                        }
                    } else {
                        log.warn("Id value was null.");
                    }
                } else {
                    final GenericResult gr = new GenericResult();
                    gr.setId(id);
                    gr.setType(className);
                    result = gr;
                }

            } catch (final Exception e) {
                throw new SearchException("Could not reconstitute resultant object.", e);
            }

            result.setRanking(i);

            resultSet.add(result);
        }

        return resultSet;
    } catch (final JDOMException e) {
        throw new IndexingException(e);
    } catch (final IOException e) {
        throw new IndexingException(e);
    }
}

From source file:eu.learnpad.core.impl.cw.XwikiCoreFacadeRestResource.java

@Override
public String getDashboardKpiDefaultViewer(String modelSetId, String userId) throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/corefacade/dashboardkpi/viewer", DefaultRestResource.REST_URI);
    GetMethod getMethod = new GetMethod(uri);
    getMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML);

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("modelsetid", modelSetId);
    queryString[1] = new NameValuePair("userid", userId);
    getMethod.setQueryString(queryString);

    try {// w  w  w .  java  2s . c  o  m
        httpClient.executeMethod(getMethod);
        String url = getMethod.getResponseBodyAsString();
        return url;
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
}

From source file:com.owncloud.android.lib.common.accounts.ExternalLinksOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;
    GetMethod get = null;
    String ocsUrl = client.getBaseUri() + OCS_ROUTE_EXTERNAL_LINKS;

    try {/*  www . j  ava 2s  .  c om*/
        // check capabilities
        RemoteOperation getCapabilities = new GetRemoteCapabilitiesOperation();
        RemoteOperationResult capabilitiesResult = getCapabilities.execute(client);
        OCCapability capability = (OCCapability) capabilitiesResult.getData().get(0);

        if (capability.getExternalLinks().isTrue()) {

            get = new GetMethod(ocsUrl);
            get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
            get.setQueryString(new NameValuePair[] { new NameValuePair("format", "json") });
            status = client.executeMethod(get);

            if (isSuccess(status)) {
                String response = get.getResponseBodyAsString();
                Log_OC.d(TAG, "Successful response: " + response);

                // parse
                JSONArray links = new JSONObject(response).getJSONObject(NODE_OCS).getJSONArray(NODE_DATA);

                ArrayList<Object> resultLinks = new ArrayList<>();

                for (int i = 0; i < links.length(); i++) {
                    JSONObject link = links.getJSONObject(i);

                    if (link != null) {
                        Integer id = link.getInt(NODE_ID);
                        String iconUrl = link.getString(NODE_ICON);
                        String language = "";
                        if (link.has(NODE_LANGUAGE)) {
                            language = link.getString(NODE_LANGUAGE);
                        }

                        ExternalLinkType type;
                        switch (link.getString(NODE_TYPE)) {
                        case "link":
                            type = ExternalLinkType.LINK;
                            break;
                        case "settings":
                            type = ExternalLinkType.SETTINGS;
                            break;
                        case "quota":
                            type = ExternalLinkType.QUOTA;
                            break;
                        default:
                            type = ExternalLinkType.UNKNOWN;
                            break;
                        }

                        String name = link.getString(NODE_NAME);
                        String url = link.getString(NODE_URL);

                        boolean redirect = false;

                        if (link.has(NODE_REDIRECT)) {
                            redirect = link.getInt(NODE_REDIRECT) == 1;
                        }

                        resultLinks.add(new ExternalLink(id, iconUrl, language, type, name, url, redirect));
                    }
                }

                result = new RemoteOperationResult(true, status, get.getResponseHeaders());
                result.setData(resultLinks);

            } else {
                result = new RemoteOperationResult(false, status, get.getResponseHeaders());
                String response = get.getResponseBodyAsString();
                Log_OC.e(TAG, "Failed response while getting external links ");
                if (response != null) {
                    Log_OC.e(TAG, "*** status code: " + status + " ; response message: " + response);
                } else {
                    Log_OC.e(TAG, "*** status code: " + status);
                }
            }
        } else {
            result = new RemoteOperationResult(RemoteOperationResult.ResultCode.NOT_AVAILABLE);
            Log_OC.d(TAG, "External links disabled");
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while getting external links ", e);
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }

    return result;
}

From source file:com.mdt.rtm.Invoker.java

public Element invoke(Param... params) throws ServiceException {
    Element result;//from   w  ww  . j a v a  2 s .c om

    long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation;
    if (timeSinceLastInvocation < INVOCATION_INTERVAL) {
        // In order not to invoke the RTM service too often
        try {
            Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation);
        } catch (InterruptedException e) {
            throw new ServiceInternalException(
                    "Unexpected interruption while attempting to pause for some time before invoking the RTM service back",
                    e);
        }
    }

    log.debug("Invoker running at " + new Date());

    HttpClient client = new HttpClient();
    if (proxyHostName != null) {
        // Sets an HTTP proxy and the credentials for authentication
        client.getHostConfiguration().setProxy(proxyHostName, proxyPortNumber);
        if (proxyLogin != null) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyLogin, proxyPassword));
        }
    }
    GetMethod method = new GetMethod(serviceBaseUrl + REST_SERVICE_URL_POSTFIX);
    method.setRequestHeader(HttpMethodParams.HTTP_URI_CHARSET, "UTF-8");
    NameValuePair[] pairs = new NameValuePair[params.length + 1];
    int i = 0;
    for (Param param : params) {
        log.debug("  setting " + param.getName() + "=" + param.getValue());
        pairs[i++] = param.toNameValuePair();
    }
    pairs[i++] = new NameValuePair(API_SIG_PARAM, calcApiSig(params));
    method.setQueryString(pairs);

    try {
        URI methodUri;
        try {
            methodUri = method.getURI();
            log.info("Executing the method:" + methodUri);
        } catch (URIException exception) {
            String message = "Cannot determine the URI of the web method";
            log.error(message);
            throw new ServiceInternalException(message, exception);
        }
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
            throw new ServiceInternalException("method failed: " + method.getStatusLine());
        }

        // THINK: this method is deprecated, but the only way to get the body as a string, without consuming
        // the body input stream: the HttpMethodBase issues a warning but does not let you call the "setResponseStream()" method!
        String responseBodyAsString = method.getResponseBodyAsString();
        log.info("  Invocation response:\r\n" + responseBodyAsString);
        Document responseDoc = builder.parse(method.getResponseBodyAsStream());
        Element wrapperElt = responseDoc.getDocumentElement();
        if (!wrapperElt.getNodeName().equals("rsp")) {
            throw new ServiceInternalException(
                    "unexpected response returned by RTM service: " + responseBodyAsString);
        } else {
            String stat = wrapperElt.getAttribute("stat");
            if (stat.equals("fail")) {
                Node errElt = wrapperElt.getFirstChild();
                while (errElt != null
                        && (errElt.getNodeType() != Node.ELEMENT_NODE || !errElt.getNodeName().equals("err"))) {
                    errElt = errElt.getNextSibling();
                }
                if (errElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by RTM service: " + responseBodyAsString);
                } else {
                    throw new ServiceException(Integer.parseInt(((Element) errElt).getAttribute("code")),
                            ((Element) errElt).getAttribute("msg"));
                }
            } else {
                Node dataElt = wrapperElt.getFirstChild();
                while (dataElt != null && (dataElt.getNodeType() != Node.ELEMENT_NODE
                        || dataElt.getNodeName().equals("transaction") == true)) {
                    try {
                        Node nextSibling = dataElt.getNextSibling();
                        if (nextSibling == null) {
                            break;
                        } else {
                            dataElt = nextSibling;
                        }
                    } catch (IndexOutOfBoundsException exception) {
                        // Some implementation may throw this exception, instead of returning a null sibling
                        break;
                    }
                }
                if (dataElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by RTM service: " + responseBodyAsString);
                } else {
                    result = (Element) dataElt;
                }
            }
        }

    } catch (HttpException e) {
        throw new ServiceInternalException("", e);
    } catch (IOException e) {
        throw new ServiceInternalException("", e);
    } catch (SAXException e) {
        throw new ServiceInternalException("", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    lastInvocation = System.currentTimeMillis();
    return result;
}

From source file:cuanto.api.CuantoConnector.java

/**
 * Gets a test case on the server that corresponds to the specified values.
 *
 * @param packageName A test package is the namespace for a particular test. In the case of JUnit or TestNG, it would
 *                    be the fully qualified class name, e.g. org.myorg.MyTestClass
 * @param testName    The name of the test, in JUnit or TestNG this would be the method name.
 * @param parameters  A string representing the parameters for this test, if it is a parameterized test. Otherwise this
 *                    should be null. The server will attempt to locate the TestCase that has these parameters. If the
 *                    parameters don't match, a TestCase will not be returned.
 * @return The found TestCase or null if no match is found.
 *//*from  w w w.  j av  a2s  .c  o m*/
public TestCase getTestCase(String packageName, String testName, String parameters) {
    GetMethod get = (GetMethod) getHttpMethod(HTTP_GET, getCuantoUrl() + "/api/getTestCase");
    get.setQueryString(new NameValuePair[] { new NameValuePair("projectKey", this.projectKey),
            new NameValuePair("packageName", packageName), new NameValuePair("testName", testName),
            new NameValuePair("parameters", parameters) });

    try {
        int httpStatus = getHttpClient().executeMethod(get);
        if (httpStatus == HttpStatus.SC_OK) {
            return TestCase.fromJSON(getResponseBodyAsString(get));
        } else {
            throw new RuntimeException("Getting the TestCase failed with HTTP status code " + httpStatus + ":\n"
                    + getResponseBodyAsString(get));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.rallydev.integration.build.rest.RallyRestService.java

protected String queryForArtifact(String object, String queryStr, String workspaceRef, String fetch) {
    NameValuePair queryParam, fetchParam, wsParam;
    NameValuePair[] pairs;/*from  w  ww.  ja v a  2 s  . c  om*/

    String reqUrl = getUrl() + "/" + object;
    GetMethod get = new GetMethod(reqUrl);
    queryParam = new NameValuePair("query", queryStr);
    wsParam = new NameValuePair("workspace", workspaceRef);
    fetchParam = new NameValuePair("fetch", fetch);
    pairs = new NameValuePair[] { queryParam, wsParam, fetchParam };
    get.setQueryString(pairs);
    try {
        String response = doGet(new HttpClient(), get);
        return response;
    } catch (IOException ex) {
        logMessage("IOException querying for artifact: " + object + ", with query " + queryStr
                + ", in workspace " + workspaceRef);
        logMessage("Exception message was" + ex.getMessage());
        return null;
    }
}

From source file:cuanto.api.CuantoConnector.java

/**
 * Counts how many total TestOutcomes are in TestRun.
 * @param testRun The TestRun.//from  w ww.jav a  2s . c  o m
 * @return The number of TestOutomes.
 */
public Integer countTestOutcomesForTestRun(TestRun testRun) {
    if (testRun.id == null) {
        throw new IllegalArgumentException(
                "The TestRun has no id. Query for the TestRun before getting it's TestOutcomes.");
    }

    GetMethod get = (GetMethod) getHttpMethod(HTTP_GET, getCuantoUrl() + "/api/countTestOutcomes");
    get.setQueryString(new NameValuePair[] { new NameValuePair("id", testRun.id.toString()), });
    try {
        int httpStatus = getHttpClient().executeMethod(get);
        if (httpStatus == HttpStatus.SC_OK) {
            JSONObject jsonResponse = JSONObject.fromObject(getResponseBodyAsString(get));
            return jsonResponse.getInt("count");
        } else {
            throw new RuntimeException("Counting the TestOutcomes failed with HTTP status code " + httpStatus
                    + ":\n" + getResponseBodyAsString(get));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:cuanto.api.CuantoConnector.java

/**
 * Gets all TestRuns for the current project from the Cuanto server.
 * @return All of the TestRuns for the current project in descending order by dateExecuted.
 *//*from w ww.  j a v  a2s .c o  m*/
public List<TestRun> getAllTestRuns() {
    GetMethod get = (GetMethod) getHttpMethod(HTTP_GET, getCuantoUrl() + "/api/getAllTestRuns");
    get.setQueryString(new NameValuePair[] { new NameValuePair("projectKey", this.projectKey) });
    try {
        int httpStatus = getHttpClient().executeMethod(get);
        if (httpStatus == HttpStatus.SC_OK) {
            JSONObject jsonReturned = JSONObject.fromObject(getResponseBodyAsString(get));
            List<TestRun> testRuns = new ArrayList<TestRun>();
            if (jsonReturned.has("testRuns")) {
                JSONArray returnedRuns = jsonReturned.getJSONArray("testRuns");
                for (Object run : returnedRuns) {
                    JSONObject jsonRun = (JSONObject) run;
                    testRuns.add(TestRun.fromJSON(jsonRun));
                }
            } else {
                throw new RuntimeException("JSON response didn't have testRuns node");
            }
            return testRuns;
        } else {
            throw new RuntimeException("Getting the TestRun failed with HTTP status code " + httpStatus + ": \n"
                    + getResponseBodyAsString(get));
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ParseException e) {
        throw new RuntimeException("Unable to parse JSON response: " + e.getMessage(), e);
    }
}

From source file:cuanto.api.CuantoConnector.java

/**
 * Gets all TestOutcomes for the specified TestCase - returned in descending ordered by dateCreated.
 *
 * @param testCase The TestCase for which to fetch TestOutcomes.
 * @return The TestOutcomes for the specified TestCase, in descending order by dateCreated.
 */// www . ja va  2  s.c  o  m
public List<TestOutcome> getAllTestOutcomesForTestCase(TestCase testCase) {
    if (testCase.id == null) {
        throw new IllegalArgumentException(
                "The TestCase has no id. Query for the TestCase before getting it's TestOutcomes.");
    }
    GetMethod get = (GetMethod) getHttpMethod(HTTP_GET, getCuantoUrl() + "/api/getTestOutcomes");
    get.setQueryString(new NameValuePair[] { new NameValuePair("testCase", testCase.id.toString()),
            new NameValuePair("sort", "dateCreated"), new NameValuePair("order", "desc"),
            new NameValuePair("sort", "finishedAt"), new NameValuePair("order", "desc") });
    try {
        int httpStatus = getHttpClient().executeMethod(get);
        if (httpStatus == HttpStatus.SC_OK) {
            JSONObject jsonResponse = JSONObject.fromObject(getResponseBodyAsString(get));
            JSONArray jsonOutcomes = jsonResponse.getJSONArray("testOutcomes");
            List<TestOutcome> outcomesToReturn = new ArrayList<TestOutcome>(jsonOutcomes.size());
            for (Object obj : jsonOutcomes) {
                JSONObject jsonOutcome = (JSONObject) obj;
                outcomesToReturn.add(TestOutcome.fromJSON(jsonOutcome));
            }
            return outcomesToReturn;
        } else {
            throw new RuntimeException("Getting the TestOutcome failed with HTTP status code " + httpStatus
                    + ":\n" + getResponseBodyAsString(get));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ParseException e) {
        throw new RuntimeException("Unable to parse JSON response: " + e.getMessage(), e);
    }
}