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:org.apache.marmotta.ldclient.provider.youtube.YoutubeVideoPagesProvider.java

@Override
public ClientResponse retrieveResource(String resource, LDClientService client, Endpoint endpoint)
        throws DataRetrievalException {

    Model model = new TreeModel();

    String uri = resource;//from ww w . j  av  a 2s. com
    URI objUri;
    try {
        objUri = new URI(uri);
    } catch (URISyntaxException e) {
        throw new RuntimeException("URI '" + uri + "'could not be parsed, it is not a valid URI");
    }

    String video_id = null;
    if (uri.startsWith(YOUTUBE_V)) { // YouTube short watch video URL
        String[] p_components = objUri.getPath().split("/");
        video_id = p_components[p_components.length - 1];
    } else if (resource.startsWith(YOUTUBE_WATCH)) { // YouTube watch video URL
        List<NameValuePair> params = URLEncodedUtils.parse(objUri, "UTF-8");
        for (NameValuePair pair : params) {
            if ("v".equals(pair.getName())) {
                video_id = pair.getValue();
                break;
            }
        }
    } else if (uri.startsWith(YOUTUBE_GDATA)) { // GData URI
        video_id = StringUtils.removeStart(uri, YOUTUBE_GDATA);
    }
    if (StringUtils.isBlank(video_id)) {
        String msg = "Not valid video id found in '" + uri + "'";
        log.error(msg);
        throw new DataRetrievalException(msg);
    } else {
        model.add(new URIImpl(uri), new URIImpl(FOAF_PRIMARY_TOPIC),
                new URIImpl(YoutubeVideoProvider.YOUTUBE_BASE_URI + video_id), (Resource) null);
        // FIXME: add inverse triple, but maybe at the YoutubeVideoProvider

        ClientResponse clientResponse = new ClientResponse(200, model);
        clientResponse.setExpires(DateUtils.addYears(new Date(), 10));
        return clientResponse;
    }

}

From source file:org.codice.alliance.imaging.chip.actionprovider.ImagingChipActionProvider.java

private static Optional<URI> getOriginalDerivedResourceUri(final Metacard metacard) {
    final Attribute derivedResourceUriAttribute = metacard.getAttribute(Metacard.DERIVED_RESOURCE_URI);
    if (derivedResourceUriAttribute == null) {
        return Optional.empty();
    }/*  w  w  w. j  a v  a  2  s.co m*/
    List<String> derivedResourceUriStrings = derivedResourceUriAttribute.getValues().stream()
            .filter(String.class::isInstance).map(String.class::cast).collect(Collectors.toList());

    for (String resourceUri : derivedResourceUriStrings) {
        try {
            final URI derivedResourceUri = new URI(resourceUri);

            if (canBeChippedLocally(derivedResourceUri)
                    && StringUtils.equals(ORIGINAL_QUALIFIER, derivedResourceUri.getFragment())) {
                return Optional.of(derivedResourceUri);
            }
            for (NameValuePair parameter : URLEncodedUtils.parse(derivedResourceUri,
                    StandardCharsets.UTF_8.name())) {
                if (QUALIFIER_KEY.equals(parameter.getName())
                        && StringUtils.equals(ORIGINAL_QUALIFIER, parameter.getValue())) {
                    return Optional.of(derivedResourceUri);
                }
            }
        } catch (URISyntaxException e) {
            // This is not an unexpected exception, there is not enough info to construct a chipping URL
        }
    }
    return Optional.empty();
}

From source file:org.esigate.util.UriUtils.java

/**
 * Returns a list of {@link NameValuePair NameValuePairs} as built from the URI's query portion. For example, a URI
 * of http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three NameValuePairs, one for a=1, one for
 * b=2, and one for c=3. By convention, {@code '&'} and {@code ';'} are accepted as parameter separators.
 * <p>/* w w  w .  j  av  a  2  s . c  o  m*/
 * This is typically useful while parsing an HTTP PUT.
 * 
 * This API is currently only used for testing.
 * 
 * @param uri
 *            URI to parse
 * @param charset
 *            Charset name to use while parsing the query
 * @return a list of {@link NameValuePair} as built from the URI's query portion.
 */
public static List<NameValuePair> parse(final String uri, final String charset) {
    return URLEncodedUtils.parse(createURI(uri), charset);
}

From source file:org.flowable.ui.modeler.rest.app.FormsResource.java

@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public ResultListDataRepresentation getForms(HttpServletRequest request) {

    // need to parse the filterText parameter ourselves, due to encoding issues with the default parsing.
    String filter = null;/*from w  w w .  java 2  s .  co m*/
    List<NameValuePair> params = URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8"));
    if (params != null) {
        for (NameValuePair nameValuePair : params) {
            if ("filter".equalsIgnoreCase(nameValuePair.getName())) {
                filter = nameValuePair.getValue();
            }
        }
    }
    String validFilter = makeValidFilterText(filter);

    List<Model> models = null;
    if (validFilter != null) {
        models = modelRepository.findByModelTypeAndFilter(AbstractModel.MODEL_TYPE_FORM, validFilter,
                ModelSort.NAME_ASC);

    } else {
        models = modelRepository.findByModelType(AbstractModel.MODEL_TYPE_FORM, ModelSort.NAME_ASC);
    }

    List<FormRepresentation> reps = new ArrayList<>();

    for (Model model : models) {
        reps.add(new FormRepresentation(model));
    }

    Collections.sort(reps, new NameComparator());

    ResultListDataRepresentation result = new ResultListDataRepresentation(reps);
    result.setTotal(Long.valueOf(models.size()));
    return result;
}

From source file:org.keycloak.testsuite.adapter.servlet.DemoServletsAdapterTest.java

private static Map<String, String> getQueryFromUrl(String url) {
    try {// ww w. j a  v a  2 s . co  m
        return URLEncodedUtils.parse(new URI(url), "UTF-8").stream()
                .collect(Collectors.toMap(p -> p.getName(), p -> p.getValue()));
    } catch (URISyntaxException e) {
        return null;
    }
}

From source file:org.keycloak.testsuite.util.OAuthClient.java

public Map<String, String> getCurrentQuery() {
    Map<String, String> m = new HashMap<>();
    List<NameValuePair> pairs = URLEncodedUtils.parse(getCurrentUri(), "UTF-8");
    for (NameValuePair p : pairs) {
        m.put(p.getName(), p.getValue());
    }/*from  w w  w. jav  a  2s .com*/
    return m;
}

From source file:org.keycloak.testsuite.util.saml.ModifySamlResponseStepBuilder.java

protected HttpUriRequest handleRedirectBinding(CloseableHttpResponse currentResponse)
        throws Exception, IOException, URISyntaxException {
    NameValuePair samlParam = null;

    assertThat(currentResponse, statusCodeIsHC(Status.FOUND));
    String location = currentResponse.getFirstHeader("Location").getValue();
    URI locationUri = URI.create(location);

    List<NameValuePair> params = URLEncodedUtils.parse(locationUri, "UTF-8");
    for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) {
        NameValuePair param = it.next();
        if ("SAMLResponse".equals(param.getName()) || "SAMLRequest".equals(param.getName())) {
            assertThat("Only one SAMLRequest/SAMLResponse check", samlParam, nullValue());
            samlParam = param;/*from   w w w .jav  a2  s .  c  om*/
            it.remove();
        }
    }

    assertThat(samlParam, notNullValue());

    String base64EncodedSamlDoc = samlParam.getValue();
    InputStream decoded = RedirectBindingUtil.base64DeflateDecode(base64EncodedSamlDoc);
    String samlDoc = IOUtils.toString(decoded, GeneralConstants.SAML_CHARSET);
    IOUtils.closeQuietly(decoded);

    String transformed = getTransformer().transform(samlDoc);
    if (transformed == null) {
        return null;
    }

    final String attrName = this.targetAttribute != null ? this.targetAttribute : samlParam.getName();

    return createRequest(locationUri, attrName, transformed, params);
}

From source file:org.opennms.netmgt.collectd.HttpCollector.java

private static HttpGet buildGetMethod(final URI uri, final HttpCollectionSet collectionSet) {
    URI uriWithQueryString = null;
    List<NameValuePair> queryParams = buildRequestParameters(collectionSet);
    try {// w ww .j ava 2  s. c om
        StringBuffer query = new StringBuffer();
        query.append(URLEncodedUtils.format(queryParams, "UTF-8"));
        if (uri.getQuery() != null && !uri.getQuery().trim().isEmpty()) {
            if (query.length() > 0) {
                query.append("&");
            }
            query.append(uri.getQuery());
        }
        final URIBuilder ub = new URIBuilder(uri);
        if (query.length() > 0) {
            final List<NameValuePair> params = URLEncodedUtils.parse(query.toString(),
                    Charset.forName("UTF-8"));
            if (!params.isEmpty()) {
                ub.setParameters(params);
            }
        }
        uriWithQueryString = ub.build();
        return new HttpGet(uriWithQueryString);
    } catch (URISyntaxException e) {
        LOG.warn(e.getMessage(), e);
        return new HttpGet(uri);
    }
}

From source file:org.opennms.netmgt.collectd.HttpCollector.java

private static URI buildUri(final HttpCollectionSet collectionSet) throws URISyntaxException {
    HashMap<String, String> substitutions = new HashMap<String, String>();
    substitutions.put("ipaddr", InetAddressUtils.str(collectionSet.getAgent().getAddress()));
    substitutions.put("nodeid", Integer.toString(collectionSet.getAgent().getNodeId()));

    final URIBuilder ub = new URIBuilder();
    ub.setScheme(collectionSet.getUriDef().getUrl().getScheme());
    ub.setHost(substituteKeywords(substitutions, collectionSet.getUriDef().getUrl().getHost(), "getHost"));
    ub.setPort(collectionSet.getPort());
    ub.setPath(substituteKeywords(substitutions, collectionSet.getUriDef().getUrl().getPath(), "getURL"));

    final String query = substituteKeywords(substitutions, collectionSet.getUriDef().getUrl().getQuery(),
            "getQuery");
    final List<NameValuePair> params = URLEncodedUtils.parse(query, Charset.forName("UTF-8"));
    ub.setParameters(params);/*from  w  w w  .j a va  2  s .co m*/

    ub.setFragment(
            substituteKeywords(substitutions, collectionSet.getUriDef().getUrl().getFragment(), "getFragment"));
    return ub.build();
}

From source file:org.opennms.netmgt.poller.monitors.WebMonitor.java

/** {@inheritDoc} */
@Override//from  w w  w.j  a va 2 s  .  c om
public PollStatus poll(MonitoredService svc, Map<String, Object> map) {
    PollStatus pollStatus = PollStatus.unresponsive();
    HttpClientWrapper clientWrapper = HttpClientWrapper.create();

    try {
        final String hostAddress = InetAddressUtils.str(svc.getAddress());

        URIBuilder ub = new URIBuilder();
        ub.setScheme(ParameterMap.getKeyedString(map, "scheme", DEFAULT_SCHEME));
        ub.setHost(hostAddress);
        ub.setPort(ParameterMap.getKeyedInteger(map, "port", DEFAULT_PORT));
        ub.setPath(ParameterMap.getKeyedString(map, "path", DEFAULT_PATH));

        String queryString = ParameterMap.getKeyedString(map, "queryString", null);
        if (queryString != null && !queryString.trim().isEmpty()) {
            final List<NameValuePair> params = URLEncodedUtils.parse(queryString, Charset.forName("UTF-8"));
            if (!params.isEmpty()) {
                ub.setParameters(params);
            }
        }

        final HttpGet getMethod = new HttpGet(ub.build());
        clientWrapper.setConnectionTimeout(ParameterMap.getKeyedInteger(map, "timeout", DEFAULT_TIMEOUT))
                .setSocketTimeout(ParameterMap.getKeyedInteger(map, "timeout", DEFAULT_TIMEOUT));

        final String userAgent = ParameterMap.getKeyedString(map, "user-agent", DEFAULT_USER_AGENT);
        if (userAgent != null && !userAgent.trim().isEmpty()) {
            clientWrapper.setUserAgent(userAgent);
        }

        final String virtualHost = ParameterMap.getKeyedString(map, "virtual-host", hostAddress);
        if (virtualHost != null && !virtualHost.trim().isEmpty()) {
            clientWrapper.setVirtualHost(virtualHost);
        }

        if (ParameterMap.getKeyedBoolean(map, "http-1.0", false)) {
            clientWrapper.setVersion(HttpVersion.HTTP_1_0);
        }

        for (final Object okey : map.keySet()) {
            final String key = okey.toString();
            if (key.matches("header_[0-9]+$")) {
                final String headerName = ParameterMap.getKeyedString(map, key, null);
                final String headerValue = ParameterMap.getKeyedString(map, key + "_value", null);
                getMethod.setHeader(headerName, headerValue);
            }
        }

        if (ParameterMap.getKeyedBoolean(map, "use-ssl-filter", false)) {
            clientWrapper.trustSelfSigned(ParameterMap.getKeyedString(map, "scheme", DEFAULT_SCHEME));
        }

        if (ParameterMap.getKeyedBoolean(map, "auth-enabled", false)) {
            clientWrapper.addBasicCredentials(ParameterMap.getKeyedString(map, "auth-user", DEFAULT_USER),
                    ParameterMap.getKeyedString(map, "auth-password", DEFAULT_PASSWORD));
            if (ParameterMap.getKeyedBoolean(map, "auth-preemptive", true)) {
                clientWrapper.usePreemptiveAuth();
            }
        }

        LOG.debug("getMethod parameters: {}", getMethod);
        CloseableHttpResponse response = clientWrapper.execute(getMethod);
        int statusCode = response.getStatusLine().getStatusCode();
        String statusText = response.getStatusLine().getReasonPhrase();
        String expectedText = ParameterMap.getKeyedString(map, "response-text", null);

        LOG.debug("returned results are:");

        if (!inRange(ParameterMap.getKeyedString(map, "response-range", DEFAULT_HTTP_STATUS_RANGE),
                statusCode)) {
            pollStatus = PollStatus.unavailable(statusText);
        } else {
            pollStatus = PollStatus.available();
        }

        if (expectedText != null) {
            String responseText = EntityUtils.toString(response.getEntity());
            if (expectedText.charAt(0) == '~') {
                if (!responseText.matches(expectedText.substring(1))) {
                    pollStatus = PollStatus.unavailable("Regex Failed");
                } else
                    pollStatus = PollStatus.available();
            } else {
                if (expectedText.equals(responseText))
                    pollStatus = PollStatus.available();
                else
                    pollStatus = PollStatus.unavailable("Did not find expected Text");
            }
        }

    } catch (IOException e) {
        LOG.info(e.getMessage());
        pollStatus = PollStatus.unavailable(e.getMessage());
    } catch (URISyntaxException e) {
        LOG.info(e.getMessage());
        pollStatus = PollStatus.unavailable(e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error("Unable to set SSL trust to allow self-signed certificates", e);
        pollStatus = PollStatus.unavailable("Unable to set SSL trust to allow self-signed certificates");
    } catch (Throwable e) {
        LOG.error("Unexpected exception while running " + getClass().getName(), e);
        pollStatus = PollStatus.unavailable("Unexpected exception: " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }
    return pollStatus;
}