// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.net.MalformedURLException;
import java.net.URL;

public class UrlFun {
    private static URL urlNormalize(URL u) throws MalformedURLException {
        String prot = u.getProtocol();
        String host = u.getHost();
        int port = u.getPort();
        String path = u.getPath();
        String query = u.getQuery();
        String[] pp = path.split("/");
        String newpath = "";
        int ix = pp.length - 1;
        while(ix >= 0) {
            if(pp[ix].equals(".")) {
                // skip
            } else if(pp[ix].equals("..")) {
                ix--; // skip this and previous
            } else {
                newpath = pp[ix] + (newpath.length() > 0 ? "/" : "") +newpath; // use
            }
            ix--;
        }
        return new URL(prot, host, port, newpath + (query != null ? "?" + query : ""));
    }
    private static void test(String urlstr) throws MalformedURLException {
        URL u1 = new URL(urlstr);
        URL u2 = urlNormalize(u1);
        System.out.println(u1 + " -> " + u2);
    }
    public static void main(String[] args) throws Exception {
        test("http://aau.dk/someDir/../");
        test("http://aau.dk/");
        test("http://www.xxx.dk/a/b/../c/d/../e/f/foobar.html");
        test("http://www.xxx.dk/a/b/.././foobar.html");
        test("http://www.xxx.dk:81/dir/foobar.html");
        test("http://www.xxx.dk:81/dir/foobar.php?f1=v1&f2=v2");
    }
}
