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:org.springframework.boot.cli.command.init.ProjectGenerationRequest.java

/**
 * Generates the URI to use to generate a project represented by this request.
 * @param metadata the metadata that describes the service
 * @return the project generation URI/*  w w  w  . j  ava2s  .c o m*/
 */
URI generateUrl(InitializrServiceMetadata metadata) {
    try {
        URIBuilder builder = new URIBuilder(this.serviceUrl);
        StringBuilder sb = new StringBuilder();
        if (builder.getPath() != null) {
            sb.append(builder.getPath());
        }

        ProjectType projectType = determineProjectType(metadata);
        this.type = projectType.getId();
        sb.append(projectType.getAction());
        builder.setPath(sb.toString());

        if (!this.dependencies.isEmpty()) {
            builder.setParameter("dependencies",
                    StringUtils.collectionToCommaDelimitedString(this.dependencies));
        }

        if (this.groupId != null) {
            builder.setParameter("groupId", this.groupId);
        }
        String resolvedArtifactId = resolveArtifactId();
        if (resolvedArtifactId != null) {
            builder.setParameter("artifactId", resolvedArtifactId);
        }
        if (this.version != null) {
            builder.setParameter("version", this.version);
        }
        if (this.name != null) {
            builder.setParameter("name", this.name);
        }
        if (this.description != null) {
            builder.setParameter("description", this.description);
        }
        if (this.packageName != null) {
            builder.setParameter("packageName", this.packageName);
        }
        if (this.type != null) {
            builder.setParameter("type", projectType.getId());
        }
        if (this.packaging != null) {
            builder.setParameter("packaging", this.packaging);
        }
        if (this.javaVersion != null) {
            builder.setParameter("javaVersion", this.javaVersion);
        }
        if (this.language != null) {
            builder.setParameter("language", this.language);
        }
        if (this.bootVersion != null) {
            builder.setParameter("bootVersion", this.bootVersion);
        }

        return builder.build();
    } catch (URISyntaxException e) {
        throw new ReportableException("Invalid service URL (" + e.getMessage() + ")");
    }
}

From source file:fr.gael.dhus.olingo.v1.Processor.java

/** Makes the `next` link for navigation purposes. */
private String makeNextLink(int skip) throws ODataException {
    try {/*from w w  w  .  j  a v  a  2s . c  o m*/
        String selfLnk = ServiceFactory.ROOT_URL;
        URIBuilder ub = new URIBuilder(selfLnk);
        ub.setParameter("$skip", String.valueOf(skip));
        return ub.toString();
    } catch (URISyntaxException ex) {
        throw new ODataException("Cannot make next link", ex);
    }
}

From source file:io.seldon.external.ExternalItemRecommendationAlgorithm.java

@Override
public ItemRecommendationResultSet recommend(String client, Long user, Set<Integer> dimensions,
        int maxRecsCount, RecommendationContext ctxt, List<Long> recentItemInteractions) {
    long timeNow = System.currentTimeMillis();
    String recommenderName = ctxt.getOptsHolder().getStringOption(ALG_NAME_PROPERTY_NAME);
    String baseUrl = ctxt.getOptsHolder().getStringOption(URL_PROPERTY_NAME);
    if (ctxt.getInclusionKeys().isEmpty()) {
        logger.warn("Cannot get external recommendations are no includers were used. Returning 0 results");
        return new ItemRecommendationResultSet(recommenderName);
    }//from   w ww  .ja  v a 2 s.com
    URI uri = URI.create(baseUrl);
    try {
        URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort())
                .setPath(uri.getPath()).setParameter("client", client).setParameter("user_id", user.toString())
                .setParameter("recent_interactions", StringUtils.join(recentItemInteractions, ","))
                .setParameter("dimensions", StringUtils.join(dimensions, ","))
                .setParameter("exclusion_items", StringUtils.join(ctxt.getExclusionItems(), ","))
                .setParameter("data_key", StringUtils.join(ctxt.getInclusionKeys(), ","))
                .setParameter("limit", String.valueOf(maxRecsCount));
        if (ctxt.getCurrentItem() != null)
            builder.setParameter("item_id", ctxt.getCurrentItem().toString());
        uri = builder.build();
    } catch (URISyntaxException e) {
        logger.error("Couldn't create URI for external recommender with name " + recommenderName, e);
        return new ItemRecommendationResultSet(recommenderName);
    }
    HttpContext context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(uri);
    try {
        if (logger.isDebugEnabled())
            logger.debug("Requesting " + httpGet.getURI().toString());
        CloseableHttpResponse resp = httpClient.execute(httpGet, context);
        try {
            if (resp.getStatusLine().getStatusCode() == 200) {
                ConsumerBean c = new ConsumerBean(client);
                ObjectReader reader = mapper.reader(AlgsResult.class);
                AlgsResult recs = reader.readValue(resp.getEntity().getContent());
                List<ItemRecommendationResultSet.ItemRecommendationResult> results = new ArrayList<>(
                        recs.recommended.size());
                for (AlgResult rec : recs.recommended) {
                    Map<String, Integer> attrDimsCandidate = itemService.getDimensionIdsForItem(c, rec.item);
                    if (CollectionUtils.containsAny(dimensions, attrDimsCandidate.values())
                            || dimensions.contains(Constants.DEFAULT_DIMENSION)) {
                        if (logger.isDebugEnabled())
                            logger.debug("Adding item " + rec.item);
                        results.add(
                                new ItemRecommendationResultSet.ItemRecommendationResult(rec.item, rec.score));
                    } else {
                        if (logger.isDebugEnabled())
                            logger.debug("Rejecting item " + rec.item + " as not in dimensions " + dimensions);
                    }
                }
                if (logger.isDebugEnabled())
                    logger.debug("External recommender took " + (System.currentTimeMillis() - timeNow) + "ms");
                return new ItemRecommendationResultSet(results, recommenderName);
            } else {
                logger.error(
                        "Couldn't retrieve recommendations from external recommender -- bad http return code: "
                                + resp.getStatusLine().getStatusCode());
            }
        } finally {
            if (resp != null)
                resp.close();
        }
    } catch (IOException e) {
        logger.error("Couldn't retrieve recommendations from external recommender - ", e);
    } catch (Exception e) {
        logger.error("Couldn't retrieve recommendations from external recommender - ", e);
    }
    return new ItemRecommendationResultSet(recommenderName);
}

From source file:org.apache.ambari.server.controller.metrics.ganglia.GangliaPropertyProvider.java

/**
 * Get the spec to locate the Ganglia stream from the given
 * request info.//from   www  .jav  a2 s  .  c o  m
 *
 * @param clusterName   the cluster name
 * @param clusterSet    the set of ganglia cluster names
 * @param hostSet       the set of host names
 * @param metricSet     the set of metric names
 * @param temporalInfo  the temporal information
 *
 * @return the spec, like http://example.com/path?param1=val1&paramn=valn
 *
 * @throws org.apache.ambari.server.controller.spi.SystemException if unable to get the Ganglia Collector host name
 */
private String getSpec(String clusterName, Set<String> clusterSet, Set<String> hostSet, Set<String> metricSet,
        TemporalInfo temporalInfo) throws SystemException {

    String clusters = getSetString(clusterSet, -1);
    String hosts = getSetString(hostSet, -1);
    String metrics = getSetString(metricSet, -1);

    URIBuilder uriBuilder = new URIBuilder();

    if (configuration.isHttpsEnabled()) {
        uriBuilder.setScheme("https");
    } else {
        uriBuilder.setScheme("http");
    }

    uriBuilder.setHost(hostProvider.getCollectorHostName(clusterName, GANGLIA));

    uriBuilder.setPath("/cgi-bin/rrd.py");

    uriBuilder.setParameter("c", clusters);

    if (hosts.length() > 0) {
        uriBuilder.setParameter("h", hosts);
    }

    if (metrics.length() > 0) {
        uriBuilder.setParameter("m", metrics);
    } else {
        // get all metrics
        uriBuilder.setParameter("m", ".*");
    }

    if (temporalInfo != null) {
        long startTime = temporalInfo.getStartTime();
        if (startTime != -1) {
            uriBuilder.setParameter("s", String.valueOf(startTime));
        }

        long endTime = temporalInfo.getEndTime();
        if (endTime != -1) {
            uriBuilder.setParameter("e", String.valueOf(endTime));
        }

        long step = temporalInfo.getStep();
        if (step != -1) {
            uriBuilder.setParameter("r", String.valueOf(step));
        }
    } else {
        uriBuilder.setParameter("e", "now");
        uriBuilder.setParameter("pt", "true");
    }

    return uriBuilder.toString();
}

From source file:org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient.java

private String createRequestUrl(String buildName, String buildNumber, String signMethod, String passphrase)
        throws URISyntaxException {
    URIBuilder urlBuilder = new URIBuilder();
    urlBuilder.setPath(artifactoryUrl + PUSH_TO_BINTRAY_REST_URL + buildName + "/" + buildNumber);

    if (StringUtils.isNotEmpty(passphrase)) {
        urlBuilder.setParameter("gpgPassphrase", passphrase);
    }//w ww. j  a v  a 2 s. c  o  m
    if (!StringUtils.equals(signMethod, "descriptor")) {
        urlBuilder.setParameter("gpgSign", signMethod);
    }
    return urlBuilder.toString();
}

From source file:com.adobe.aem.demo.communities.Loader.java

private static String doGet(String hostname, String port, String url, String user, String password,
        List<NameValuePair> params) {

    String rawResponse = null;//w  w w .  java2s  .co m

    try {

        HttpHost target = new HttpHost(hostname, Integer.parseInt(port), "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(user, password));
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();

        try {

            // Adding the Basic Authentication data to the context for this command
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            // Composing the root URL for all subsequent requests
            URIBuilder uribuilder = new URIBuilder();
            uribuilder.setScheme("http").setHost(hostname).setPort(Integer.parseInt(port)).setPath(url);

            // Adding the params
            if (params != null)
                for (NameValuePair nvp : params) {
                    uribuilder.setParameter(nvp.getName(), nvp.getValue());
                }

            URI uri = uribuilder.build();
            logger.debug("URI built as " + uri.toString());
            HttpGet httpget = new HttpGet(uri);
            CloseableHttpResponse response = httpClient.execute(httpget, localContext);
            try {
                rawResponse = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception ex) {
                logger.error(ex.getMessage());
            } finally {
                response.close();
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage());
        } finally {
            httpClient.close();
        }

    } catch (IOException e) {

        e.printStackTrace();
    }

    return rawResponse;

}

From source file:org.apache.ambari.server.controller.ganglia.GangliaPropertyProvider.java

/**
 * Get the spec to locate the Ganglia stream from the given
 * request info.//from w  ww.jav  a2 s.c o m
 *
 * @param clusterName   the cluster name
 * @param clusterSet    the set of ganglia cluster names
 * @param hostSet       the set of host names
 * @param metricSet     the set of metric names
 * @param temporalInfo  the temporal information
 *
 * @return the spec, like http://example.com/path?param1=val1&paramn=valn
 *
 * @throws org.apache.ambari.server.controller.spi.SystemException if unable to get the Ganglia Collector host name
 */
private String getSpec(String clusterName, Set<String> clusterSet, Set<String> hostSet, Set<String> metricSet,
        TemporalInfo temporalInfo) throws SystemException {

    String clusters = getSetString(clusterSet, -1);
    String hosts = getSetString(hostSet, -1);
    String metrics = getSetString(metricSet, -1);

    URIBuilder uriBuilder = new URIBuilder();

    if (configuration.isGangliaSSL()) {
        uriBuilder.setScheme("https");
    } else {
        uriBuilder.setScheme("http");
    }

    uriBuilder.setHost(hostProvider.getGangliaCollectorHostName(clusterName));

    uriBuilder.setPath("/cgi-bin/rrd.py");

    uriBuilder.setParameter("c", clusters);

    if (hosts.length() > 0) {
        uriBuilder.setParameter("h", hosts);
    }

    if (metrics.length() > 0) {
        uriBuilder.setParameter("m", metrics);
    } else {
        // get all metrics
        uriBuilder.setParameter("m", ".*");
    }

    if (temporalInfo != null) {
        long startTime = temporalInfo.getStartTime();
        if (startTime != -1) {
            uriBuilder.setParameter("s", String.valueOf(startTime));
        }

        long endTime = temporalInfo.getEndTime();
        if (endTime != -1) {
            uriBuilder.setParameter("e", String.valueOf(endTime));
        }

        long step = temporalInfo.getStep();
        if (step != -1) {
            uriBuilder.setParameter("r", String.valueOf(step));
        }
    } else {
        uriBuilder.setParameter("e", "now");
        uriBuilder.setParameter("pt", "true");
    }

    return uriBuilder.toString();
}

From source file:org.wikidata.wdtk.rdf.WikidataPropertyTypes.java

/**
 * Find the datatype of a property online.
 *
 * @param propertyIdValue/*from  www. j a v  a  2s. c o m*/
 * @return IRI of the datatype
 * @throws IOException
 * @throws URISyntaxException
 *             , IOException
 */
String fetchPropertyType(PropertyIdValue propertyIdValue) throws IOException, URISyntaxException {
    logger.info("Fetching datatype of property " + propertyIdValue.getId() + " online.");

    URIBuilder uriBuilder;
    uriBuilder = new URIBuilder(this.webAPIUrl);
    uriBuilder.setParameter("action", "wbgetentities");
    uriBuilder.setParameter("ids", propertyIdValue.getId());
    uriBuilder.setParameter("format", "json");
    uriBuilder.setParameter("props", "datatype");
    InputStream inStream = this.webResourceFetcher.getInputStreamForUrl(uriBuilder.toString());

    JsonNode jsonNode = this.objectMapper.readTree(inStream);
    String datatype = jsonNode.path("entities").path(propertyIdValue.getId()).path("datatype").asText();
    if (datatype == null || "".equals(datatype)) {
        logger.error("Could not find datatype of property " + propertyIdValue.getId() + " online.");
        return null;
    }

    switch (datatype) {
    case "wikibase-item":
        return DatatypeIdValue.DT_ITEM;
    case "wikibase-property":
        return DatatypeIdValue.DT_PROPERTY;
    case "string":
        return DatatypeIdValue.DT_STRING;
    case "quantity":
        return DatatypeIdValue.DT_QUANTITY;
    case "url":
        return DatatypeIdValue.DT_URL;
    case "globe-coordinate":
        return DatatypeIdValue.DT_GLOBE_COORDINATES;
    case "time":
        return DatatypeIdValue.DT_TIME;
    case "commonsMedia":
        return DatatypeIdValue.DT_COMMONS_MEDIA;
    case "monolingualtext":
        return DatatypeIdValue.DT_MONOLINGUAL_TEXT;
    default:
        logger.error("Got unkown datatype " + datatype);
        return null;
    }
}

From source file:org.apache.ambari.server.controller.metrics.timeline.AMSReportPropertyProvider.java

private void setProperties(Resource resource, String clusterName, Request request, Set<String> ids)
        throws SystemException {

    Map<String, MetricReportRequest> reportRequestMap = getPropertyIdMaps(request, ids);
    String host = hostProvider.getCollectorHostName(clusterName, TIMELINE_METRICS);
    String port = hostProvider.getCollectorPort(clusterName, TIMELINE_METRICS);
    URIBuilder uriBuilder = AMSPropertyProvider.getAMSUriBuilder(host,
            port != null ? Integer.parseInt(port) : 6188, configuration.isHttpsEnabled());

    for (Map.Entry<String, MetricReportRequest> entry : reportRequestMap.entrySet()) {
        MetricReportRequest reportRequest = entry.getValue();
        TemporalInfo temporalInfo = reportRequest.getTemporalInfo();
        Map<String, String> propertyIdMap = reportRequest.getPropertyIdMap();

        uriBuilder.removeQuery();//from  w  ww  .  ja  v a 2  s.c o m
        // Call with hostname = null
        uriBuilder.addParameter("metricNames",
                MetricsPropertyProvider.getSetString(propertyIdMap.keySet(), -1));

        uriBuilder.setParameter("appId", "HOST");
        long startTime = temporalInfo.getStartTime();
        if (startTime != -1) {
            uriBuilder.setParameter("startTime", String.valueOf(startTime));
        }

        long endTime = temporalInfo.getEndTime();
        if (endTime != -1) {
            uriBuilder.setParameter("endTime", String.valueOf(endTime));
        }

        TimelineAppMetricCacheKey metricCacheKey = new TimelineAppMetricCacheKey(propertyIdMap.keySet(), "HOST",
                temporalInfo);

        metricCacheKey.setSpec(uriBuilder.toString());

        // Self populating cache updates itself on every get with latest results
        TimelineMetrics timelineMetrics;
        if (metricCache != null && metricCacheKey.getTemporalInfo() != null) {
            timelineMetrics = metricCache.getAppTimelineMetricsFromCache(metricCacheKey);
        } else {
            try {
                timelineMetrics = requestHelper.fetchTimelineMetrics(uriBuilder,
                        temporalInfo.getStartTimeMillis(), temporalInfo.getEndTimeMillis());
            } catch (IOException e) {
                timelineMetrics = null;
            }
        }

        if (timelineMetrics != null) {
            for (TimelineMetric metric : timelineMetrics.getMetrics()) {
                if (metric.getMetricName() != null && metric.getMetricValues() != null) {
                    // Pad zeros or nulls if needed to a clone so we do not cache
                    // padded values
                    TimelineMetric timelineMetricClone = new TimelineMetric(metric);
                    metricsPaddingMethod.applyPaddingStrategy(timelineMetricClone, temporalInfo);

                    String propertyId = propertyIdMap.get(metric.getMetricName());
                    if (propertyId != null) {
                        resource.setProperty(propertyId, getValue(timelineMetricClone, temporalInfo));
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java

public void getStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, RDFHandler handler,
        Resource... contexts) throws IOException, RDFHandlerException, RepositoryException,
        UnauthorizedException, QueryInterruptedException {
    checkRepositoryURL();/*from   w  ww . j a  v  a 2  s  . co  m*/

    try {
        final boolean useTransaction = transactionURL != null;

        String baseLocation = useTransaction ? transactionURL : Protocol.getStatementsLocation(getQueryURL());
        URIBuilder url = new URIBuilder(baseLocation);

        if (subj != null) {
            url.setParameter(Protocol.SUBJECT_PARAM_NAME, Protocol.encodeValue(subj));
        }
        if (pred != null) {
            url.setParameter(Protocol.PREDICATE_PARAM_NAME, Protocol.encodeValue(pred));
        }
        if (obj != null) {
            url.setParameter(Protocol.OBJECT_PARAM_NAME, Protocol.encodeValue(obj));
        }
        for (String encodedContext : Protocol.encodeContexts(contexts)) {
            url.addParameter(Protocol.CONTEXT_PARAM_NAME, encodedContext);
        }
        url.setParameter(Protocol.INCLUDE_INFERRED_PARAM_NAME, Boolean.toString(includeInferred));
        if (useTransaction) {
            url.setParameter(Protocol.ACTION_PARAM_NAME, Action.GET.toString());
        }

        HttpRequestBase method = useTransaction ? new HttpPut(url.build()) : new HttpGet(url.build());

        try {
            getRDF(method, handler, true);
        } catch (MalformedQueryException e) {
            logger.warn("Server reported unexpected malfored query error", e);
            throw new RepositoryException(e.getMessage(), e);
        } finally {
            method.reset();
        }
    } catch (URISyntaxException e) {
        throw new AssertionError(e);
    }
}