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

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

Introduction

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

Prototype

public URIBuilder setParameters(final NameValuePair... nvps) 

Source Link

Document

Sets URI query parameters.

Usage

From source file:org.apache.rya.indexing.smarturi.SmartUriAdapter.java

/**
 * Serializes a map into a URI.//w w w .  jav a2s  .  co m
 * @param subject the {@link RyaURI} subject of the Entity. Identifies the
 * thing that is being represented as an Entity.
 * @param map the {@link Map} of {@link URI}s to {@link Value}s.
 * @return the Smart {@link URI}.
 * @throws SmartUriException
 */
public static URI serializeUri(final RyaURI subject, final Map<URI, Value> map) throws SmartUriException {
    final String subjectData = subject.getData();
    final int fragmentPosition = subjectData.indexOf("#");
    String prefix = subjectData;
    String fragment = null;
    if (fragmentPosition > -1) {
        prefix = subjectData.substring(0, fragmentPosition);
        fragment = subjectData.substring(fragmentPosition + 1, subjectData.length());
    }

    URIBuilder uriBuilder = null;
    try {
        if (fragmentPosition > -1) {
            uriBuilder = new URIBuilder(new java.net.URI("urn://" + fragment));
        } else {
            uriBuilder = new URIBuilder(new java.net.URI(subjectData.replaceFirst(":", "://")));
        }
    } catch (final URISyntaxException e) {
        throw new SmartUriException("Unable to serialize a Smart URI from the provided properties", e);
    }
    final List<NameValuePair> nameValuePairs = new ArrayList<>();

    for (final Entry<URI, Value> entry : map.entrySet()) {
        final URI key = entry.getKey();
        final Value value = entry.getValue();
        nameValuePairs.add(new BasicNameValuePair(key.getLocalName(), value.stringValue()));
    }

    uriBuilder.setParameters(nameValuePairs);

    URI uri = null;
    try {
        if (fragmentPosition > -1) {
            final java.net.URI partialUri = uriBuilder.build();
            final String uriString = StringUtils.removeStart(partialUri.getRawSchemeSpecificPart(), "//");
            final URIBuilder fragmentUriBuilder = new URIBuilder(new java.net.URI(prefix));
            fragmentUriBuilder.setFragment(uriString);
            final String fragmentUriString = fragmentUriBuilder.build().toString();
            uri = new URIImpl(fragmentUriString);
        } else {
            final String uriString = uriBuilder.build().toString();
            uri = new URIImpl(uriString);
        }
    } catch (final URISyntaxException e) {
        throw new SmartUriException("Smart URI could not serialize the property map.", e);
    }

    return uri;
}

From source file:com.fredhopper.core.connector.index.upload.impl.RestPublishingStrategy.java

protected URI createUri(final String scheme, final String host, final Integer port, final String servername,
        final String path, final List<NameValuePair> params) {
    Preconditions.checkArgument(StringUtils.isNotBlank(scheme));
    Preconditions.checkArgument(StringUtils.isNotBlank(host));
    Preconditions.checkArgument(port != null);
    Preconditions.checkArgument(StringUtils.isNotBlank(servername));
    Preconditions.checkArgument(StringUtils.isNotBlank(path));

    final URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme(scheme);//from  w  w w.j av a 2s  .  c  o  m
    uriBuilder.setHost(host);
    uriBuilder.setPort(port.intValue());
    uriBuilder.setPath("/".concat(servername).concat(path));
    if (CollectionUtils.isNotEmpty(params)) {
        uriBuilder.setParameters(params);
    }
    try {
        return uriBuilder.build();
    } catch (final URISyntaxException ex) {
        throw new IllegalArgumentException(ex);
    }
}

From source file:es.upv.grycap.coreutils.fiber.net.UrlBuilder.java

/**
 * Creates a new URL relative to the base URL provided in the constructor of this class. The new relative URL
 * includes the path, query parameters and the internal reference of the {@link UrlBuilder#baseUrl base URL} 
 * provided with this class. An additional fragment, as well as additional query parameters can be optionally 
 * added to the new URL. In addition to the parameters passed to the method as an argument, the supplied 
 * fragment can also include parameters that will be added to the created URL. The created URL is normalized 
 * and unencoded before returning it to the caller. The current implementation has the following limitations:
 * <ul>// w w w . j av a2  s . c  om
 * <li>Arrays are not supported: <tt>q=foo&amp;q=bar</tt> will produce an error.</li>
 * <li>Internal references are only supported in the base URL. Any additional reference provided with the 
 * fragment will be silently ignored: the fragment <tt>/rd#ref</tt> will be appended to the base URL as
 * <tt>/rd</tt>, ignoring the internal reference.</li>
 * </ul>
 * @param fragment - optional URL fragment (may include parameters, but not references) that will be added 
 *                   to the base URL
 * @param params - optional query parameters that will be added to the base URL
 * @return A relative URL created from the base URL provided in the constructor of this class and adding the
 *         fragment and parameters passed as arguments to this method.
 */
public String buildRelativeUrl(final @Nullable String fragment, final @Nullable Map<String, String> params) {
    String url = null;
    final Optional<String> fragment2 = ofNullable(trimToNull(fragment));
    try {
        final Optional<URL> fragmentUrl = ofNullable(
                fragment2.isPresent() ? new URL("http://example.com/" + fragment2.get()) : null);
        final URIBuilder uriBuilder = new URIBuilder();
        // add path
        uriBuilder.setPath(new StringBuilder(ofNullable(trimToNull(baseUrl.getPath())).orElse("/"))
                .append(fragmentUrl.isPresent() ? "/" + stripEnd(fragmentUrl.get().getPath(), "/") : "")
                .toString().replaceAll("[/]{2,}", "/"));
        // add query parameters
        if (isNotBlank(baseUrl.getQuery())) {
            uriBuilder.setParameters(URLEncodedUtils.parse(baseUrl.getQuery(), defaultCharset()));
        }
        if (fragmentUrl.isPresent() && isNotBlank(fragmentUrl.get().getQuery())) {
            URLEncodedUtils.parse(fragmentUrl.get().getQuery(), defaultCharset()).stream().forEach(p -> {
                uriBuilder.addParameter(p.getName(), p.getValue());
            });
        }
        ofNullable(params).orElse(emptyMap()).entrySet().stream().forEach(p -> {
            uriBuilder.addParameter(p.getKey(), p.getValue());
        });
        // add internal reference
        uriBuilder.setFragment(baseUrl.getRef());
        // build relative URL
        url = uriBuilder.build().normalize().toString();
    } catch (MalformedURLException | URISyntaxException e) {
        throw new IllegalStateException(
                new StringBuilder("Failed to create relative URL from provided parameters: fragment=")
                        .append(fragment2.orElse("null")).append(", params=")
                        .append(params != null ? params.toString() : "null").toString(),
                e);
    }
    return url;
}

From source file:org.exfio.weave.storage.StorageContext.java

private URI buildCollectionUri(String collection, String[] ids, Double older, Double newer, Integer index_above,
        Integer index_below, Integer limit, Integer offset, String sort, String format, boolean full)
        throws WeaveException {

    URI location = this.storageURL.resolve(URIUtils.sanitize(String.format("storage/%s", collection)));

    //Build list of URL querystring parameters
    List<NameValuePair> params = new LinkedList<NameValuePair>();

    if (ids != null && ids.length > 0) {
        String value = "";
        String delim = "";
        for (int i = 0; i < ids.length; i++) {
            value = value + delim + ids[i];
            delim = ",";
        }//w  w w.  j  ava 2 s . co  m
        params.add(new BasicNameValuePair("ids", value));
    }
    if (older != null) {
        params.add(new BasicNameValuePair("older", String.format("%.2f", older.doubleValue())));
    }
    if (newer != null) {
        params.add(new BasicNameValuePair("newer", String.format("%.2f", newer.doubleValue())));
    }
    if (index_above != null) {
        params.add(new BasicNameValuePair("index_above", index_above.toString()));
    }
    if (index_below != null) {
        params.add(new BasicNameValuePair("index_below", index_below.toString()));
    }
    if (limit != null) {
        params.add(new BasicNameValuePair("limit", limit.toString()));
    }
    if (offset != null) {
        params.add(new BasicNameValuePair("offset", offset.toString()));
    }
    if (sort != null) {
        sort = sort.toLowerCase();
        if (sort.matches("oldest|newest|index")) {
            params.add(new BasicNameValuePair("sort", sort.toString()));
        } else {
            throw new WeaveException(
                    String.format("getCollection() sort parameter value of '%s' not recognised", sort));
        }
    }
    if (format != null) {
        //Only default format supported
        throw new WeaveException(
                String.format("getCollection() format parameter value of '%s' not supported", format));
    }
    if (full) {
        //returns entire WBO
        params.add(new BasicNameValuePair("full", "1"));
    }

    try {
        //FIXME - use URI builder for all uri handling

        //Use URIBuilder to encode query string parameters. java.util.URI DOES NOT correctly handle commas
        URIBuilder uri = new URIBuilder(location);
        if (params.size() > 0) {
            uri.setParameters(params);
        }
        location = new URI(uri.toString());
    } catch (URISyntaxException e) {
        throw new WeaveException(e);
    }

    return location;
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

private void setQueryString(URIBuilder uriBuilder, List<NameValuePair> queryParameters) {
    if (queryParameters.size() > 0) {
        uriBuilder.setParameters(queryParameters);
    }
}

From source file:lh.api.showcase.server.api.lh.ApiRequestFactoryLhAbstract.java

@Override
public URI getRequestUri(ApiDataArea area, NameValuePair resourceNameKey,
        List<NameValuePair> subResourceNameKey, List<NameValuePair> optionKeyValue) throws URISyntaxException {

    Preconditions.checkNotNull(area);// w  ww.  ja va2 s.c om
    Preconditions.checkNotNull(resourceNameKey);
    Preconditions.checkArgument(StringUtils.isNotEmpty(resourceNameKey.getName()));

    URIBuilder urib = new URIBuilder();
    urib.setScheme(getScheme());
    urib.setHost(getHost());

    StringBuilder sb = new StringBuilder();
    // build path
    sb.append("/");
    sb.append(getVersion());
    sb.append("/");
    // area
    sb.append(area.toString().toLowerCase());
    sb.append("/");
    // resource
    sb.append(resourceNameKey.getName());
    if (StringUtils.isNotEmpty(resourceNameKey.getValue())) {
        sb.append("/");
        sb.append(resourceNameKey.getValue());
    }
    // sub resources
    if (subResourceNameKey != null) {
        for (NameValuePair vp : subResourceNameKey) {
            if (StringUtils.isEmpty(vp.getName())) {
                continue;
            }
            sb.append("/");
            sb.append(vp.getName());
            if (StringUtils.isNotEmpty(vp.getValue())) {
                sb.append("/");
                sb.append(vp.getValue());
            }
        }
    }
    urib.setPath(sb.toString());
    // parameters
    if (optionKeyValue != null && !optionKeyValue.isEmpty()) {
        urib.setParameters(optionKeyValue);
    }
    return urib.build();
}

From source file:com.clxcommunications.xms.ApiConnection.java

/**
 * Helper returning an endpoint URL for the given sub-path and query
 * parameters./*from   w w w .  j  av  a 2s . co  m*/
 * 
 * @param subPath
 *            path fragment to place after the base path
 * @param params
 *            the query parameters, may be empty
 * @return a non-null endpoint URL
 */
@Nonnull
private URI endpoint(@Nonnull String subPath, @Nonnull List<NameValuePair> params) {
    try {
        String spid = URLEncoder.encode(servicePlanId(), "UTF-8");
        String path = endpoint().getPath() + "/v1/" + spid + subPath;
        URIBuilder uriBuilder = new URIBuilder(endpoint()).setPath(path);

        if (!params.isEmpty()) {
            uriBuilder.setParameters(params);
        }

        return uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.ibm.iotf.client.api.APIClient.java

private HttpResponse casePutFromConnect(List<NameValuePair> queryParameters, String url, String method,
        StringEntity input, String encodedString) throws URISyntaxException, IOException {
    URIBuilder putBuilder = new URIBuilder(url);
    if (queryParameters != null) {
        putBuilder.setParameters(queryParameters);
    }/*  w ww.j a va2  s .com*/
    HttpPut put = new HttpPut(putBuilder.build());
    put.setEntity(input);
    put.addHeader("Content-Type", "application/json");
    put.addHeader("Accept", "application/json");
    put.addHeader("Authorization", "Basic " + encodedString);
    try {
        HttpClient client = HttpClientBuilder.create().useSystemProperties().setSslcontext(sslContext).build();
        return client.execute(put);
    } catch (IOException e) {
        LoggerUtility.warn(CLASS_NAME, method, e.getMessage());
        throw e;
    }

}