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

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

Introduction

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

Prototype

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

Source Link

Document

Adds parameter to URI query.

Usage

From source file:com.kolich.twitter.TwitterApiClient.java

public Either<HttpFailure, List<Tweet>> getTweets(final String username, final int count, final long maxId,
        final long sinceId, final OAuthConsumer consumer) {
    checkNotNull(username, "Username cannot be null!");
    return new TwitterApiGsonClosure<List<Tweet>>(new TypeToken<List<Tweet>>() {
    }.getType(), consumer) {/*www  .jav  a  2 s  . c om*/
        @Override
        public URI getFinalURI(final URI uri) throws Exception {
            final URIBuilder builder = new URIBuilder(uri).addParameter(API_SCREEN_NAME_PARAM, username)
                    .addParameter(API_COUNT_PARAM, Integer.toString(count));
            if (maxId > 0L) {
                builder.addParameter(API_MAXID_PARAM, Long.toString(maxId - 1L));
            }
            if (sinceId > 0L) {
                builder.addParameter(API_SINCEID_PARAM, Long.toString(sinceId));
            }
            return builder.build();
        }
    }.get(STATUSES_USER_TIMELINE_URL);
}

From source file:alien4cloud.paas.cloudify2.rest.external.RestClientExecutor.java

/**
 *
 * @param relativeUrl//from  w w  w.j  a  v a  2 s . c  o  m
 *            The URL to send the delete request to.
 * @param responseTypeReference
 *            The type reference of the response.
 * @param params
 *            Request parameters
 * @param <T> The type of the response.
 * @return The response object from the REST server.
 * @throws RestClientException .
 */
public <T> T delete(final String relativeUrl, final Map<String, String> params,
        final TypeReference<Response<T>> responseTypeReference) throws RestClientException {

    URIBuilder builder;

    try {
        builder = new URIBuilder(getFullUrl(relativeUrl));
    } catch (URISyntaxException e) {
        throw MessagesUtils.createRestClientException(RestClientMessageKeys.INVALID_URL.getName(), e,
                getFullUrl(relativeUrl));
    }

    if (params != null) {
        for (final Map.Entry<String, String> entry : params.entrySet()) {
            builder.addParameter(entry.getKey(), entry.getValue());
        }
    }

    final HttpDelete deleteRequest = new HttpDelete(builder.toString());
    if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, "executing delete request to " + relativeUrl);
    }
    return executeRequest(deleteRequest, responseTypeReference);
}

From source file:nl.surfnet.demo.SurfOAuthClient.java

@Override
public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    AccessTokenInfo tokenInfo = new AccessTokenInfo();

    KeyManagerConfiguration config = KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();

    String introspectionURL = config.getParameter(SurfClientConstants.INTROSPECTION_URL);
    String introspectionConsumerKey = config.getParameter(SurfClientConstants.INTROSPECTION_CK);
    String introspectionConsumerSecret = config.getParameter(SurfClientConstants.INTROSPECTION_CS);
    String encodedSecret = Base64
            .encode(new String(introspectionConsumerKey + ":" + introspectionConsumerSecret).getBytes());

    BufferedReader reader = null;

    try {//  w w w. j av a2s .co  m
        URIBuilder uriBuilder = new URIBuilder(introspectionURL);
        uriBuilder.addParameter("access_token", accessToken);
        uriBuilder.build();

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        HttpClient client = new DefaultHttpClient();

        httpGet.setHeader("Authorization", "Basic " + encodedSecret);
        HttpResponse response = client.execute(httpGet);
        int responseCode = response.getStatusLine().getStatusCode();

        if (log.isDebugEnabled()) {
            log.debug("HTTP Response code : " + responseCode);
        }

        // {"audience":"MappedClient","scopes":["test"],"principal":{"name":"mappedclient","roles":[],"groups":[],"adminPrincipal":false,
        // "attributes":{}},"expires_in":1433059160531}
        HttpEntity entity = response.getEntity();
        JSONObject parsedObject;
        String errorMessage = null;
        reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

        if (HttpStatus.SC_OK == responseCode) {
            //pass bufferReader object  and get read it and retrieve  the parsedJson object
            parsedObject = getParsedObjectByReader(reader);
            if (parsedObject != null) {

                Map valueMap = parsedObject;
                Object principal = valueMap.get("principal");

                if (principal == null) {
                    tokenInfo.setTokenValid(false);
                    return tokenInfo;
                }
                Map principalMap = (Map) principal;
                String clientId = (String) principalMap.get("name");
                Long expiryTimeString = (Long) valueMap.get("expires_in");

                // Returning false if mandatory attributes are missing.
                if (clientId == null || expiryTimeString == null) {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
                    return tokenInfo;
                }

                long currentTime = System.currentTimeMillis();
                long expiryTime = expiryTimeString;
                if (expiryTime > currentTime) {
                    tokenInfo.setTokenValid(true);
                    tokenInfo.setConsumerKey(clientId);
                    tokenInfo.setValidityPeriod(expiryTime - currentTime);
                    // Considering Current Time as the issued time.
                    tokenInfo.setIssuedTime(currentTime);
                    JSONArray scopesArray = (JSONArray) valueMap.get("scopes");

                    if (scopesArray != null && !scopesArray.isEmpty()) {

                        String[] scopes = new String[scopesArray.size()];
                        for (int i = 0; i < scopes.length; i++) {
                            scopes[i] = (String) scopesArray.get(i);
                        }
                        tokenInfo.setScope(scopes);
                    }
                } else {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
                    return tokenInfo;
                }

            } else {
                log.error("Invalid Token " + accessToken);
                tokenInfo.setTokenValid(false);
                tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
                return tokenInfo;
            }
        } //for other HTTP error codes we just pass generic message.
        else {
            log.error("Invalid Token " + accessToken);
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
            return tokenInfo;
        }

    } catch (UnsupportedEncodingException e) {
        handleException("The Character Encoding is not supported. " + e.getMessage(), e);
    } catch (ClientProtocolException e) {
        handleException(
                "HTTP request error has occurred while sending request  to OAuth Provider. " + e.getMessage(),
                e);
    } catch (IOException e) {
        handleException("Error has occurred while reading or closing buffer reader. " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        handleException("Error occurred while building URL with params." + e.getMessage(), e);
    } catch (ParseException e) {
        handleException("Error while parsing response json " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return tokenInfo;
}

From source file:org.jodconverter.task.OnlineConversionTask.java

@SuppressWarnings("unchecked")
private void addPropertiesToBuilder(final URIBuilder uriBuilder, final Map<String, Object> properties,
        final String parameterPrefix) {

    if (properties != null && !properties.isEmpty()) {
        for (final Map.Entry<String, Object> entry : properties.entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();

            // First, check if we are dealing with the FilterData property
            if (FILTER_DATA.equalsIgnoreCase(key) && Map.class.isInstance(value)) {
                // Add all the FilterData properties
                for (final Map.Entry<String, Object> fdentry : ((Map<String, Object>) value).entrySet()) {
                    uriBuilder.addParameter(parameterPrefix + FILTER_DATA_PREFIX_PARAM + fdentry.getKey(),
                            fdentry.getValue().toString());
                }//from  www .ja va 2  s .c  om
            } else if (value instanceof String || value.getClass().isPrimitive()) {
                uriBuilder.addParameter(parameterPrefix + key, value.toString());
            }
        }
    }
}

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. j  ava2  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.instagram4j.DefaultInstagramClient.java

private void addAuth(URIBuilder uri) {
    if (accessToken != null)
        uri.addParameter("access_token", accessToken);
    else/*from  ww w. j  av  a  2s .c  o m*/
        uri.addParameter("client_id", clientId);
}

From source file:br.com.oauthtwo.OAuthTwoClient.java

@Override
public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    AccessTokenInfo tokenInfo = new AccessTokenInfo();

    KeyManagerConfiguration config = KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();

    String introspectionURL = config.getParameter(OAuthTwoConstants.INTROSPECTION_URL);
    String introspectionConsumerKey = config.getParameter(OAuthTwoConstants.INTROSPECTION_CK);
    String introspectionConsumerSecret = config.getParameter(OAuthTwoConstants.INTROSPECTION_CS);
    String encodedSecret = Base64
            .encode(new String(introspectionConsumerKey + ":" + introspectionConsumerSecret).getBytes());

    BufferedReader reader = null;

    try {//from   w  w  w  .j  a va2  s  .  co m
        URIBuilder uriBuilder = new URIBuilder(introspectionURL);
        uriBuilder.addParameter("access_token", accessToken);
        uriBuilder.build();

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        HttpClient client = new DefaultHttpClient();

        httpGet.setHeader("Authorization", "Basic " + encodedSecret);
        HttpResponse response = client.execute(httpGet);
        int responseCode = response.getStatusLine().getStatusCode();

        LOGGER.log(Level.INFO, "HTTP Response code : " + responseCode);

        // {"audience":"MappedClient","scopes":["test"],"principal":{"name":"mappedclient","roles":[],"groups":[],"adminPrincipal":false,
        // "attributes":{}},"expires_in":1433059160531}
        HttpEntity entity = response.getEntity();
        JSONObject parsedObject;
        String errorMessage = null;
        reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

        if (HttpStatus.SC_OK == responseCode) {
            // pass bufferReader object and get read it and retrieve the
            // parsedJson object
            parsedObject = getParsedObjectByReader(reader);
            if (parsedObject != null) {

                Map valueMap = parsedObject;
                Object principal = valueMap.get("principal");

                if (principal == null) {
                    tokenInfo.setTokenValid(false);
                    return tokenInfo;
                }
                Map principalMap = (Map) principal;
                String clientId = (String) principalMap.get("clientId");
                Long expiryTimeString = (Long) valueMap.get("expires_in");
                String endUserName = (String) principalMap.get("name");

                LOGGER.log(Level.INFO,
                        "OAuthTwoClient - clientId:" + clientId + " expires_in:" + expiryTimeString);

                // Returning false if mandatory attributes are missing.
                if (clientId == null || expiryTimeString == null) {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
                    return tokenInfo;
                }

                long currentTime = System.currentTimeMillis();
                long expiryTime = expiryTimeString;
                if (expiryTime > currentTime) {
                    tokenInfo.setTokenValid(true);
                    tokenInfo.setConsumerKey(clientId);
                    tokenInfo.setValidityPeriod(expiryTime - currentTime);
                    // Considering Current Time as the issued time.
                    tokenInfo.setIssuedTime(currentTime);
                    tokenInfo.setEndUserName(endUserName);
                    tokenInfo.setAccessToken(accessToken);
                    //         tokenInfo.

                    JSONArray scopesArray = (JSONArray) valueMap.get("scopes");

                    if (scopesArray != null && !scopesArray.isEmpty()) {

                        String[] scopes = new String[scopesArray.size()];
                        for (int i = 0; i < scopes.length; i++) {
                            scopes[i] = (String) scopesArray.get(i);
                        }
                        tokenInfo.setScope(scopes);
                    }
                } else {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
                    return tokenInfo;
                }

            } else {
                LOGGER.log(Level.SEVERE, "Invalid Token " + accessToken);
                tokenInfo.setTokenValid(false);
                tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
                return tokenInfo;
            }
        } // for other HTTP error codes we just pass generic message.
        else {
            LOGGER.log(Level.SEVERE, "Invalid Token " + accessToken);
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
            return tokenInfo;
        }

    } catch (UnsupportedEncodingException e) {
        handleException("The Character Encoding is not supported. " + e.getMessage(), e);
    } catch (ClientProtocolException e) {
        handleException(
                "HTTP request error has occurred while sending request  to OAuth Provider. " + e.getMessage(),
                e);
    } catch (IOException e) {
        handleException("Error has occurred while reading or closing buffer reader. " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        handleException("Error occurred while building URL with params." + e.getMessage(), e);
    } catch (ParseException e) {
        handleException("Error while parsing response json " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }
    LOGGER.log(Level.INFO, "OAuthTwoClient - getTokenMetada - return SUCCESSFULY" + tokenInfo.getJSONString());

    return tokenInfo;
}

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.java 2s.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;
}