Example usage for org.apache.http.client.utils URIBuilder setParameter

List of usage examples for org.apache.http.client.utils URIBuilder setParameter

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder setParameter.

Prototype

public URIBuilder setParameter(final String param, final String value) 

Source Link

Document

Sets parameter of URI query overriding existing value if set.

Usage

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpAnnotationsEndToEndTest.java

private URI getAnnotationsQueryURI(Map<String, String> parameterMap) throws URISyntaxException {
    URIBuilder builder = new URIBuilder().setScheme("http").setHost("127.0.0.1").setPort(queryPort)
            .setPath("/v2.0/" + tenant_id + "/events/getEvents");

    Set<String> parameters = parameterMap.keySet();
    Iterator<String> setIterator = parameters.iterator();
    while (setIterator.hasNext()) {
        String paramName = setIterator.next();
        builder.setParameter(paramName, parameterMap.get(paramName));
    }/*from   w  w w  .  j a v a 2s .  c o m*/
    return builder.build();
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

/**
 * Searches for items./*from   w  ww  . j  a v  a2s .c  om*/
 * @param query query
 * @param num max number of items
 * @param start start item
 * @param token token (optional)
 * @return query response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public QueryResponse search(String query, long num, long start, String token)
        throws URISyntaxException, IOException {
    URIBuilder builder = new URIBuilder(searchUri());

    builder.setParameter("f", "json");
    builder.setParameter("q", String.format("%s %s", query, QUERY_EXTRAS));
    if (token != null) {
        builder.setParameter("token", token);
    }
    HttpGet req = new HttpGet(builder.build());

    return execute(req, QueryResponse.class);
}

From source file:com.lonepulse.zombielink.request.QueryParamProcessor.java

/**
 * <p>Accepts the {@link InvocationContext} along with an {@link HttpRequestBase} and creates a 
 * <a href="http://en.wikipedia.org/wiki/Query_string">query string</a> using arguments annotated 
 * with @{@link QueryParam} and @{@link QueryParams}; which is subsequently appended to the URI.</p>
 * /*ww  w .  ja  va  2 s  . c  o  m*/
 * <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p>
 * 
 * @param context
 *          the {@link InvocationContext} which is used to discover annotated query parameters
 * <br><br>
 * @param request
 *          prefers an instance of {@link HttpGet} so as to conform with HTTP 1.1; however, other 
 *          request types will be entertained to allow compliance with unusual endpoint definitions 
 * <br><br>
  * @return the same instance of {@link HttpRequestBase} which was given for processing query parameters
 * <br><br>
 * @throws RequestProcessorException
 *          if the creation of a query string failed due to an unrecoverable errorS
 * <br><br>
 * @since 1.3.0
 */
@Override
protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) {

    try {

        URIBuilder uriBuilder = new URIBuilder(request.getURI());

        //add static name and value pairs
        List<Param> constantQueryParams = RequestUtils.findStaticQueryParams(context);

        for (Param param : constantQueryParams) {

            uriBuilder.setParameter(param.name(), param.value());
        }

        //add individual name and value pairs
        List<Entry<QueryParam, Object>> queryParams = Metadata.onParams(QueryParam.class, context);

        for (Entry<QueryParam, Object> entry : queryParams) {

            String name = entry.getKey().value();
            Object value = entry.getValue();

            if (!(value instanceof CharSequence)) {

                StringBuilder errorContext = new StringBuilder().append("Query parameters can only be of type ")
                        .append(CharSequence.class.getName())
                        .append(". Please consider implementing CharSequence ")
                        .append("and providing a meaningful toString() representation for the ")
                        .append("<name> of the query parameter. ");

                throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
            }

            uriBuilder.setParameter(name, ((CharSequence) value).toString());
        }

        //add batch name and value pairs (along with any static params)
        List<Entry<QueryParams, Object>> queryParamMaps = Metadata.onParams(QueryParams.class, context);

        for (Entry<QueryParams, Object> entry : queryParamMaps) {

            Param[] constantParams = entry.getKey().value();

            if (constantParams != null && constantParams.length > 0) {

                for (Param param : constantParams) {

                    uriBuilder.setParameter(param.name(), param.value());
                }
            }

            Object map = entry.getValue();

            if (!(map instanceof Map)) {

                StringBuilder errorContext = new StringBuilder()
                        .append("@QueryParams can only be applied on <java.util.Map>s. ")
                        .append("Please refactor the method to provide a Map of name and value pairs. ");

                throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
            }

            Map<?, ?> nameAndValues = (Map<?, ?>) map;

            for (Entry<?, ?> nameAndValue : nameAndValues.entrySet()) {

                Object name = nameAndValue.getKey();
                Object value = nameAndValue.getValue();

                if (!(name instanceof CharSequence
                        && (value instanceof CharSequence || value instanceof Collection))) {

                    StringBuilder errorContext = new StringBuilder().append(
                            "The <java.util.Map> identified by @QueryParams can only contain mappings of type ")
                            .append("<java.lang.CharSequence, java.lang.CharSequence> or ")
                            .append("<java.lang.CharSequence, java.util.Collection<? extends CharSequence>>");

                    throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                }

                if (value instanceof CharSequence) {

                    uriBuilder.addParameter(((CharSequence) name).toString(),
                            ((CharSequence) value).toString());
                } else { //add multi-valued query params 

                    Collection<?> multivalues = (Collection<?>) value;

                    for (Object multivalue : multivalues) {

                        if (!(multivalue instanceof CharSequence)) {

                            StringBuilder errorContext = new StringBuilder().append(
                                    "Values for the <java.util.Map> identified by @QueryParams can only contain collections ")
                                    .append("of type java.util.Collection<? extends CharSequence>");

                            throw new RequestProcessorException(
                                    new IllegalArgumentException(errorContext.toString()));
                        }

                        uriBuilder.addParameter(((CharSequence) name).toString(),
                                ((CharSequence) multivalue).toString());
                    }
                }
            }
        }

        request.setURI(uriBuilder.build());

        return request;
    } catch (Exception e) {

        throw (e instanceof RequestProcessorException) ? (RequestProcessorException) e
                : new RequestProcessorException(context, getClass(), e);
    }
}

From source file:com.rackspacecloud.blueflood.http.HttpIntegrationTestBase.java

public HttpResponse queryMultiplot(String tenantId, long fromTime, long toTime, String points,
        String resolution, String select, String metricNames) throws URISyntaxException, IOException {
    URIBuilder query_builder = getRollupsQueryURIBuilder().setPath(String.format("/v2.0/%s/views", tenantId));
    query_builder.setParameter("from", Long.toString(fromTime));
    query_builder.setParameter("to", Long.toString(toTime));

    if (!points.isEmpty()) {
        query_builder.setParameter("points", points);
    }//  w  ww . ja  va2s .  com

    if (!resolution.isEmpty()) {
        query_builder.setParameter("resolution", resolution);
    }

    if (!select.isEmpty()) {
        query_builder.setParameter("select", select);
    }

    HttpPost query_post = new HttpPost(query_builder.build());
    HttpEntity entity = new StringEntity(metricNames);
    query_post.setEntity(entity);
    query_post.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());

    return client.execute(query_post);
}

From source file:no.digipost.api.useragreements.client.ApiService.java

public StreamingRateLimitedResponse<UserId> getAgreementOwners(final SenderId senderId,
        final AgreementType agreementType, final Boolean smsNotificationsEnabled,
        final String requestTrackingId) {
    URIBuilder uriBuilder = new URIBuilder(serviceEndpoint)
            .setPath(userAgreementsPath(senderId) + "/agreement-owners")
            .setParameter(AgreementType.QUERY_PARAM_NAME, agreementType.getType());
    if (smsNotificationsEnabled != null) {
        uriBuilder.setParameter("invoice-sms-notification", smsNotificationsEnabled.toString());
    }/*from  w w  w  .j  a v a2s  .  com*/

    HttpGet request = newGetRequest(uriBuilder, requestTrackingId);
    request.setHeader(X_Digipost_UserId, brokerId.serialize());
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(request);
        return new StreamingRateLimitedResponse<>(
                mapOkResponseOrThrowException(response, r -> unmarshallEntities(r, AgreementOwners.class)),
                AgreementOwners::getIdsAsStream);
    } catch (IOException ioe) {
        throw new RuntimeIOException(ioe.getMessage(), ioe);
    } catch (RuntimeException rte) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                rte.addSuppressed(e);
            }
        }
        throw rte;
    }
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

/**
 * Reads item information.//from   w  w  w.j  a va 2s.  co  m
 * @param itemId item id
 * @param token token
 * @return item entry
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public ItemEntry readItem(String itemId, String token) throws IOException, URISyntaxException {
    URIBuilder builder = new URIBuilder(itemInfoUri(itemId));

    builder.setParameter("f", "json");
    if (token != null) {
        builder.setParameter("token", token);
    }
    HttpGet req = new HttpGet(builder.build());

    return execute(req, ItemEntry.class);
}

From source file:com.github.woz_dialog.ros_woz_dialog_project.TTSHTTPClient.java

/**
 * Builds the REST clients for speech recognition and synthesis.
 *
 * @/* w  ww. j av  a2 s.  c o  m*/
 */
private void buildClients() {

    // Initialize the HTTP clients
    asrClient = HttpClientBuilder.create().build();
    ttsClient = HttpClientBuilder.create().build();

    try {

        URIBuilder builder = new URIBuilder();
        builder.setScheme("https");
        builder.setHost("dictation.nuancemobility.net");
        builder.setPort(443);
        builder.setPath("/NMDPAsrCmdServlet/dictation");
        builder.setParameter("appId", APP_ID);
        builder.setParameter("appKey", APP_KEY);
        builder.setParameter("id", "0000");
        asrURI = builder.build();
        builder.setHost("tts.nuancemobility.net");
        builder.setPath("/NMDPTTSCmdServlet/tts");
        builder.setParameter("ttsLang", LANGUAGE);
        builder.setParameter("voice", VOICE);
        ttsURI = builder.build();

    } catch (Exception e) {
        throw new RuntimeException("cannot build client: " + e);
    }
}

From source file:com.yottaa.newrelic.PostJob.java

/**
 * @param params//ww  w.  jav a  2 s.c  o  m
 * @param apiKey
 * @param postedJSON
 * @return
 */
protected Object newrelicPost(JSONObject params, String apiKey, Object postedJSON) {
    Object responseObj = null;

    try {
        URIBuilder builder = new URIBuilder("https://platform-api.newrelic.com");
        builder.setPath("/platform/v1/metrics");

        if (params != null) {
            Iterator it = params.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                builder.setParameter(entry.getKey().toString(), entry.getValue().toString());
            }
        }

        URI uri = builder.build();

        HttpPost httpMethod = new HttpPost(uri);

        httpMethod.setHeader("X-License-Key", apiKey);
        httpMethod.removeHeaders("accept");
        httpMethod.setHeader("Accept", "application/json");

        StringEntity entity = new StringEntity(postedJSON.toString(), HTTP.UTF_8);
        entity.setContentType("application/json");
        httpMethod.setEntity(entity);

        HttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse = client.execute(httpMethod);
        HttpEntity responseEntity = httpResponse.getEntity();
        if (responseEntity != null) {
            String responseStr = EntityUtils.toString(responseEntity);
            JSONParser parser = new JSONParser();
            responseObj = parser.parse(responseStr);
        }
    } catch (UnsupportedEncodingException e) {
        logger.error("Failed to post Yottaa metrics to New Relic", e);
    } catch (ClientProtocolException e) {
        logger.error("Failed to post Yottaa metrics to New Relic", e);
    } catch (IOException e) {
        logger.error("Failed to post Yottaa metrics to New Relic", e);
    } catch (URISyntaxException e) {
        logger.error("Failed to post Yottaa metrics to New Relic", e);
    } catch (ParseException e) {
        logger.error("Failed to post Yottaa metrics to New Relic", e);
    }

    return responseObj;
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

/**
 * Lists content.//  w  w w.  j a  va2s  .  c o  m
 * @param owner owner
 * @param folderId folder id (optional)
 * @param num number items to return
 * @param start start item
 * @param token token (optional)
 * @return content response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public ContentResponse listContent(String owner, String folderId, long num, long start, String token)
        throws URISyntaxException, IOException {
    URIBuilder builder = new URIBuilder(userUri(owner, folderId));

    builder.setParameter("f", "json");
    builder.setParameter("num", Long.toString(num));
    builder.setParameter("start", Long.toString(start));
    if (token != null) {
        builder.setParameter("token", token);
    }
    HttpGet req = new HttpGet(builder.build());

    return execute(req, ContentResponse.class);
}

From source file:org.wikidata.wdtk.wikibaseapi.WikibaseDataFetcher.java

/**
 * Sets the value for the API's "languages" parameter based on the current
 * settings./*from   w ww  .ja v  a2  s .c  om*/
 *
 * @param uriBuilder
 *            the URI builder to set the parameter in
 */
private void setRequestLanguages(URIBuilder uriBuilder) {
    if (this.filter.excludeAllLanguages() || this.filter.getLanguageFilter() == null) {
        return;
    }
    uriBuilder.setParameter("languages", implodeObjects(this.filter.getLanguageFilter()));
}