Example usage for org.apache.http.client.utils URLEncodedUtils parse

List of usage examples for org.apache.http.client.utils URLEncodedUtils parse

Introduction

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

Prototype

public static List<NameValuePair> parse(final String s, final Charset charset) 

Source Link

Document

Returns a list of NameValuePair NameValuePairs as parsed from the given string using the given character encoding.

Usage

From source file:com.fonoster.astive.agi.AgiRequest.java

/**
 * Create a new AgiRequest object with the info sent by a new
 * <code>channel</code>./*from  w w w. j a  va2s. c o m*/
 *
 * @param lines array of a pairs key/value elements with information about
 * the <code>channel</code>.
 */
public AgiRequest(final ArrayList<String> lines) {
    this.lines = lines;

    fieldsMap = new HashMap<String, String>();

    List<String> args = new ArrayList<String>();

    for (String line : lines) {

        String key = line.split(":")[0].trim();

        if (line.split(":").length < 2) {
            fieldsMap.put(line.split(":")[0].trim(), null);
            continue;
        }

        String value = line.split(":")[1].trim();

        if (key.equals("agi_request") && (line.split(":").length == 3)) {
            value = value + ":" + line.split(":")[2].trim();
        }

        if (key.matches("agi_arg_(.*)")) {
            args.add(value);
        }

        fieldsMap.put(key, value);
    }

    arguments = args.toArray(new String[args.size()]);

    try {
        fillFields();
    } catch (IllegalArgumentException ex) {
        LOG.warn(ex.getMessage());
    } catch (IllegalAccessException ex) {
        LOG.warn(ex.getMessage());
    }

    queryParameters = new HashMap<String, String>();

    List<NameValuePair> params = null;
    try {
        params = URLEncodedUtils.parse(new URI(script), "UTF-8");
        for (NameValuePair param : params) {
            queryParameters.put(param.getName(), param.getValue());
        }
    } catch (URISyntaxException ex) {
        LOG.warn(ex.getMessage());
    }

}

From source file:com.vmware.bdd.cli.auth.LoginClientImplTest.java

public LoginTestTemplate(final String expectedUserName, final String expectedPassword, final int responseCode,
        final String sessionId) {

    httpHandler = new HttpHandler() {
        @Override/* w ww  .  j  a v a  2s .  c o  m*/
        public void handle(HttpExchange httpExchange) throws IOException {
            Headers headers = httpExchange.getRequestHeaders();

            Assert.assertEquals("application/x-www-form-urlencoded; charset=UTF-8",
                    headers.getFirst("Content-Type"));
            Assert.assertEquals("POST", httpExchange.getRequestMethod());

            InputStream reqStream = httpExchange.getRequestBody();

            Reader reader = new InputStreamReader(reqStream);

            StringBuilder sb = new StringBuilder();

            char[] tmp = new char[16];
            int count = reader.read(tmp);
            while (count > 0) {
                sb.append(tmp, 0, count);
                count = reader.read(tmp);
            }

            //            String val = URLDecoder.decode(sb.toString(), "UTF-8");

            List<NameValuePair> namePasswordPairs = URLEncodedUtils.parse(sb.toString(),
                    Charset.forName("UTF-8"));
            Assert.assertEquals(namePasswordPairs.get(0).getValue(), expectedUserName);
            Assert.assertEquals(namePasswordPairs.get(1).getValue(), expectedPassword);

            if (sessionId != null) {
                Headers responseHeaders = httpExchange.getResponseHeaders();
                responseHeaders.set(LoginClientImpl.SET_COOKIE_HEADER,
                        "JSESSIONID=" + sessionId + "; Path=/serengeti; Secure");
            }

            String response = "LoginClientImplTest";
            httpExchange.sendResponseHeaders(responseCode, response.length());

            BufferedOutputStream os = new BufferedOutputStream(httpExchange.getResponseBody());

            os.write(response.getBytes());
            os.close();

        }
    };
}

From source file:datacite.oai.provider.service.MDSSearchServiceSolrImpl.java

static SolrQuery constructSolrQuery(Date updateDateFrom, Date updateDateTo, String setspec, int offset,
        int length) throws ServiceException {
    SolrQuery query = new SolrQuery();
    query.setQuery("*:*");
    query.setRows(length);// w w w.  ja v  a  2  s  .c o  m
    query.setStart(offset);
    query.setSortField("updated", ORDER.asc);

    setspec = StringUtils.trimToEmpty(setspec);
    if (setspec.contains(Constants.Set.BASE64_PART_DELIMITER)) {
        String split[] = setspec.split(Constants.Set.BASE64_PART_DELIMITER, 2);
        setspec = split[0];
        String base64 = split[1];
        String solrfilter = new String(Base64.decodeBase64(base64));
        logger.info("decoded base64 setspec: " + solrfilter);
        solrfilter = solrfilter.replaceAll("^[?&]+", "");

        List<NameValuePair> params = URLEncodedUtils.parse(solrfilter, Charset.defaultCharset());
        for (NameValuePair param : params) {
            String name = param.getName();
            String value = param.getValue();
            if (name.equals("q"))
                query.setQuery(value);
            else if (name.equals("fq"))
                query.addFilterQuery(value);
            else
                throw new ServiceException("parameter '" + name + "' is not supported");
        }
    }

    if (setspec != null && setspec.trim().length() > 0) {
        setspec = setspec.trim().toUpperCase();

        if (setspec.equalsIgnoreCase(Constants.Set.REF_QUALITY)) {
            query.addFilterQuery("refQuality:true");
        } else {
            if (setspec.endsWith(Constants.Set.REF_QUALITY_SUFFIX)) {
                query.addFilterQuery("refQuality:true");
                setspec = setspec.substring(0, setspec.lastIndexOf(Constants.Set.REF_QUALITY_SUFFIX));
            }
            String field = setspec.contains(".") ? "datacentre_symbol" : "allocator_symbol";
            query.addFilterQuery(field + ":" + setspec);
        }
    }

    String from = dateFormat.format(updateDateFrom);
    String to = dateFormat.format(updateDateTo);

    query.addFilterQuery("updated:[" + from + " TO " + to + "]");

    query.setParam(CommonParams.QT, "/public/api");

    return query;
}

From source file:com.devicehive.model.oauth.FacebookAuthProvider.java

private String getAccessToken(final String code, final String redirectUrl) {
    if (StringUtils.isBlank(code) || StringUtils.isBlank(redirectUrl)) {
        logger.error(Messages.INVALID_AUTH_REQUEST_PARAMETERS);
        throw new HiveException(Messages.INVALID_AUTH_REQUEST_PARAMETERS,
                Response.Status.BAD_REQUEST.getStatusCode());
    }/*from  w w w .  j a va 2 s .  co  m*/
    final String endpoint = identityProvider.getTokenEndpoint();
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("code", code));
    params.add(new BasicNameValuePair("client_id",
            configurationService.get(Constants.FACEBOOK_IDENTITY_CLIENT_ID)));
    params.add(new BasicNameValuePair("client_secret",
            configurationService.get(Constants.FACEBOOK_IDENTITY_CLIENT_SECRET)));
    params.add(new BasicNameValuePair("redirect_uri", redirectUrl));
    final String response = identityProviderUtils.executeGet(new NetHttpTransport(), params, endpoint,
            FACEBOOK_PROVIDER_NAME);
    List<NameValuePair> responseParams = URLEncodedUtils.parse(response, Charset.forName(UTF8));
    if (!"access_token".equals(responseParams.get(0).getName())) {
        logger.error("Exception has been caught during Identity Provider GET request execution", response);
        throw new HiveException(
                String.format(Messages.GETTING_OAUTH_ACCESS_TOKEN_FAILED, FACEBOOK_PROVIDER_NAME, response),
                Response.Status.UNAUTHORIZED.getStatusCode());
    }
    return responseParams.get(0).getValue();
}

From source file:com.hp.autonomy.hod.client.api.authentication.AuthenticationServiceImplTest.java

@Test
public void generatesCombinedSignedRequest() throws URISyntaxException {
    final SignedRequest request = service.combinedRequest(ALLOWED_ORIGINS, TOKEN, DOMAIN, APPLICATION,
            USER_STORE_DOMAIN, USER_STORE_NAME, TokenType.Simple.INSTANCE);

    assertThat(request.getVerb(), is(Request.Verb.POST));

    final List<NameValuePair> expectedParameters = Arrays.<NameValuePair>asList(
            new BasicNameValuePair("allowed_origins", ALLOWED_ORIGINS.get(0)),
            new BasicNameValuePair("allowed_origins", ALLOWED_ORIGINS.get(1)));

    checkCombinedUrl(request, expectedParameters);

    final List<NameValuePair> pairs = URLEncodedUtils.parse(request.getBody(), StandardCharsets.UTF_8);
    checkParameterPair(pairs, "domain", DOMAIN);
    checkParameterPair(pairs, "application", APPLICATION);
    checkParameterPair(pairs, "userstore_domain", USER_STORE_DOMAIN);
    checkParameterPair(pairs, "userstore_name", USER_STORE_NAME);
    checkParameterPair(pairs, "token_type", TokenType.Simple.INSTANCE.getParameter());

    assertThat(request.getToken(),/* w ww.j  a v a2  s .  c om*/
            is("UNB:HMAC_SHA1:my-token-id:wJkMexQxgEhW13IAeN6i6A:R9XBlyBildIbslAWyxDwQ5O-8WQ"));
}

From source file:com.nestapi.lib.UserAuthActivity.java

private String parseCodeQuery(String urlStr) {
    try {//from  w  w w  .j  a v  a2  s  .  c o  m
        List<NameValuePair> params = URLEncodedUtils.parse(new URI(urlStr), "UTF-8");
        for (NameValuePair pair : params) {
            log("Parsed parameters: " + pair.getName() + " value: " + pair.getValue());
            if (pair.getName().equals("code")) {
                return pair.getValue();
            }
        }
        return null;
    } catch (URISyntaxException excep) {
        return null;
    }
}

From source file:org.apache.servicecomb.foundation.vertx.http.StandardHttpServletRequestEx.java

private Map<String, List<String>> parseUrlEncodedBody() {
    try (InputStream inputStream = getInputStream()) {
        Map<String, List<String>> listMap = new HashMap<>();
        String body = IOUtils.toString(inputStream);
        List<NameValuePair> pairs = URLEncodedUtils.parse(body,
                getCharacterEncoding() == null ? null : Charset.forName(getCharacterEncoding()));
        for (NameValuePair pair : pairs) {
            List<String> values = listMap.computeIfAbsent(pair.getName(), k -> new ArrayList<>());
            values.add(pair.getValue());
        }//from  w  w  w.ja  va  2s.  c o m
        return listMap;
    } catch (IOException e) {
        throw new IllegalStateException("", e);
    }
}

From source file:com.github.parisoft.resty.request.Request.java

/**
 * Creates a request from a {@link URI}.<br>
 * The URI must conform the <a href=https://www.ietf.org/rfc/rfc2396.txt>RFC 2396</a> with the <i>path</i> and <i>query</i> properly encoded.<br>
 * <br>/*from w  w w . j av a 2s  .  c  om*/
 * For your convenience, call this constructor with the base address of your request - like {@literal <scheme>://<authority>} -
 * and use {@link #path(String...)} and {@link #query(String, String)} to configure the URI path and query respectively without worring about escape.<br>
 * <br>
 * As example, you can do<br>
 * <pre>
 * URI partialUri = new URI("http://some.domain.org:1234");
 * Request request = new Request(partialUri)
 *                       .path("any unescaped path")
 *                       .query("don't", "scape too");
 * </pre>
 * or
 * <pre>
 * URI fullUri = new URI("http://some.domain.org:1234/any%20unescaped%20path?don%27t=scape+too");
 * Request request = new Request(fullUri);
 * </pre>
 * <i>Note:</i> this is equivalent to {@link RESTy#request(URI)}
 *
 * @param uri A {@link URI} as defined by <a href=https://www.ietf.org/rfc/rfc2396.txt>RFC 2396</a>
 * @throws IllegalArgumentException If the URI is null
 */
public Request(URI uri) {
    if (uri == null) {
        throw new IllegalArgumentException("Cannot create a request: URI cannot be null");
    }

    path(emptyIfNull(uri.getPath()));

    try {
        query(URLEncodedUtils.parse(uri, UTF_8.name()));
        rootUri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null,
                uri.getFragment());
    } catch (Exception e) {
        throw new IllegalArgumentException("Cannot create a request: " + e.getMessage());
    }
}