import java.net.*; import java.io.*; import java.util.*; /** * Provides a static method to convert a relative url * to an absolute url. But the algorithm is only * approximate, and not complete * * @author http://bumble.sf.net */ public class RelativeUrl extends Object { //-------------------------------------------- private static String NEWLINE = System.getProperty("line.separator"); //-------------------------------------------- private String text; //-------------------------------------------- public RelativeUrl() { this.text = ""; } //-------------------------------------------- public RelativeUrl(String sText) { this.text = sText; } //-------------------------------------------- /** resolve a relative url */ public static String resolve(String sBaseUrl, String sRelativeUrl) { URL urlTest; URL urlBase; String sHost = ""; String sBaseDirectory = ""; try { //-- if the relative url has a protocol then it is //-- not relative an nothing further should be done. //-- urlTest = new URL(sRelativeUrl); return sRelativeUrl; } catch (MalformedURLException e) {} try { //-- if the base url has no protocol then it is not //-- much good to us. urlBase = new URL(sBaseUrl); } catch (MalformedURLException e) { return sRelativeUrl; } sHost = urlBase.getProtocol() + "://" + urlBase.getHost(); sBaseDirectory = sBaseUrl.substring(0, sBaseUrl.lastIndexOf("/") + 1); if (sRelativeUrl.trim().startsWith("/")) { return sHost + sRelativeUrl.trim(); } else { return sBaseDirectory + sRelativeUrl.trim(); } //return sRelativeUrl; } //-- method: resolve //-------------------------------------------- /** a main method for testing */ public static void main(String[] args) throws Exception { StringBuffer sbUsageMessage = new StringBuffer(""); sbUsageMessage.append( "test usage: java RelativeUrl base-url relative-url"); sbUsageMessage.append(NEWLINE); StringBuffer sbMessage = new StringBuffer(""); if (args.length < 2) { System.out.println(sbUsageMessage); System.exit(-1); } String sBaseUrl = args[0]; String sRelativeUrl = args[1]; //System.out.print("Using >"); //System.out.println(sText); System.out.println(""); System.out.print(".resolve() >"); System.out.println(RelativeUrl.resolve(sBaseUrl, sRelativeUrl)); } //-- main() } //-- RelativeUrl class