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:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.XsltWriter.java

/**
 * Parameter identifiers have a leading "-". Parameter values are separated
 * from the parameter identifier via a single space.
 * <ul>//from   w w w . j av  a 2  s.  com
 * <li>Parameter {@value #PARAM_xslTransformerFactory}: fully qualified name
 * of the XSLT processor implementation; NOTE: this parameter may not be
 * provided if the default implementation shall be used.</li>
 * <li>Parameter {@value #PARAM_hrefMappings}: list of key-value pairs
 * defining href mappings, structured using URL query syntax (i.e. using '='
 * to separate the key from the value, using '&' to separate pairs, and with
 * URL-encoded value (with UTF-8 character encoding); NOTE: this parameter
 * may not be provided if href mappings are not needed.</li>
 * <li>Parameter {@value #PARAM_transformationParameters}: list of key-value
 * pairs defining the transformation parameters, structured using URL query
 * syntax (i.e. using '=' to separate the key from the value, using '&' to
 * separate pairs, and with URL-encoded value (with UTF-8 character
 * encoding); NOTE: this parameter may not be provided if transformation
 * parameters are not needed.</li>
 * <li>Parameter {@value #PARAM_transformationSourcePath}: path to the
 * transformation source file (may be a relative path); NOTE: this is a
 * required parameter.</li>
 * <li>Parameter {@value #PARAM_xsltMainFileUri}: String representation of
 * the URI to the main XSLT file; NOTE: this is a required parameter.</li>
 * <li>Parameter {@value #PARAM_transformationTargetPath}: path to the
 * transformation target file (may be a relative path); NOTE: this is a
 * required parameter.</li>
 * </ul>
 */
public static void main(String[] args) {

    String xslTransformerFactory = null;
    String hrefMappingsString = null;
    String transformationParametersString = null;
    String transformationSourcePath = null;
    String xsltMainFileUriString = null;
    String transformationTargetPath = null;

    // identify parameters
    String arg = null;

    for (int i = 0; i < args.length; i++) {

        arg = args[i];

        if (arg.equals(PARAM_xslTransformerFactory)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println("No value provided for invocation parameter " + PARAM_xslTransformerFactory);
                return;
            } else {
                xslTransformerFactory = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_hrefMappings)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println("No value provided for invocation parameter " + PARAM_hrefMappings);
                return;
            } else {
                hrefMappingsString = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_transformationParameters)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println(
                        "No value provided for invocation parameter " + PARAM_transformationParameters);
                return;
            } else {
                transformationParametersString = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_transformationSourcePath)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println(
                        "No value provided for invocation parameter " + PARAM_transformationSourcePath);
                return;
            } else {
                transformationSourcePath = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_transformationTargetPath)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println(
                        "No value provided for invocation parameter " + PARAM_transformationTargetPath);
                return;
            } else {
                transformationTargetPath = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_xsltMainFileUri)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println("No value provided for invocation parameter " + PARAM_xsltMainFileUri);
                return;
            } else {
                xsltMainFileUriString = args[i + 1];
                i++;
            }
        }
    }

    try {

        // parse parameter values
        Map<String, URI> hrefMappings = new HashMap<String, URI>();

        List<NameValuePair> hrefMappingsList = URLEncodedUtils.parse(hrefMappingsString, ENCODING_CHARSET);
        for (NameValuePair nvp : hrefMappingsList) {

            hrefMappings.put(nvp.getName(), new URI(nvp.getValue()));
        }

        Map<String, String> transformationParameters = new HashMap<String, String>();

        List<NameValuePair> transParamList = URLEncodedUtils.parse(transformationParametersString,
                ENCODING_CHARSET);
        for (NameValuePair nvp : transParamList) {
            transformationParameters.put(nvp.getName(), nvp.getValue());
        }

        boolean invalidParameters = false;

        if (transformationSourcePath == null) {
            invalidParameters = true;
            System.err.println("Path to transformation source file was not provided.");
        }
        if (xsltMainFileUriString == null) {
            invalidParameters = true;
            System.err.println("Path to main XSLT file was not provided.");
        }
        if (transformationTargetPath == null) {
            invalidParameters = true;
            System.err.println("Path to transformation target file was not provided.");
        }

        if (!invalidParameters) {

            // set up and execute XSL transformation
            XsltWriter writer = new XsltWriter(xslTransformerFactory, hrefMappings, transformationParameters,
                    null);

            File transformationSource = new File(transformationSourcePath);
            URI xsltMainFileUri = new URI(xsltMainFileUriString);
            File transformationTarget = new File(transformationTargetPath);

            writer.xsltWrite(transformationSource, xsltMainFileUri, transformationTarget);
        }

    } catch (Exception e) {

        String m = e.getMessage();

        if (m != null) {
            System.err.println(m);
        } else {
            System.err.println("Exception occurred while processing the XSL transformation.");
        }
    }
}

From source file:net.desgrange.pwad.service.UrlUtils.java

public static String getParameter(final String url, final String parameterName) throws BadUrlException {
    try {/* w  ww .j a  v  a  2s  .  co m*/
        final List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(new URI(url), "UTF-8");
        for (final NameValuePair pair : nameValuePairs) {
            if (pair.getName().equalsIgnoreCase(parameterName)) {
                return pair.getValue();
            }
        }
        return null;
    } catch (final URISyntaxException e) {
        throw new BadUrlException(e);
    } catch (final IllegalArgumentException e) {
        throw new BadUrlException(e);
    } catch (final NullPointerException e) {
        throw new BadUrlException(e);
    }
}

From source file:org.apache.usergrid.utils.HttpUtils.java

public static Map<String, List<String>> parseQueryString(String queryString) {
    Map<String, List<String>> mapOfLists = new HashMap<String, List<String>>();
    if ((queryString == null) || (queryString.length() == 0)) {
        return mapOfLists;
    }/*from   w w w.j  av a 2  s . c  o m*/
    List<NameValuePair> list = URLEncodedUtils.parse(URI.create("http://localhost/?" + queryString), "UTF-8");
    for (NameValuePair pair : list) {
        List<String> values = mapOfLists.get(pair.getName());
        if (values == null) {
            values = new ArrayList<String>();
            mapOfLists.put(pair.getName(), values);
        }
        if (pair.getValue() != null) {
            values.add(pair.getValue());
        }
    }

    return mapOfLists;
}

From source file:org.epics.archiverappliance.utils.ui.URIUtils.java

/**
 * Parse the query string of a URI (typically used in archiver config strings) and return these as a name value pair hashmap.
 * We do not handle multiple values for the same param in this call; we simply replace previous names.
 * @param uri URI//from w  w w .j a va  2  s  . c o m
 * @return HashMap Parse the query string
 * @throws IOException  &emsp; 
 */
public static HashMap<String, String> parseQueryString(URI uri) throws IOException {
    HashMap<String, String> ret = new HashMap<String, String>();
    if (uri == null)
        return ret;
    List<NameValuePair> nvs = URLEncodedUtils.parse(uri, "UTF-8");
    if (nvs == null)
        return ret;
    for (NameValuePair nv : nvs) {
        ret.put(nv.getName(), nv.getValue());
    }
    return ret;
}

From source file:org.piwik.sdk.QuickTrackTest.java

private static QueryHashMap<String, String> parseEventUrl(String url) throws Exception {
    QueryHashMap<String, String> values = new QueryHashMap<String, String>();

    List<NameValuePair> params = URLEncodedUtils.parse(new URI("http://localhost/" + url), "UTF-8");

    for (NameValuePair param : params) {
        values.put(param.getName(), param.getValue());
    }/*from   w  w w. j a  v  a  2 s  .  c  o  m*/

    return values;
}

From source file:com.bazaarvoice.seo.sdk.util.BVUtilty.java

public static String getPageNumber(String queryString) {
    if (queryString != null && queryString.length() > 0) {
        List<NameValuePair> parameters = URLEncodedUtils.parse(queryString, Charset.forName("UTF-8"));
        for (NameValuePair parameter : parameters) {
            if (parameter.getName().equals("bvrrp") || parameter.getName().equals("bvqap")) {
                final Pattern p = Pattern.compile("^[^/]+/\\w+/\\w+/(\\d+)/[^/]+\\.htm$");
                return matchPageNumber(p, parameter.getValue());
            } else if (parameter.getName().equals("bvsyp")) {
                final Pattern p = Pattern.compile("^[^/]+/\\w+/\\w+/(\\d+)[[/\\w+]|[^/]]+\\.htm$");
                return matchPageNumber(p, parameter.getValue());
            } else if (parameter.getName().equals("bvpage")) {
                final Pattern p = Pattern.compile("^\\w+/(\\d+)$");
                return matchPageNumber(p, parameter.getValue());
            }//w  w w  . ja va  2  s  .co m
        }
    }
    return "1";
}

From source file:com.magnet.plugin.helpers.UrlParser.java

public static ParsedUrl parseUrl(String url) {
    List<PathPart> pathParts = new ArrayList<PathPart>();
    List<Query> queries = new ArrayList<Query>();
    ParsedUrl parsedUrl;//  ww w.j a v a2 s. co m
    String base;

    try {
        URL aURL = new URL(url);
        base = aURL.getAuthority();
        String protocol = aURL.getProtocol();
        parsedUrl = new ParsedUrl();
        parsedUrl.setPathWithEndingSlash(aURL.getPath().endsWith("/"));
        parsedUrl.setBase(protocol + "://" + base);
        List<NameValuePair> pairs = URLEncodedUtils.parse(aURL.getQuery(), Charset.defaultCharset());
        for (NameValuePair pair : pairs) {
            Query query = new Query(pair.getName(), pair.getValue());
            queries.add(query);
        }
        parsedUrl.setQueries(queries);

        String[] pathStrings = aURL.getPath().split("/");
        for (String pathPart : pathStrings) {
            Matcher m = PATH_PARAM_PATTERN.matcher(pathPart);
            if (m.find()) {
                String paramDef = m.group(1);
                String[] paramParts = paramDef.split(":");
                if (paramParts.length > 1) {
                    pathParts.add(new PathPart(paramParts[1].trim(), paramParts[0].trim()));
                } else {
                    pathParts.add(new PathPart(paramParts[0].trim()));
                }
            } else {
                if (!pathPart.isEmpty()) {
                    pathParts.add(new PathPart(pathPart));
                }
            }
        }
        parsedUrl.setPathParts(pathParts);
    } catch (Exception ex) {
        Logger.error(UrlParser.class, "Can't parse URL " + url);
        return null;
    }
    return parsedUrl;
}

From source file:org.apache.hadoop.security.token.delegation.web.ServletUtils.java

/**
 * Extract a query string parameter without triggering http parameters
 * processing by the servlet container.//from  w  ww  .  j a  va2  s.  c  om
 *
 * @param request the request
 * @param name the parameter to get the value.
 * @return the parameter value, or <code>NULL</code> if the parameter is not
 * defined.
 * @throws IOException thrown if there was an error parsing the query string.
 */
public static String getParameter(HttpServletRequest request, String name) throws IOException {
    List<NameValuePair> list = URLEncodedUtils.parse(request.getQueryString(), UTF8_CHARSET);
    if (list != null) {
        for (NameValuePair nv : list) {
            if (name.equals(nv.getName())) {
                return nv.getValue();
            }
        }
    }
    return null;
}

From source file:io.servicecomb.foundation.common.net.URIEndpointObject.java

public static Map<String, List<String>> splitQuery(URI uri) {
    final Map<String, List<String>> queryPairs = new LinkedHashMap<String, List<String>>();
    List<NameValuePair> pairs = URLEncodedUtils.parse(uri, StandardCharsets.UTF_8.name());
    for (NameValuePair pair : pairs) {
        List<String> list = queryPairs.computeIfAbsent(pair.getName(), name -> {
            return new ArrayList<>();
        });//from www.j a v  a2s . co m
        list.add(pair.getValue());
    }
    return queryPairs;
}

From source file:org.onebusaway.io.client.test.UriAssert.java

/**
 * Check request for matching Uri./*from w  w  w .ja  v a2  s  .  com*/
 *
 * @param expectedUri   The Uri the test should expect (query values are ignored, use
 *                      expectedQuery)
 * @param expectedQuery A Map of query key/values required to be in the Uri.
 *                      Use asterisk to require key, but ignore value. Order is irrelevant.
 *                      The list is not exhaustive, extra key/values are ignored.
 */
public static void assertUriMatch(URI expectedUri, Map<String, String> expectedQuery, URI actualUri) {
    assertEquals(expectedUri.getHost(), actualUri.getHost());
    assertEquals(expectedUri.getScheme(), actualUri.getScheme());
    assertEquals(expectedUri.getPath(), actualUri.getPath());
    List<NameValuePair> actualParams = URLEncodedUtils.parse(actualUri, "UTF-8");

    if (expectedQuery != null) {
        for (Map.Entry<String, String> entry : expectedQuery.entrySet()) {
            String expectedValue = entry.getValue();
            String actualValue = null;

            // Find actual param
            for (NameValuePair pair : actualParams) {
                if (pair.getName().equalsIgnoreCase(entry.getKey())) {
                    actualValue = pair.getValue();
                }
            }

            if ("*".equals(expectedValue)) {
                assertNotNull("URI missing key \"" + entry.getKey() + "\"", actualValue);
            } else {
                assertEquals("URI mismatch on query key \"" + entry.getKey() + "\"", expectedValue,
                        actualValue);
            }
        }
    }
}