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:mx.openpay.client.core.impl.DefaultHttpServiceClient.java

protected URI createUriWithParams(final String url, final Map<String, String> queryParams)
        throws IllegalArgumentException {
    URIBuilder builder = new URIBuilder(URI.create(url));
    for (Entry<String, String> entry : queryParams.entrySet()) {
        if (entry.getValue() != null) {
            builder.addParameter(entry.getKey(), entry.getValue());
        }/*ww w  .j av  a  2  s .  co m*/
    }
    try {
        return builder.build();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.collective.celos.CelosClient.java

public List<RegisterKey> getRegisterKeys(BucketID bucket, String prefix) throws Exception {
    URIBuilder uriBuilder = new URIBuilder(address);
    uriBuilder.setPath(uriBuilder.getPath() + LIST_REGISTER_KEYS_PATH);
    uriBuilder.addParameter(BUCKET_PARAM, bucket.toString());
    if (!StringUtils.isEmpty(prefix)) {
        uriBuilder.addParameter(PREFIX_PARAM, prefix);
    }/* ww  w.j ava 2  s. c o m*/
    InputStream contentStream = execute(new HttpGet(uriBuilder.build())).getEntity().getContent();
    return parseKeyList(contentStream);
}

From source file:com.collective.celos.CelosClient.java

/**
 * Returns the specified register value, or null if not found.
 *//*from w w w.  ja  v a 2s .  c  om*/
public JsonNode getRegister(BucketID bucket, RegisterKey key) throws Exception {
    URIBuilder uriBuilder = new URIBuilder(address);
    uriBuilder.setPath(uriBuilder.getPath() + REGISTER_PATH);
    uriBuilder.addParameter(BUCKET_PARAM, bucket.toString());
    uriBuilder.addParameter(KEY_PARAM, key.toString());

    HttpResponse res = client.execute(new HttpGet(uriBuilder.build()));
    try {
        switch (res.getStatusLine().getStatusCode()) {
        case HttpServletResponse.SC_NOT_FOUND:
            return null;
        case HttpServletResponse.SC_OK:
            return Util.JSON_READER.readTree(res.getEntity().getContent());
        default:
            throw new Exception(res.getStatusLine().toString());
        }
    } finally {
        EntityUtils.consume(res.getEntity());
    }
}

From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java

/**
 * Process the Adobe I/O action//from   w w  w. j ava  2  s.  c om
 * 
 * @param actionUrl
 *            The url to be executed
 * @param queryParameters
 *            The query parameters to pass
 * @param method
 *            The method to be executed
 * @param payload
 *            The payload of the call
 * @return JsonObject containing the result of the action
 * @throws Exception
 *             Thrown when process-action throws an exception
 */
private JsonObject process(@NotNull final String actionUrl, @NotNull final Map<String, String> queryParameters,
        @NotNull final String method, final String[] headers, @NotNull final JsonObject payload) {
    if (isBlank(actionUrl) || isBlank(method)) {
        LOGGER.error("Method or url is null");
        return new JsonObject();
    }

    URI uri = null;

    try {
        URIBuilder builder = new URIBuilder(actionUrl);
        queryParameters.forEach((k, v) -> builder.addParameter(k, v));
        uri = builder.build();

    } catch (URISyntaxException uriexception) {
        LOGGER.error(uriexception.getMessage());
        return new JsonObject();
    }

    LOGGER.debug("Performing method = {}. queryParameters = {}. actionUrl = {}. payload = {}", method,
            queryParameters, uri, payload);

    try {
        if (StringUtils.equalsIgnoreCase(method, METHOD_POST)) {
            return processPost(uri, payload, headers);
        } else if (StringUtils.equalsIgnoreCase(method, METHOD_GET)) {
            return processGet(uri, headers);
        } else if (StringUtils.equalsIgnoreCase(method, "PATCH")) {
            return processPatch(uri, payload, headers);
        } else {
            return new JsonObject();
        }
    } catch (IOException ioexception) {
        LOGGER.error(ioexception.getMessage());
        return new JsonObject();

    }

}

From source file:com.ginger.Ginger4J.java

/**
 * Parse the given text and return the JSON object that contains the
 * result & the suggested corrections.
 *
 * @param text//from   www  .j  a  v  a 2s  .  co  m
 *            The text that should be corrected.
 *
 * @return JSONObject
 */
public JSONObject parse(String text) {
    String json = "";
    URIBuilder builder = null;

    try {
        // Build the Web Service URL
        builder = new URIBuilder(this.getBaseURL());
        builder.addParameters(parameters);
        builder.addParameter("text", text);

        // Create the HTTP client
        HttpClient client = HttpClientBuilder.create().build();
        // Create GET request
        HttpGet request = new HttpGet(builder.build());

        // Add request header
        request.addHeader("User-Agent", USER_AGENT);

        // Send request
        HttpResponse response = client.execute(request);

        // Get json response
        json = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

        // Process the suggested corrections
        this.correction = this.processSuggestions(text, new JSONObject(json));
    } catch (URISyntaxException | IOException e) {
        System.out.println("Error: " + e.getMessage());
    } catch (JSONException e) {
        System.out.println("Error while parsing the json response: " + e.getMessage());
    }

    return this.correction;
}

From source file:org.mitre.openid.connect.filter.AuthorizationRequestFilter.java

/**
 * /* w w w.j a va2s . co  m*/
 */
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession session = request.getSession();

    // skip everything that's not an authorize URL
    if (!requestMatcher.matches(request)) {
        chain.doFilter(req, res);
        return;
    }

    try {
        // we have to create our own auth request in order to get at all the parmeters appropriately
        AuthorizationRequest authRequest = null;

        ClientDetailsEntity client = null;

        authRequest = authRequestFactory
                .createAuthorizationRequest(createRequestMap(request.getParameterMap()));
        if (!Strings.isNullOrEmpty(authRequest.getClientId())) {
            client = clientService.loadClientByClientId(authRequest.getClientId());
        }

        // save the login hint to the session
        // but first check to see if the login hint makes any sense
        String loginHint = loginHintExtracter.extractHint((String) authRequest.getExtensions().get(LOGIN_HINT));
        if (!Strings.isNullOrEmpty(loginHint)) {
            session.setAttribute(LOGIN_HINT, loginHint);
        } else {
            session.removeAttribute(LOGIN_HINT);
        }

        if (authRequest.getExtensions().get(PROMPT) != null) {
            // we have a "prompt" parameter
            String prompt = (String) authRequest.getExtensions().get(PROMPT);
            List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt));

            if (prompts.contains(PROMPT_NONE)) {
                // see if the user's logged in
                Authentication auth = SecurityContextHolder.getContext().getAuthentication();

                if (auth != null) {
                    // user's been logged in already (by session management)
                    // we're OK, continue without prompting
                    chain.doFilter(req, res);
                } else {
                    logger.info("Client requested no prompt");
                    // user hasn't been logged in, we need to "return an error"
                    if (client != null && authRequest.getRedirectUri() != null) {

                        // if we've got a redirect URI then we'll send it

                        String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client);

                        try {
                            URIBuilder uriBuilder = new URIBuilder(url);

                            uriBuilder.addParameter(ERROR, LOGIN_REQUIRED);
                            if (!Strings.isNullOrEmpty(authRequest.getState())) {
                                uriBuilder.addParameter(STATE, authRequest.getState()); // copy the state parameter if one was given
                            }

                            response.sendRedirect(uriBuilder.toString());
                            return;

                        } catch (URISyntaxException e) {
                            logger.error("Can't build redirect URI for prompt=none, sending error instead", e);
                            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                            return;
                        }
                    }

                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                    return;
                }
            } else if (prompts.contains(PROMPT_LOGIN)) {

                // first see if the user's already been prompted in this session
                if (session.getAttribute(PROMPTED) == null) {
                    // user hasn't been PROMPTED yet, we need to check

                    session.setAttribute(PROMPT_REQUESTED, Boolean.TRUE);

                    // see if the user's logged in
                    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                    if (auth != null) {
                        // user's been logged in already (by session management)
                        // log them out and continue
                        SecurityContextHolder.getContext().setAuthentication(null);
                        chain.doFilter(req, res);
                    } else {
                        // user hasn't been logged in yet, we can keep going since we'll get there
                        chain.doFilter(req, res);
                    }
                } else {
                    // user has been PROMPTED, we're fine

                    // but first, undo the prompt tag
                    session.removeAttribute(PROMPTED);
                    chain.doFilter(req, res);
                }
            } else {
                // prompt parameter is a value we don't care about, not our business
                chain.doFilter(req, res);
            }

        } else if (authRequest.getExtensions().get(MAX_AGE) != null
                || (client != null && client.getDefaultMaxAge() != null)) {

            // default to the client's stored value, check the string parameter
            Integer max = (client != null ? client.getDefaultMaxAge() : null);
            String maxAge = (String) authRequest.getExtensions().get(MAX_AGE);
            if (maxAge != null) {
                max = Integer.parseInt(maxAge);
            }

            if (max != null) {

                Date authTime = (Date) session.getAttribute(AuthenticationTimeStamper.AUTH_TIMESTAMP);

                Date now = new Date();
                if (authTime != null) {
                    long seconds = (now.getTime() - authTime.getTime()) / 1000;
                    if (seconds > max) {
                        // session is too old, log the user out and continue
                        SecurityContextHolder.getContext().setAuthentication(null);
                    }
                }
            }
            chain.doFilter(req, res);
        } else {
            // no prompt parameter, not our business
            chain.doFilter(req, res);
        }

    } catch (InvalidClientException e) {
        // we couldn't find the client, move on and let the rest of the system catch the error
        chain.doFilter(req, res);
    }
}

From source file:com.palominolabs.crm.sf.rest.HttpApiClient.java

@Nonnull
private URI getUriForPath(String path, List<NameValuePair> params) throws IOException {

    URIBuilder b = getUriBuilderForPath(path);

    for (NameValuePair param : params) {
        b.addParameter(param.getName(), param.getValue());
    }//from   w  ww.  j a v a2s  .  c o  m

    try {
        return b.build();
    } catch (URISyntaxException e) {
        throw new IOException("Couldn't create URI", e);
    }
}

From source file:uk.co.matbooth.calameo.impl.CalameoClientImpl.java

/**
 * Internal method that actually does the work of making the request to Calamo and
 * parsing the response./*from  w w  w . j  a  v  a2 s  .com*/
 * 
 * @param responseType
 *          the class of type T that the response is expected to be
 * @param params
 *          a map of key/value pairs to be sent to Calamo as query parameters
 * @return the response object of type T, whose class was specified in the responseType
 *         argument
 * @throws CalameoException
 *           if there was an error communicating with Calamo
 */
private <T extends Response<?>> T executeRequest(final Class<T> responseType, final Map<String, String> params)
        throws CalameoException {
    HttpClient client = null;
    HttpGet get = null;
    InputStreamReader entity = null;
    try {
        // Generate signed params
        Map<String, String> p = new HashMap<String, String>(params);
        p.put("apikey", getConfig().getKey());
        p.put("expires", Long.toString(new Date().getTime() + getConfig().getExpires()));
        p.put("output", "JSON");
        p.put("subscription_id", getConfig().getSubscription());
        Set<String> keys = new TreeSet<String>(p.keySet());
        StringBuilder input = new StringBuilder(getConfig().getSecret());
        for (String key : keys) {
            input.append(key);
            input.append(p.get(key));
        }
        p.put("signature", DigestUtils.md5Hex(input.toString()));
        // Configure HTTP client
        client = new DefaultHttpClient();
        // Configure GET request
        URIBuilder uri = new URIBuilder(getConfig().getEndpoint());
        for (String key : p.keySet()) {
            uri.addParameter(key, p.get(key));
        }
        get = new HttpGet(uri.build());
        log.debug("Request URI: " + get.getURI());
        // Execute request and parse response
        HttpResponse response = client.execute(get);
        entity = new InputStreamReader(response.getEntity().getContent());
        JsonElement parsed = new JsonParser().parse(entity);
        JsonElement responseJson = parsed.getAsJsonObject().get("response");
        T r = new Gson().fromJson(responseJson, responseType);
        log.debug("Response Object: " + r);
        // Return response or throw an error
        if ("error".equals(r.getStatus())) {
            CalameoException e = new CalameoException(r.getError().getCode(), r.getError().getMessage());
            log.error(e.getMessage());
            throw e;
        } else {
            return r;
        }
    } catch (IOException e) {
        log.error(e.getMessage());
        throw new CalameoException(e);
    } catch (URISyntaxException e) {
        log.error(e.getMessage());
        throw new CalameoException(e);
    } catch (JsonParseException e) {
        log.error(e.getMessage());
        throw new CalameoException(e);
    } finally {
        if (entity != null) {
            try {
                entity.close();
            } catch (IOException e) {
                log.warn(e.getMessage());
            }
        }
        if (get != null) {
            get.releaseConnection();
        }
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    }
}

From source file:net.javacrumbs.restfire.httpcomponents.HttpComponentsRequestBuilder.java

private void copyParamsIfNeeded(URIBuilder newUriBuilder) {
    if (newUriBuilder.getQueryParams().isEmpty() && !uriBuilder.getQueryParams().isEmpty()) {
        //there were parameters set which would be overwritten
        for (NameValuePair param : uriBuilder.getQueryParams()) {
            newUriBuilder.addParameter(param.getName(), param.getValue());
        }/*from  www. java2s . c  o  m*/
    }
}