// URLUtils.java
// $Id: URLUtils.java,v 1.5 2013/10/18 13:42:30 ylafon Exp $
// (c) COPYRIGHT ERCIM, Keio and MIT, 2003.
// Please first read the full copyright statement in file COPYRIGHT.html
package org.w3c.util;
import java.net.MalformedURLException;
import java.net.URL;
public class URLUtils {
/**
* Checks that the protocol://host:port part of two URLs are equal.
*
* @param u1, the first URL to check
* @param u2, the second URL to check
* @return a boolean, true if the protocol://host:port part of the URL
* are equals, false otherwise
*/
public static boolean equalsProtocolHostPort(URL u1, URL u2) {
if ((u1 == null) || (u2 == null)) {
return false;
}
// check that the protocol are the same (as it impacts the
// default port check
if (!u1.getProtocol().equalsIgnoreCase(u2.getProtocol())) {
return false;
}
// check that both hostnames are equal
if (!u1.getHost().equalsIgnoreCase(u2.getHost())) {
return false;
}
int u1p = u1.getPort();
int u2p = u2.getPort();
// if port is ok, it's good!
if (u1p == u2p) {
return true;
} else if ((u1p > 0) && (u2p > 0)) {
return false;
}
// otherwise, the painful comparison of -1 and such
if (u1p == -1) {
int u1dp = u1.getDefaultPort();
return (u2p == u1dp);
} else {
int u2dp = u2.getDefaultPort();
return (u2dp == u1p);
}
}
/**
* normalize an URL,
*
* @param u, the URL to normalize
* @return a new URL, the normalized version of the parameter, or
* the u URL, if something failed in the process
*/
public static URL normalize(URL u) {
String proto = u.getProtocol().toLowerCase();
String host = u.getHost().toLowerCase();
int port = u.getPort();
if (port != -1) {
int udp = u.getDefaultPort();
if (udp == port) {
port = -1;
}
}
try {
URL _nu;
if (port == -1) {
_nu = new URL(proto, host, u.getFile());
} else {
_nu = new URL(proto, host, port, u.getFile());
}
return _nu;
} catch (MalformedURLException ex) {
}
return u;
}
}
Webmaster