Example usage for java.net URL getQuery

List of usage examples for java.net URL getQuery

Introduction

In this page you can find the example usage for java.net URL getQuery.

Prototype

public String getQuery() 

Source Link

Document

Gets the query part of this URL .

Usage

From source file:de.betterform.agent.betty.Betty.java

public static URI toFileCompatibleURI(URL url) throws URISyntaxException {
    if (url == null) {
        return null;
    }/*from ww w  .j  av  a2  s .  c  o  m*/

    String string = url.toString();
    if (url.getProtocol().equals("file") && url.getQuery() != null) {
        return new URI(string.substring(0, string.indexOf('?')));
    }

    return new URI(string);
}

From source file:com.vmware.identity.SharedUtils.java

/**
 * Create mock request based on the url/*from   w w w.j a  v a2s.c  om*/
 *
 * @param string
 * @return
 * @throws MalformedURLException
 * @throws UnsupportedEncodingException
 */
public static HttpServletRequest buildMockRequestObjectFromUrl(String string)
        throws MalformedURLException, UnsupportedEncodingException {
    Cookie[] expectedCookies = new Cookie[] {};

    URL url = new URL(string);
    Map<String, String> queryMap = getQueryMap(url.getQuery());

    String samlRequestParameter = getParameterFromQueryMap(queryMap, Shared.SAML_REQUEST_PARAMETER);
    String relayStateParameter = getParameterFromQueryMap(queryMap, Shared.RELAY_STATE_PARAMETER);
    String sigAlgParameter = getParameterFromQueryMap(queryMap, Shared.SIGNATURE_ALGORITHM_PARAMETER);
    String signatureParameter = getParameterFromQueryMap(queryMap, Shared.SIGNATURE_PARAMETER);
    StringBuffer sbRequestUrl = new StringBuffer();
    sbRequestUrl.append(string.replace("?" + url.getQuery(), ""));

    // build mock request object
    HttpServletRequest request = createMock(HttpServletRequest.class);
    expect(request.getCookies()).andReturn(expectedCookies).anyTimes();
    expect(request.getParameter(Shared.SAML_REQUEST_PARAMETER)).andReturn(samlRequestParameter).anyTimes();
    expect(request.getParameter(Shared.RELAY_STATE_PARAMETER)).andReturn(relayStateParameter).anyTimes();
    expect(request.getParameter(Shared.SIGNATURE_ALGORITHM_PARAMETER)).andReturn(sigAlgParameter).anyTimes();
    expect(request.getParameter(Shared.SIGNATURE_PARAMETER)).andReturn(signatureParameter).anyTimes();
    expect(request.getRequestURL()).andReturn(sbRequestUrl).anyTimes();
    expect(request.getParameter(Shared.REQUEST_AUTH_PARAM)).andReturn(TestConstants.AUTHORIZATION).anyTimes();
    String queryString = Shared.SAML_REQUEST_PARAMETER + "=" + samlRequestParameter;
    if (relayStateParameter != null) {
        queryString = queryString + "&" + Shared.RELAY_STATE_PARAMETER + "=" + relayStateParameter;
    }
    if (sigAlgParameter != null) {
        queryString = queryString + "&" + Shared.SIGNATURE_ALGORITHM_PARAMETER + "=" + sigAlgParameter;
    }
    if (signatureParameter != null) {
        queryString = queryString + "&" + Shared.SIGNATURE_PARAMETER + "=" + signatureParameter;
    }
    expect(request.getQueryString()).andReturn(queryString).anyTimes();

    replay(request);
    return request;
}

From source file:io.github.tavernaextras.biocatalogue.model.Util.java

/**
 * Extracts the query string from the provided URL. Parses this query string into
 * a map of parameters./*  w  ww .j a va 2 s.c  om*/
 * 
 * All parameters (both names and values) will have special characters unescaped
 * (i.e. decoded from the standard url-encoding) and can be used directly.
 * 
 * @param url The string representation of the URL to parse.
 */
public static Map<String, String> extractURLParameters(String url) {
    try {
        // extract the query part of the supplied URL
        URL theURL = new URL(url);
        String queryString = theURL.getQuery();

        // prepare storage for output
        Map<String, String> parameterMap = null;

        // extract each name-value pair from query string (if any are specified in the URL)
        if (queryString != null && queryString.length() > 0) {
            // only initialise if there are some parameters
            parameterMap = new HashMap<String, String>();

            for (String parameter : queryString.split("&")) {
                String[] nameValueArr = parameter.split("=");

                String name = nameValueArr[0]; // parameter name must always be present
                String value = (nameValueArr.length == 2 ? nameValueArr[1] : null); // could be that parameter value is not set (e.g. "q=") - insert null then

                // decode possible special characters
                name = urlDecodeQuery(name);
                if (value != null)
                    value = urlDecodeQuery(value);

                parameterMap.put(name, value);
            }
        }

        return (parameterMap);
    } catch (MalformedURLException e) {
        // some problem occurred - report it; can't return any data in this case
        logger.error("Couldn't parse parameters of a URL: " + url + "; details below:", e);
        return null;
    }
}

From source file:net.antidot.semantic.rdf.rdb2rdf.r2rml.tools.R2RMLToolkit.java

/**
 * The URL-safe version of a string is obtained by an URL encoding to a
 * string value.//from  w  w  w  . j  a  v a 2s  .co  m
 * 
 * @throws R2RMLDataError
 * @throws MalformedURLException
 */
public static String getURLSafeVersion(String value) throws R2RMLDataError {
    if (value == null)
        return null;
    URL url = null;
    try {
        url = new URL(value);
    } catch (MalformedURLException mue) {
        // This template should be not a url : no encoding
        return value;
    }
    // No exception raised, this template is a valid url : perform
    // percent-encoding
    try {
        java.net.URI uri = new java.net.URI(url.getProtocol(), url.getAuthority(), url.getPath(),
                url.getQuery(), url.getRef());
        String result = uri.toURL().toString();
        // Percent encoding : complete with no supported char in this
        // treatment
        result = result.replaceAll("\\,", "%2C");
        return result;
    } catch (URISyntaxException e) {
        throw new R2RMLDataError("[R2RMLToolkit:getIRISafeVersion] This value " + value
                + " can not be percent-encoded because " + e.getMessage());
    } catch (MalformedURLException e) {
        throw new R2RMLDataError("[R2RMLToolkit:getIRISafeVersion] This value " + value
                + " can not be percent-encoded because " + e.getMessage());
    }
}

From source file:org.apache.hadoop.hdfs.web.WebHdfsFileSystem.java

/** Remove offset parameter, if there is any, from the url */
static URL removeOffsetParam(final URL url) throws MalformedURLException {
    String query = url.getQuery();
    if (query == null) {
        return url;
    }/*from   ww w .ja  va2s .co  m*/
    final String lower = query.toLowerCase();
    if (!lower.startsWith(OFFSET_PARAM_PREFIX) && !lower.contains("&" + OFFSET_PARAM_PREFIX)) {
        return url;
    }

    //rebuild query
    StringBuilder b = null;
    for (final StringTokenizer st = new StringTokenizer(query, "&"); st.hasMoreTokens();) {
        final String token = st.nextToken();
        if (!token.toLowerCase().startsWith(OFFSET_PARAM_PREFIX)) {
            if (b == null) {
                b = new StringBuilder("?").append(token);
            } else {
                b.append('&').append(token);
            }
        }
    }
    query = b == null ? "" : b.toString();

    final String urlStr = url.toString();
    return new URL(urlStr.substring(0, urlStr.indexOf('?')) + query);
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified port.
 * @param u the URL on which to base the returned URL
 * @param newPort the new port to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified port
 * @throws MalformedURLException if there is a problem creating the new URL
 *//*from   ww  w  .  j  a  v a2s.com*/
public static URL getUrlWithNewPort(final URL u, final int newPort) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), newPort, u.getPath(), u.getRef(), u.getQuery());
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified reference.
 * @param u the URL on which to base the returned URL
 * @param newRef the new reference to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified reference
 * @throws MalformedURLException if there is a problem creating the new URL
 */// ww  w  . j a  v  a  2 s  . c  om
public static URL getUrlWithNewRef(final URL u, final String newRef) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), u.getPort(), u.getPath(), newRef, u.getQuery());
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified host.
 * @param u the URL on which to base the returned URL
 * @param newHost the new host to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified host
 * @throws MalformedURLException if there is a problem creating the new URL
 *///from ww w . j av a  2s.c o m
public static URL getUrlWithNewHost(final URL u, final String newHost) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), newHost, u.getPort(), u.getPath(), u.getRef(), u.getQuery());
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified path.
 * @param u the URL on which to base the returned URL
 * @param newPath the new path to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified path
 * @throws MalformedURLException if there is a problem creating the new URL
 *///  w  w w.  j a v  a2  s .  com
public static URL getUrlWithNewPath(final URL u, final String newPath) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), u.getPort(), newPath, u.getRef(), u.getQuery());
}

From source file:io.github.tavernaextras.biocatalogue.model.Util.java

/**
 * This method takes a string representation of a URL and a name-value pair
 * of strings to add to the URL as a new parameter.
 * // w  w w .j av a  2  s.  c  om
 * If parameter with the same name was already present in the URL, the new value
 * will replace the existing one.
 * 
 * @param url The URL to add a new parameter to.
 * @param name Name of the parameter to add.
 * @param value Value of the parameter to add.
 * @return New string which is the original <code>url</code> with the desired
 *         parameter (<code>name</code>=<code>value</code> pair) added to it.
 */
public static String appendURLParameter(String url, String name, String value) {
    // if name of the parameter is not given, ignore this request
    // (makes sense to return the same URL as the input in this case -
    //  as appending "nothing" wouldn't make it any different)
    if (name == null || name.length() == 0) {
        return (url);
    }

    // do everything in the protected block
    try {
        // parse the parameters of the given URL
        Map<String, String> urlParameters = extractURLParameters(url);
        if (urlParameters == null) {
            // there were no parameters in the original URL, create new map
            urlParameters = new HashMap<String, String>();
        }

        // add the new parameter (this will replace a parameter with identical
        // name if it was already present in the map)
        urlParameters.put(name, value);

        // parse the URL string into the URL object to extract original query string
        URL theURL = new URL(url);
        String originalQueryString = theURL.getQuery();

        // prepare the basis for the new URL to return
        String newUrl = null;
        if (originalQueryString != null) {
            // replace the original query string with empty space to
            // give way for appending the new query string
            newUrl = url.replace(originalQueryString, "");
        } else {
            // there were no parameters in the original URL
            newUrl = url + "?";
        }

        // append the new query string
        newUrl += constructURLQueryString(urlParameters);

        return (newUrl);
    } catch (Exception e) {
        logger.error("\nCouldn't append parameter ('" + name + "', '" + value + "') to the URL: " + url, e);
        return (null);
    }
}