* If the string is a properly formatted file URL, then the file * portion will be made canonical. * *
* If the string is an invalid URL then it will be converted into a * file URL. * * @param urlspec The string to construct a URL for. * @param relativePrefix The string to prepend to relative file * paths, or null to disable prepending. * @return A URL for the given string. * * @throws MalformedURLException Could not make a URL for the given string. */ public static URL toURL(String urlspec, final String relativePrefix) throws MalformedURLException { urlspec = urlspec.trim(); URL url; try { url = new URL(urlspec); if (url.getProtocol().equals("file")) { url = makeURLFromFilespec(url.getFile(), relativePrefix); } } catch (Exception e) { // make sure we have a absolute & canonical file url try { url = makeURLFromFilespec(urlspec, relativePrefix); } catch (IOException n) { // // jason: or should we rethrow e? // throw new MalformedURLException(n.toString()); } } return url; } public static URI toURI(String urispec, final String relativePrefix) throws URISyntaxException { urispec = urispec.trim(); URI uri; if( urispec.startsWith("file:") ) { uri = makeURIFromFilespec(urispec.substring(5), relativePrefix); } else { uri = new URI(urispec); } return uri; } /** A helper to make a URL from a filespec. */ private static URL makeURLFromFilespec(final String filespec, final String relativePrefix) throws IOException { // make sure the file is absolute & canonical file url File file = new File(decode(filespec)); // if we have a prefix and the file is not abs then prepend if (relativePrefix != null && !file.isAbsolute()) { file = new File(relativePrefix, filespec); } // make sure it is canonical (no ../ and such) file = file.getCanonicalFile(); return file.toURI().toURL(); } private static String decode(String filespec) { try { return URLDecoder.decode(filespec, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Error decoding filespec: " + filespec, e); } } private static URI makeURIFromFilespec(final String filespec, final String relativePrefix) { // make sure the file is absolute & canonical file url File file = new File(decode(filespec)); // if we have a prefix and the file is not abs then prepend if (relativePrefix != null && !file.isAbsolute()) { file = new File(relativePrefix, filespec); } return file.toURI(); } /** * Make a URL from the given string. * * @see #toURL(String,String) * * @param urlspec The string to construct a URL for. * @return A URL for the given string. * * @throws MalformedURLException Could not make a URL for the given string. */ public static URL toURL(final String urlspec) throws MalformedURLException { return toURL(urlspec, null); } /** * * @param urispec * @return the uri * @throws URISyntaxException for any error */ public static URI toURI(final String urispec) throws URISyntaxException { return toURI(urispec, null); } }