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.cloud.utils.rest.RESTServiceConnector.java

@SuppressWarnings("unchecked")
public <T> T executeRetrieveObject(final Type returnObjectType, final String uri,
        final Map<String, String> parameters) throws CloudstackRESTException {
    final GetMethod gm = (GetMethod) createMethod(GET_METHOD_TYPE, uri);
    gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
    if (parameters != null && !parameters.isEmpty()) {
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
        for (final Entry<String, String> e : parameters.entrySet()) {
            nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue()));
        }// w  w  w. ja v a 2 s  .c om
        gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
    }

    executeMethod(gm);

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

    T returnValue;
    try {
        returnValue = (T) gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
    } catch (final IOException e) {
        s_logger.error("IOException while retrieving response body", e);
        throw new CloudstackRESTException(e);
    } finally {
        gm.releaseConnection();
    }
    return returnValue;
}

From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java

public void login() {
    // create client and configure it
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    // instantiating a new method and configuring it
    GetMethod method = new GetMethod(restCommandUrlPrefix + "login");
    method.setFollowRedirects(true); // ?
    // Provide custom retry handler is necessary (?)
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] params = new NameValuePair[] { new NameValuePair("username", "admin"),
            new NameValuePair("password", "admin") };
    method.setQueryString(params);

    try {//from   w ww  . j  a  v a 2 s  .  c o m
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody)); // TODO rm

        HashSet<String> defaultElementSet = new HashSet<String>(
                Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE,
                        RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE }));
        HashMap<String, String> elementValueMap = new HashMap<String, String>(6);

        try {
            XMLEventReader xmlReader = XmlHelper.getXMLInputFactory()
                    .createXMLEventReader(new ByteArrayInputStream(responseBody));
            StringBuffer singleLevelTextBuf = null;
            while (xmlReader.hasNext()) {
                XMLEvent event = xmlReader.nextEvent();
                switch (event.getEventType()) {
                case XMLEvent.CHARACTERS:
                case XMLEvent.CDATA:
                    if (singleLevelTextBuf != null) {
                        singleLevelTextBuf.append(event.asCharacters().getData());
                    } // else element not meaningful
                    break;
                case XMLEvent.START_ELEMENT:
                    StartElement startElement = event.asStartElement();
                    String elementName = startElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)
                            // TODO another command specific level
                            || "ticket".equals(elementName)) {
                        // reinit buffer at start of meaningful elements
                        singleLevelTextBuf = new StringBuffer();
                    } else {
                        singleLevelTextBuf = null; // not useful
                    }
                    break;
                case XMLEvent.END_ELEMENT:
                    if (singleLevelTextBuf == null) {
                        break; // element not meaningful
                    }

                    // TODO or merely put it in the map since the element has been tested at start
                    EndElement endElement = event.asEndElement();
                    elementName = endElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)) {
                        String value = singleLevelTextBuf.toString();
                        elementValueMap.put(elementName, value);
                        // TODO test if it is code and it is not OK, break to error handling
                    }
                    // TODO another command specific level
                    else if ("ticket".equals(elementName)) {
                        ticket = singleLevelTextBuf.toString();
                    }
                    // singleLevelTextBuf = new StringBuffer(); // no ! in start
                    break;
                }
            }
        } catch (XMLStreamException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Throwable t) {
            // TODO Auto-generated catch block
            t.printStackTrace();
            //throw t;
        }

        String code = elementValueMap.get(RestConstants.TAG_CODE);
        assertTrue(RestConstants.CODE_OK.equals(code));
        System.out.println("got ticket " + ticket);

    } catch (HttpException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:cuanto.api.CuantoConnector.java

/**
 * Gets all TestOutcomes for the specified TestCase in the specified TestRun. In most normal Cuanto usages, a TestRun
 * will only have a single TestOutcome per TestCase. TestOutcomes will be in descending order by their finishedAt
 * values (if they have them) or dateCreated otherwise.
 *
 * @param testRun  The TestRun to search.
 * @param testCase The TestCase for which to retrieve TestOutcomes.
 * @return A list of all the TestOutcomes for the specified TestCase and TestRun.
 *///from   ww  w .  j  a  v  a2  s . c  o  m
public List<TestOutcome> getTestCaseOutcomesForTestRun(TestCase testCase, TestRun testRun) {
    if (testRun.id == null) {
        throw new IllegalArgumentException(
                "The TestRun has no id. Query for the TestRun before getting it's TestOutcomes.");
    }
    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/getTestCaseOutcomesForTestRun");
    get.setQueryString(new NameValuePair[] { new NameValuePair("testRun", testRun.id.toString()),
            new NameValuePair("testCase", testCase.id.toString()) });
    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);
    }
}

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

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

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

    InputStream feedbacksStream = null;
    try {//from ww  w. ja  va 2 s.c o  m
        httpClient.executeMethod(getMethod);
        feedbacksStream = getMethod.getResponseBodyAsStream();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }

    Recommendations recommendations = null;

    try {
        JAXBContext jc = JAXBContext.newInstance(Recommendations.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        recommendations = (Recommendations) unmarshaller.unmarshal(feedbacksStream);
    } catch (JAXBException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
    return recommendations;
}

From source file:com.cloud.network.bigswitch.BigSwitchBcfApi.java

@SuppressWarnings("unchecked")
protected <T> T executeRetrieveObject(final Type returnObjectType, final String uri,
        final Map<String, String> parameters) throws BigSwitchBcfApiException {
    checkInvariants();//from   ww w  .  j a va  2  s .c  om

    GetMethod gm = (GetMethod) createMethod("get", uri, _port);

    setHttpHeader(gm);

    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()));
        }
        gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
    }

    executeMethod(gm);

    String hash = checkResponse(gm, "BigSwitch HTTP get failed: ");

    T returnValue;
    try {
        // CAUTIOUS: Safety margin of 2048 characters - extend if needed.
        returnValue = (T) gson.fromJson(gm.getResponseBodyAsString(2048), returnObjectType);
    } catch (IOException e) {
        S_LOGGER.error("IOException while retrieving response body", e);
        throw new BigSwitchBcfApiException(e);
    } finally {
        gm.releaseConnection();
    }
    if (returnValue instanceof ControlClusterStatus) {
        if (HASH_CONFLICT.equals(hash)) {
            isMaster = true;
            ((ControlClusterStatus) returnValue).setTopologySyncRequested(true);
        } else if (!HASH_IGNORE.equals(hash) && !isMaster) {
            isMaster = true;
            ((ControlClusterStatus) returnValue).setTopologySyncRequested(true);
        }
    }
    return returnValue;
}

From source file:com.cloud.network.bigswitch.BigSwitchVnsApi.java

@SuppressWarnings("unchecked")
protected <T> T executeRetrieveObject(Type returnObjectType, String uri, int port,
        Map<String, String> parameters) throws BigSwitchVnsApiException {
    if (_host == null || _host.isEmpty()) {
        throw new BigSwitchVnsApiException("Hostname is null or empty");
    }// w  w  w .j  a va2s.com

    GetMethod gm = (GetMethod) createMethod("get", uri, port);
    gm.setRequestHeader(CONTENT_TYPE, CONTENT_JSON);
    gm.setRequestHeader(ACCEPT, CONTENT_JSON);
    gm.setRequestHeader(HTTP_HEADER_INSTANCE_ID, CLOUDSTACK_INSTANCE_ID);

    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()));
        }
        gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
    }

    executeMethod(gm);

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

    Gson gson = new Gson();
    T returnValue;
    try {
        returnValue = (T) gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
    } catch (IOException e) {
        s_logger.error("IOException while retrieving response body", e);
        throw new BigSwitchVnsApiException(e);
    } finally {
        gm.releaseConnection();
    }
    return returnValue;
}

From source file:com.funambol.json.dao.JsonDAOImpl.java

public JsonResponse getNewItemKeys(String token, long since, long until) throws HttpException, IOException {

    String request = Utility.getUrl(jsonServerUrl, resourceType, GET_NEW_ITEM_KEYS_URL);

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: start getNewItemKeys '" + since + "; '" + until + "'");
    }//  w ww.j a v a  2  s .c  om

    GetMethod get = new GetMethod(request);
    get.setRequestHeader(Utility.TOKEN_HEADER_NAME, token);
    NameValuePair[] httpParameters = { new NameValuePair(SINCE, Long.toString(since)),
            new NameValuePair(UNTIL, Long.toString(until)) };
    get.setQueryString(httpParameters);

    int statusCode = 0;
    String responseBody = null;
    try {
        statusCode = httpClient.executeMethod(get);
        responseBody = get.getResponseBodyAsString();
    } finally {
        get.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: getNewItemKeys " + responseBody);
        log.trace("JsonDAOImpl: finish getNewItemKeys");
    }

    JsonResponse response = new JsonResponse(statusCode, responseBody);

    return response;
}

From source file:com.funambol.json.dao.JsonDAOImpl.java

public JsonResponse getUpdatedItemKeys(String token, long since, long until) throws HttpException, IOException {

    String request = Utility.getUrl(jsonServerUrl, resourceType, GET_UPDATED_ITEM_KEYS_URL);

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: start getUpdatedItemKeys '" + since + "; '" + until + "'");
    }/*from ww w.j a  v a2  s .  com*/

    GetMethod get = new GetMethod(request);
    get.setRequestHeader(Utility.TOKEN_HEADER_NAME, token);
    NameValuePair[] httpParameters = { new NameValuePair(SINCE, Long.toString(since)),
            new NameValuePair(UNTIL, Long.toString(until)) };
    get.setQueryString(httpParameters);

    int statusCode = 0;
    String responseBody = null;
    try {
        statusCode = httpClient.executeMethod(get);
        responseBody = get.getResponseBodyAsString();
    } finally {
        get.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: getUpdatedItemKeys " + responseBody);
        log.trace("JsonDAOImpl: finish getUpdatedItemKeys");
    }

    JsonResponse response = new JsonResponse(statusCode, responseBody);

    return response;
}

From source file:com.funambol.json.dao.JsonDAOImpl.java

public JsonResponse getDeletedItemKeys(String token, long since, long until) throws HttpException, IOException {

    String request = Utility.getUrl(jsonServerUrl, resourceType, GET_DELETED_ITEM_KEYS_URL);

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: start getDeletedItemKeys '" + since + "; '" + until + "'");
    }/*w ww. j  a va 2s  .c  o  m*/

    GetMethod get = new GetMethod(request);
    get.setRequestHeader(Utility.TOKEN_HEADER_NAME, token);
    NameValuePair[] httpParameters = { new NameValuePair(SINCE, Long.toString(since)),
            new NameValuePair(UNTIL, Long.toString(until)) };
    get.setQueryString(httpParameters);

    int statusCode = 0;
    String responseBody = null;
    try {
        statusCode = httpClient.executeMethod(get);
        responseBody = get.getResponseBodyAsString();
    } finally {
        get.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: getDeletedItemKeys " + responseBody);
        log.trace("JsonDAOImpl: finish getDeletedItemKeys");
    }

    JsonResponse response = new JsonResponse(statusCode, responseBody);

    return response;
}

From source file:com.cloud.network.nicira.NiciraNvpApi.java

private <T> T executeRetrieveObject(Type returnObjectType, String uri, Map<String, String> parameters)
        throws NiciraNvpApiException {
    String url;/*from   ww w.  j ava 2  s.com*/
    try {
        url = new URL(_protocol, _host, uri).toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build Nicira API URL", e);
        throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
    }

    GetMethod gm = new GetMethod(url);
    gm.setRequestHeader("Content-Type", "application/json");
    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()));
        }
        gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
    }

    executeMethod(gm);

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

    Gson gson = new Gson();
    T returnValue;
    try {
        returnValue = (T) gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
    } catch (IOException e) {
        s_logger.error("IOException while retrieving response body", e);
        throw new NiciraNvpApiException(e);
    } finally {
        gm.releaseConnection();
    }
    return returnValue;
}