Java URL Resolve reverseUrl(String urlString)

Here you can find the source of reverseUrl(String urlString)

Description

Reverses a url's domain.

License

Apache License

Parameter

Parameter Description
url url to be reversed

Exception

Parameter Description
MalformedURLException an exception

Return

Reversed url

Declaration

public static String reverseUrl(String urlString) throws MalformedURLException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    /** Reverses a url's domain. This form is better for storing in hbase. 
     * Because scans within the same domain are faster. <p>
     * E.g. "http://bar.foo.com:8983/to/index.html?a=b" becomes 
     * "com.foo.bar:8983:http/to/index.html?a=b".
     * @param url url to be reversed//from  ww  w  .  j  a v  a  2s .co m
     * @return Reversed url
     * @throws MalformedURLException 
     */
    public static String reverseUrl(String urlString) throws MalformedURLException {
        return reverseUrl(new URL(urlString));
    }

    /** Reverses a url's domain. This form is better for storing in hbase. 
     * Because scans within the same domain are faster. <p>
     * E.g. "http://bar.foo.com:8983/to/index.html?a=b" becomes 
     * "com.foo.bar:http:8983/to/index.html?a=b".
     * @param url url to be reversed
     * @return Reversed url
     */
    public static String reverseUrl(URL url) {
        String host = url.getHost();
        String file = url.getFile();
        String protocol = url.getProtocol();
        int port = url.getPort();

        StringBuilder buf = new StringBuilder();

        /* reverse host */
        reverseAppendSplits(host.split("\\."), buf);

        /* add protocol */
        buf.append(':');
        buf.append(protocol);

        /* add port if necessary */
        if (port != -1) {
            buf.append(':');
            buf.append(port);
        }

        /* add path */
        if (file.length() == 0 || '/' != file.charAt(0)) {
            buf.append('/');
        }
        buf.append(file);

        return buf.toString();
    }

    private static void reverseAppendSplits(String[] splits, StringBuilder buf) {
        for (int i = splits.length - 1; i > 0; i--) {
            buf.append(splits[i]);
            buf.append('.');
        }
        buf.append(splits[0]);
    }
}

Related

  1. resolveURL(URL base, String target)
  2. resolveURL(URL contextURL, String url)
  3. resolveURL(URL url)
  4. resolveWsURI(String url)
  5. resolveXmlConfigUrl(@Nullable URL defaultXmlConfigUrl)