package net.sourceforge.stripes.util; import java.net.MalformedURLException; import java.net.URL; /** * UrlParser * * @author Christian Schwanke */ public class UrlParser { private static final String JSESSIONID_NAME = ";jsessionid"; /** * Parses the given url into a HttpUrlInfo instance * * @param urlValue * The url to parse * @return a HttpUrlInfo instance containing the various parts of the url * @throws MalformedURLException * If the given string cannot be parsed */ public static HttpUrlInfo parseUrl(String urlValue) throws MalformedURLException { HttpUrlInfo urlInfo = new HttpUrlInfo(); if (urlValue != null) { URL url = null; if (urlValue.startsWith("http")) { url = new URL(urlValue); urlInfo.setProtocol(url.getProtocol()); urlInfo.setHost(url.getHost()); urlInfo.setPort(url.getPort()); } else { url = new URL("http://dummy" + urlValue); } urlInfo.setQuery(url.getQuery()); urlInfo.setRef(url.getRef()); urlInfo.setPath(removeSession(url.getPath())); urlInfo.setSession(extractSession(url.getPath())); } return urlInfo; } /** * Extracts the jsessionid from the given url without the leading ; * character * * @param url * The url to work with * @return The jsessionid found in the url or null if no jsessionid is * present */ public static String extractSession(String url) { if (url != null && url.contains(JSESSIONID_NAME)) { int end = url.length(); if (url.contains("?")) { end = url.indexOf("?"); } else if (url.contains("#")) { end = url.indexOf("#"); } return url.substring(url.indexOf(JSESSIONID_NAME) + 1, end); } return null; } /** * Strips an existing jsession part from the given URL. If no sessionid is * present, the url is returned unchanged * * @param url * The url to manipulate * @return The given url without the jsessionid */ public static String removeSession(String url) { if (url != null && url.contains(JSESSIONID_NAME)) { int end = url.length(); if (url.contains("?")) { end = url.indexOf("?"); } else if (url.contains("#")) { end = url.indexOf("#"); } String endPart = url.substring(end + 1); return url.substring(0, url.indexOf(JSESSIONID_NAME)) + endPart; } return url; } }