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:org.sakaiproject.util.impl.FormattedTextImpl.java

public String sanitizeHrefURL(String urlToSanitize) {
    if (urlToSanitize == null)
        return null;
    if (StringUtils.isBlank(urlToSanitize))
        return null;
    if (ABOUT_BLANK.equals(urlToSanitize))
        return ABOUT_BLANK;

    boolean trimProtocol = false;
    boolean trimHost = false;
    // For a protocol-relative URL, we validate with protocol attached 
    // RFC 1808 Section 4
    if ((urlToSanitize.startsWith("//")) && (urlToSanitize.indexOf("://") == -1)) {
        urlToSanitize = PROTOCOL_PREFIX + urlToSanitize;
        trimProtocol = true;//from  w  w w  . j a  v a 2s . c o m
    }

    // For a site-relative URL, we validate with host name and protocol attached 
    // SAK-13787 SAK-23752
    if ((urlToSanitize.startsWith("/")) && (urlToSanitize.indexOf("://") == -1)) {
        urlToSanitize = HOST_PREFIX + urlToSanitize;
        trimHost = true;
    }

    // KNL-1105
    try {
        URL rawUrl = new URL(urlToSanitize);
        URI uri = new URI(rawUrl.getProtocol(), rawUrl.getUserInfo(), rawUrl.getHost(), rawUrl.getPort(),
                rawUrl.getPath(), rawUrl.getQuery(), rawUrl.getRef());
        URL encoded = uri.toURL();
        String retval = encoded.toString();

        // Un-trim the added bits
        if (trimHost && retval.startsWith(HOST_PREFIX)) {
            retval = retval.substring(HOST_PREFIX.length());
        }

        if (trimProtocol && retval.startsWith(PROTOCOL_PREFIX)) {
            retval = retval.substring(PROTOCOL_PREFIX.length());
        }

        // http://stackoverflow.com/questions/7731919/why-doesnt-uri-escape-escape-single-quotes
        // We want these to be usable in JavaScript string values so we map single quotes
        retval = retval.replace("'", "%27");
        // We want anchors to work
        retval = retval.replace("%23", "#");
        // Sorry - these just need to come out - they cause to much trouble
        // Note that ampersand is not encoded as it is used for parameters.
        retval = retval.replace("&#", "");
        retval = retval.replace("%25", "%");
        return retval;
    } catch (java.net.URISyntaxException e) {
        M_log.info("Failure during encode of href url: " + e);
        return null;
    } catch (java.net.MalformedURLException e) {
        M_log.info("Failure during encode of href url: " + e);
        return null;
    }
}

From source file:org.springframework.security.oauth.consumer.CoreOAuthConsumerSupport.java

/**
 * Loads the OAuth parameters for the given resource at the given URL and the given token. These parameters include
 * any query parameters on the URL since they are included in the signature. The oauth parameters are NOT encoded.
 *
 * @param details      The resource details.
 * @param requestURL   The request URL.// www  .j  a  v  a  2 s .c om
 * @param requestToken The request token.
 * @param httpMethod   The http method.
 * @param additionalParameters Additional oauth parameters (outside of the core oauth spec).
 * @return The parameters.
 */
protected Map<String, Set<CharSequence>> loadOAuthParameters(ProtectedResourceDetails details, URL requestURL,
        OAuthConsumerToken requestToken, String httpMethod, Map<String, String> additionalParameters) {
    Map<String, Set<CharSequence>> oauthParams = new TreeMap<String, Set<CharSequence>>();

    if (additionalParameters != null) {
        for (Map.Entry<String, String> additionalParam : additionalParameters.entrySet()) {
            Set<CharSequence> values = oauthParams.get(additionalParam.getKey());
            if (values == null) {
                values = new HashSet<CharSequence>();
                oauthParams.put(additionalParam.getKey(), values);
            }
            if (additionalParam.getValue() != null) {
                values.add(additionalParam.getValue());
            }
        }
    }

    String query = requestURL.getQuery();
    if (query != null) {
        StringTokenizer queryTokenizer = new StringTokenizer(query, "&");
        while (queryTokenizer.hasMoreElements()) {
            String token = (String) queryTokenizer.nextElement();
            CharSequence value = null;
            int equalsIndex = token.indexOf('=');
            if (equalsIndex < 0) {
                token = urlDecode(token);
            } else {
                value = new QueryParameterValue(urlDecode(token.substring(equalsIndex + 1)));
                token = urlDecode(token.substring(0, equalsIndex));
            }

            Set<CharSequence> values = oauthParams.get(token);
            if (values == null) {
                values = new HashSet<CharSequence>();
                oauthParams.put(token, values);
            }
            if (value != null) {
                values.add(value);
            }
        }
    }

    String tokenSecret = requestToken == null ? null : requestToken.getSecret();
    String nonce = getNonceFactory().generateNonce();
    oauthParams.put(OAuthConsumerParameter.oauth_consumer_key.toString(),
            Collections.singleton((CharSequence) details.getConsumerKey()));
    if ((requestToken != null) && (requestToken.getValue() != null)) {
        oauthParams.put(OAuthConsumerParameter.oauth_token.toString(),
                Collections.singleton((CharSequence) requestToken.getValue()));
    }

    oauthParams.put(OAuthConsumerParameter.oauth_nonce.toString(), Collections.singleton((CharSequence) nonce));
    oauthParams.put(OAuthConsumerParameter.oauth_signature_method.toString(),
            Collections.singleton((CharSequence) details.getSignatureMethod()));
    oauthParams.put(OAuthConsumerParameter.oauth_timestamp.toString(),
            Collections.singleton((CharSequence) String.valueOf(System.currentTimeMillis() / 1000)));
    oauthParams.put(OAuthConsumerParameter.oauth_version.toString(),
            Collections.singleton((CharSequence) "1.0"));
    String signatureBaseString = getSignatureBaseString(oauthParams, requestURL, httpMethod);
    OAuthSignatureMethod signatureMethod = getSignatureFactory()
            .getSignatureMethod(details.getSignatureMethod(), details.getSharedSecret(), tokenSecret);
    String signature = signatureMethod.sign(signatureBaseString);
    oauthParams.put(OAuthConsumerParameter.oauth_signature.toString(),
            Collections.singleton((CharSequence) signature));
    return oauthParams;
}

From source file:org.apache.http.benchmark.HttpBenchmark.java

private void prepare() throws UnsupportedEncodingException {
    // prepare http params
    params = getHttpParams(config.getSocketTimeout(), config.isUseHttp1_0(), config.isUseExpectContinue());

    URL url = config.getUrl();
    host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    HttpEntity entity = null;//from   w  ww . jav a2  s .c  o m

    // Prepare requests for each thread
    if (config.getPayloadFile() != null) {
        entity = new FileEntity(config.getPayloadFile(), config.getContentType());
        ((FileEntity) entity).setChunked(config.isUseChunking());
        contentLength = config.getPayloadFile().length();

    } else if (config.getPayloadText() != null) {
        entity = new StringEntity(config.getPayloadText(), config.getContentType(), "UTF-8");
        ((StringEntity) entity).setChunked(config.isUseChunking());
        contentLength = config.getPayloadText().getBytes().length;
    }
    request = new HttpRequest[config.getThreads()];

    for (int i = 0; i < request.length; i++) {
        if ("POST".equals(config.getMethod())) {
            BasicHttpEntityEnclosingRequest httppost = new BasicHttpEntityEnclosingRequest("POST",
                    url.getPath());
            httppost.setEntity(entity);
            request[i] = httppost;
        } else if ("PUT".equals(config.getMethod())) {
            BasicHttpEntityEnclosingRequest httpput = new BasicHttpEntityEnclosingRequest("PUT", url.getPath());
            httpput.setEntity(entity);
            request[i] = httpput;
        } else {
            String path = url.getPath();
            if (url.getQuery() != null && url.getQuery().length() > 0) {
                path += "?" + url.getQuery();
            } else if (path.trim().length() == 0) {
                path = "/";
            }
            request[i] = new BasicHttpRequest(config.getMethod(), path);
        }
    }

    if (!config.isKeepAlive()) {
        for (int i = 0; i < request.length; i++) {
            request[i].addHeader(new DefaultHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
        }
    }

    String[] headers = config.getHeaders();
    if (headers != null) {
        for (int i = 0; i < headers.length; i++) {
            String s = headers[i];
            int pos = s.indexOf(':');
            if (pos != -1) {
                Header header = new DefaultHeader(s.substring(0, pos).trim(), s.substring(pos + 1));
                for (int j = 0; j < request.length; j++) {
                    request[j].addHeader(header);
                }
            }
        }
    }

    if (config.isUseAcceptGZip()) {
        for (int i = 0; i < request.length; i++) {
            request[i].addHeader(new DefaultHeader("Accept-Encoding", "gzip"));
        }
    }

    if (config.getSoapAction() != null && config.getSoapAction().length() > 0) {
        for (int i = 0; i < request.length; i++) {
            request[i].addHeader(new DefaultHeader("SOAPAction", config.getSoapAction()));
        }
    }
}

From source file:com.google.acre.script.HostEnv.java

/**
 * create a fresh request scope./* w ww .j a  va2  s.  c  om*/
 * we re-use the old AcreRequest object after augmenting it with
 *  information about the redirect.
 * for isolation reasons we create a complete new HostEnv and
 *  js context - only the information on AcreRequest is carried through.
 *
 * NOTE it is the caller's responsibility to exit after calling this
 *  function
 *
 *  @returns the new HostEnv
 */

public HostEnv internalRedirect(String script_path, boolean skip_routes) throws IOException {
    syslog(DEBUG, "hostenv.script.internalredirect", "internal redirect to " + script_path);

    // reset the request path_info and query_string
    URL url;
    try {
        url = new URL("http:" + script_path);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }

    String query_string = url.getQuery();

    if (query_string == null) {
        query_string = "";
    }

    req.setPathInfo(url.getPath());
    req.setQueryString(query_string);

    // reset the response
    res.reset();

    // create a new HostEnv and populate it from this
    // we re-use the same AcreRequest
    // NOTE: keep checking for time quota for all error pages
    // that are not the default one
    HostEnv newenv = new HostEnv(_resourceSource, req, res, _supervisor);
    newenv._parent_hostenv = this;

    // modify the AcreRequest to add any additional info
    req.handler_script_path = script_path;
    req.skip_routes = skip_routes;

    // if the script is an error script, add additional time to the quota for the error script
    // to be executed. Note that urlfetches by user error scripts are restricted
    // so that this extended time does not get passed on further.
    if (req.error_info != null) {
        req._deadline += ERROR_DEADLINE_EXTENSION;
    }

    // exit the old Context (which is stored thread-local by rhino)
    if (_context != null) {
        Context.exit();
        _context = null;
    }

    // remove any supervisor watch on this thread
    //  (it will be re-established for the error page)
    if (_supervised) {
        Thread thread = Thread.currentThread();
        _supervisor.release(thread);
        _supervised = false;
    }

    // run the request using a fresh js context but the same thread
    newenv.run();

    return newenv;
}

From source file:org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport.java

/**
 * Loads the OAuth parameters for the given resource at the given URL and the given token. These parameters include
 * any query parameters on the URL since they are included in the signature. The oauth parameters are NOT encoded.
 *
 * @param details      The resource details.
 * @param requestURL   The request URL./*www  . j a  v  a 2 s. co m*/
 * @param requestToken The request token.
 * @param httpMethod   The http method.
 * @param additionalParameters Additional oauth parameters (outside of the core oauth spec).
 * @return The parameters.
 */
protected Map<String, Set<CharSequence>> loadOAuthParameters(ProtectedResourceDetails details, URL requestURL,
        OAuthConsumerToken requestToken, String httpMethod, Map<String, String> additionalParameters) {
    Map<String, Set<CharSequence>> oauthParams = new TreeMap<String, Set<CharSequence>>();

    if (additionalParameters != null) {
        for (Map.Entry<String, String> additionalParam : additionalParameters.entrySet()) {
            Set<CharSequence> values = oauthParams.get(additionalParam.getKey());
            if (values == null) {
                values = new HashSet<CharSequence>();
                oauthParams.put(additionalParam.getKey(), values);
            }
            if (additionalParam.getValue() != null) {
                values.add(additionalParam.getValue());
            }
        }
    }

    String query = requestURL.getQuery();
    if (query != null) {
        StringTokenizer queryTokenizer = new StringTokenizer(query, "&");
        while (queryTokenizer.hasMoreElements()) {
            String token = (String) queryTokenizer.nextElement();
            CharSequence value = null;
            int equalsIndex = token.indexOf('=');
            if (equalsIndex < 0) {
                token = urlDecode(token);
            } else {
                value = new QueryParameterValue(urlDecode(token.substring(equalsIndex + 1)));
                token = urlDecode(token.substring(0, equalsIndex));
            }

            Set<CharSequence> values = oauthParams.get(token);
            if (values == null) {
                values = new HashSet<CharSequence>();
                oauthParams.put(token, values);
            }
            if (value != null) {
                values.add(value);
            }
        }
    }

    String tokenSecret = requestToken == null ? null : requestToken.getSecret();
    String nonce = getNonceFactory().generateNonce();
    oauthParams.put(OAuthConsumerParameter.oauth_consumer_key.toString(),
            Collections.singleton((CharSequence) details.getConsumerKey()));
    if ((requestToken != null) && (requestToken.getValue() != null)) {
        oauthParams.put(OAuthConsumerParameter.oauth_token.toString(),
                Collections.singleton((CharSequence) requestToken.getValue()));
    }

    oauthParams.put(OAuthConsumerParameter.oauth_nonce.toString(), Collections.singleton((CharSequence) nonce));
    oauthParams.put(OAuthConsumerParameter.oauth_signature_method.toString(),
            Collections.singleton((CharSequence) details.getSignatureMethod()));
    oauthParams.put(OAuthConsumerParameter.oauth_timestamp.toString(),
            Collections.singleton((CharSequence) String.valueOf(System.currentTimeMillis() / 1000)));
    oauthParams.put(OAuthConsumerParameter.oauth_version.toString(),
            Collections.singleton((CharSequence) "1.0"));
    String signatureBaseString = getSignatureBaseString(oauthParams, requestURL, httpMethod);
    OAuthSignatureMethod signatureMethod;
    try {
        signatureMethod = getSignatureFactory().getSignatureMethod(details.getSignatureMethod(),
                details.getSharedSecret(), tokenSecret);
    } catch (UnsupportedSignatureMethodException e) {
        throw new OAuthRequestFailedException(e.getMessage(), e);
    }
    String signature = signatureMethod.sign(signatureBaseString);
    oauthParams.put(OAuthConsumerParameter.oauth_signature.toString(),
            Collections.singleton((CharSequence) signature));
    return oauthParams;
}

From source file:org.imsglobal.lti.toolProvider.ResourceLink.java

/**
 * Send a service request to the tool consumer.
 *
 * @param string type Message type value
 * @param string url  URL to send request to
 * @param string xml  XML of message request
 *
 * @return boolean True if the request successfully obtained a response
 *//*  w  ww.j  a va2s.c o  m*/
private boolean doLTI11Service(String type, String url, String xml) {

    boolean ok = false;
    this.extRequest = null;
    this.extRequestHeaders = null;
    this.extResponse = null;
    this.extResponseHeaders = null;
    if (StringUtils.isNotEmpty(url)) {
        String messageId = UUID.randomUUID().toString();
        String xmlRequest = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n"
                + "<imsx_POXEnvelopeRequest xmlns = \"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0\">\n"
                + "  <imsx_POXHeader>\n" + "    <imsx_POXRequestHeaderInfo>\n"
                + "      <imsx_version>V1.0</imsx_version>\n" + "      <imsx_messageIdentifier>" + id
                + "</imsx_messageIdentifier>\n" + "    </imsx_POXRequestHeaderInfo>\n" + "  </imsx_POXHeader>\n"
                + "  <imsx_POXBody>\n" + "    <" + type + "Request>\n" + xml + "    </" + type + "Request>\n"
                + "  </imsx_POXBody>\n" + "</imsx_POXEnvelopeRequest>\n";
        // Calculate body hash
        String hash = Base64.encodeBase64String(DigestUtils.sha1(xmlRequest.toString()));
        Map<String, String> params = new HashMap<String, String>();
        params.put("oauth_body_hash", hash);
        HashSet<Map.Entry<String, String>> httpParams = new HashSet<Map.Entry<String, String>>();
        httpParams.addAll(params.entrySet());
        // Check for query parameters which need to be included in the signature
        Map<String, String> queryParams = new HashMap<String, String>();
        String urlNoQuery = url;
        try {
            URL uri = new URL(url);
            String query = uri.getQuery();
            if (query != null) {
                urlNoQuery = urlNoQuery.substring(0, urlNoQuery.length() - query.length() - 1);
                String[] queryItems = query.split("&");
                for (int i = 0; i < queryItems.length; i++) {
                    String[] queryItem = queryItems[i].split("=", 2);
                    if (queryItem.length > 1) {
                        queryParams.put(queryItem[0], queryItem[1]);
                    } else {
                        queryParams.put(queryItem[0], "");
                    }
                }
                httpParams.addAll(queryParams.entrySet());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Add OAuth signature
        Map<String, String> header = new HashMap<String, String>();
        OAuthMessage oAuthMessage = new OAuthMessage("POST", urlNoQuery, httpParams);
        OAuthConsumer oAuthConsumer = new OAuthConsumer("about:blank", this.consumer.getKey(),
                this.consumer.getSecret(), null);
        OAuthAccessor oAuthAccessor = new OAuthAccessor(oAuthConsumer);
        try {
            oAuthMessage.addRequiredParameters(oAuthAccessor);
            header.put("Authorization", oAuthMessage.getAuthorizationHeader(null));
            header.put("Content-Type", "application/xml");
        } catch (OAuthException e) {
        } catch (URISyntaxException e) {
        } catch (IOException e) {
        }
        try {
            StringEntity entity = new StringEntity(xmlRequest);

            // Connect to tool consumer
            this.extResponse = doPostRequest(url, LTIUtil.getHTTPParams(params), header, entity);
            // Parse XML response
            if (this.extResponse != null) {
                this.extDoc = LTIUtil.getXMLDoc(extResponse);
                ok = this.extDoc != null;
                if (ok) {
                    Element el = LTIUtil.getXmlChild(this.extDoc.getRootElement(), "imsx_statusInfo");
                    ok = el != null;
                    if (ok) {
                        String responseCode = LTIUtil.getXmlChildValue(el, "imsx_codeMajor");
                        ok = responseCode != null;
                        if (ok) {
                            ok = responseCode.equals("success");
                        }
                    }
                }
                if (!ok) {
                    this.extResponse = null;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    return (this.extResponse != null);

}

From source file:com.rsltc.profiledata.main.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button loginButton = (Button) findViewById(R.id.button);
    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override/*  w  w  w. j  a v a 2s  .  co  m*/
        public void onClick(View v) {
            try {
                AlertDialog.Builder alert = new AlertDialog.Builder(thisActivity);
                alert.setTitle("Title here");

                StringBuilder query = new StringBuilder();

                query.append("redirect_uri=" + URLEncoder.encode(redirectUri, "utf-8"));
                query.append("&client_id=" + URLEncoder.encode(clientId, "utf-8"));
                query.append("&scope=" + URLEncoder.encode(scopes, "utf-8"));

                query.append("&response_type=code");
                URI uri = new URI("https://login.live.com/oauth20_authorize.srf?" + query.toString());

                URL url = uri.toURL();

                final WebView wv = new WebView(thisActivity);

                WebSettings webSettings = wv.getSettings();
                webSettings.setJavaScriptEnabled(true);
                wv.loadUrl(url.toString());
                wv.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String location) {
                        Log.e(TAG, location);
                        // TODO: extract to method
                        try {
                            URL url = new URL(location);

                            if (url.getPath().equalsIgnoreCase("/oauth20_desktop.srf")) {
                                System.out.println("Dit werkt al!");
                                System.out.println(url.getQuery());
                                Map<String, List<String>> result = splitQuery(url);
                                if (result.containsKey("code")) {
                                    System.out.println("bevat code");
                                    if (result.containsKey("error")) {
                                        System.out.println(String.format("{0}\r\n{1}", result.get("error"),
                                                result.get("errorDesc")));
                                    }
                                    System.out.println(result.get("code").get(0));
                                    String tokenError = GetToken(result.get("code").get(0), false);
                                    if (tokenError == null || "".equals(tokenError)) {
                                        System.out.println("Successful sign-in!");
                                        Log.e(TAG, "Successful sign-in!");
                                    } else {
                                        Log.e(TAG, "tokenError: " + tokenError);
                                    }
                                } else {
                                    System.out.println("Successful sign-out!");
                                }
                            }
                        } catch (IOException | URISyntaxException e) {
                            e.printStackTrace();
                        }

                        view.loadUrl(location);

                        return true;
                    }
                });
                LinearLayout linearLayout = new LinearLayout(thisActivity);
                linearLayout.setMinimumHeight(500);
                ArrayList<View> views = new ArrayList<View>();
                views.add(wv);
                linearLayout.addView(wv);
                EditText text = new EditText(thisActivity);
                text.setVisibility(View.GONE);
                linearLayout.addView(text);
                alert.setView(linearLayout);
                alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                    }
                });
                alert.show();
            } catch (Exception e) {
                Log.e(TAG, "dd");
            }
        }
    });
    Button showProfile = (Button) findViewById(R.id.button2);
    showProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showProfile();
        }
    });
    Button showSummmary = (Button) findViewById(R.id.button3);
    showSummmary.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showSummaries();
        }
    });

    if (savedInstanceState != null)

    {
        authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
    }

    buildFitnessClient();
}

From source file:org.opencms.workplace.tools.database.CmsHtmlImport.java

/**
 * Calculates an absolute uri from a relative "uri" and the given absolute "baseUri".<p> 
 * //from   w  w w. ja v a2  s.c o  m
 * If "uri" is already absolute, it is returned unchanged.
 * This method also returns "uri" unchanged if it is not well-formed.<p>
 *    
 * @param relativeUri the relative uri to calculate an absolute uri for
 * @param baseUri the base uri, this must be an absolute uri
 * @return an absolute uri calculated from "uri" and "baseUri"
 */
public String getAbsoluteUri(String relativeUri, String baseUri) {

    if ((relativeUri == null) || (relativeUri.charAt(0) == '/') || (relativeUri.startsWith("#"))) {

        return relativeUri;
    }

    // if we are on a windows system, we must add a ":" in the uri later               
    String windowsAddition = "";
    if (File.separator.equals("\\")) {
        windowsAddition = ":";
    }

    try {
        URL baseUrl = new URL("file://");
        URL url = new URL(new URL(baseUrl, "file://" + baseUri), relativeUri);
        if (url.getQuery() == null) {
            if (url.getRef() == null) {
                return url.getHost() + windowsAddition + url.getPath();
            } else {
                return url.getHost() + windowsAddition + url.getPath() + "#" + url.getRef();
            }
        } else {
            return url.getHost() + windowsAddition + url.getPath() + "?" + url.getQuery();
        }
    } catch (MalformedURLException e) {
        return relativeUri;
    }
}

From source file:com.buildabrand.gsb.util.URLUtils.java

/**
 * Returns the canonicalized form of a URL, core logic written by Henrik Sjostrand, heavily modified for v2 by Dave Shanley.
 *
 * @param queryURL//www . ja v  a  2  s.  c  om
 * @return
 * @author Henrik Sjostrand, Netvouz, http://www.netvouz.com/, info@netvouz.com & Dave Shanley <dave@buildabrand.com>
 */
public String canonicalizeURL(String queryURL) {
    if (StringUtils.isEmpty(queryURL)) {
        return null;
    }

    // Start by stripping off the fragment identifier.
    queryURL = StringUtils.substringBefore(queryURL, "#");
    // Stripping off leading and trailing white spaces.
    queryURL = StringUtils.trim(queryURL);
    // Remove any embedded tabs and CR/LF characters which aren't escaped.
    queryURL = StringUtils.remove(queryURL, '\t');
    queryURL = StringUtils.remove(queryURL, '\r');
    queryURL = StringUtils.remove(queryURL, '\n');

    // Un-escape and re-escpae the URL just in case there are some encoded
    // characters in the url scheme for example.
    queryURL = escape(queryURL);

    URL url;
    try {
        url = new URL(queryURL);
    } catch (MalformedURLException e) {
        // Try again with "http://"
        try {
            url = new URL("http://" + queryURL);
        } catch (MalformedURLException e2) {
            logger.error("Malformed url", e);
            return null;
        }
    }

    if (!(url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equalsIgnoreCase("https")
            || url.getProtocol().equalsIgnoreCase("ftp"))) {
        return null;
    }

    // Note: applying HOST_PORT_REGEXP also removes any user and password.
    Matcher hostMatcher = HOST_PORT_REGEXP.matcher(url.getHost());

    if (!hostMatcher.find()) {
        return null;
    }

    String host = hostMatcher.group(1);

    String canonicalHost = canonicalizeHost(host);
    if (canonicalHost == null) {
        return null;
    }

    // Now that the host is canonicalized we add the port back if it's not the
    // default port for that url scheme
    if (url.getPort() != -1 && ((url.getProtocol().equalsIgnoreCase("http") && url.getPort() != 80)
            || (url.getProtocol().equalsIgnoreCase("https") && url.getPort() != 443)
            || (url.getProtocol().equalsIgnoreCase("ftp") && url.getPort() != 21))) {
        canonicalHost = canonicalHost + ":" + url.getPort();
    }

    String canonicalPath = canonicalizePath(url.getPath());

    String canonicalUrl = url.getProtocol() + "://" + canonicalHost + canonicalPath;
    if (StringUtils.isNotEmpty(url.getQuery()) || queryURL.endsWith("?")) {
        canonicalUrl += "?" + url.getQuery();
    }

    return canonicalUrl;
}

From source file:org.apache.shindig.common.testing.FakeHttpServletRequest.java

public FakeHttpServletRequest(String urlStr) throws MalformedURLException {
    URL url = new URL(urlStr);
    String contextPath;//from w ww. j a  v a 2s  .c  om
    String servletPath;
    String path = url.getPath();
    if (path.length() <= 1) {
        // path must be either empty string or "/"
        contextPath = path;
        servletPath = null;
    } else {
        // Look for the second slash which separates the servlet path from the
        // context path. e.g. "/foo/bar"
        int secondSlash = path.indexOf('/', 1);
        if (secondSlash < 0) {
            // No second slash
            contextPath = path;
            servletPath = null;
        } else {
            contextPath = path.substring(0, secondSlash);
            servletPath = path.substring(secondSlash);
        }
    }

    // Set the scheme
    scheme = url.getProtocol();
    if (scheme.equalsIgnoreCase("https")) {
        secure = true;
    }

    int port = url.getPort();

    // Call constructor() instead of this() because the later is only allowed
    // at the begining of a constructor
    constructor(url.getHost(), port, contextPath, servletPath, url.getQuery());
}