001 package com.thaiopensource.util; 002 003 import java.net.URL; 004 import java.net.MalformedURLException; 005 import java.io.File; 006 007 public class UriOrFile { 008 private UriOrFile() { 009 } 010 011 public static String toUri(String uriOrFile) { 012 if (!hasScheme(uriOrFile)) { 013 try { 014 return fileToUri(uriOrFile); 015 } 016 catch (MalformedURLException e) { } 017 } 018 return uriOrFile; 019 } 020 021 private static boolean hasScheme(String str) { 022 int len = str.length(); 023 if (len == 0) 024 return false; 025 if (!isAlpha(str.charAt(0))) 026 return false; 027 for (int i = 1; i < len; i++) { 028 char c = str.charAt(i); 029 switch (c) { 030 case ':': 031 // Don't recognize single letters as schemes 032 return i == 1 ? false : true; 033 case '+': 034 case '-': 035 break; 036 default: 037 if (!isAlnum(c)) 038 return false; 039 break; 040 } 041 } 042 return false; 043 } 044 045 private static boolean isAlpha(char c) { 046 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); 047 } 048 049 private static boolean isAlnum(char c) { 050 return isAlpha(c) || ('0' <= c && c <= '9'); 051 } 052 053 public static String fileToUri(String file) throws MalformedURLException { 054 return fileToUri(new File(file)); 055 } 056 057 public static String fileToUri(File file) throws MalformedURLException { 058 String path = file.getAbsolutePath().replace(File.separatorChar, '/'); 059 if (path.length() > 0 && path.charAt(0) != '/') 060 path = '/' + path; 061 return new URL("file", "", path).toString(); 062 } 063 064 public static String uriToUriOrFile(String uri) { 065 if (!uri.startsWith("file:")) 066 return uri; 067 uri = uri.substring(5); 068 int nSlashes = 0; 069 while (nSlashes < uri.length() && uri.charAt(nSlashes) == '/') 070 nSlashes++; 071 File f = new File(uri.substring(nSlashes).replace('/', File.separatorChar)); 072 if (f.isAbsolute()) 073 return f.toString(); 074 return uri.replace('/', File.separatorChar); 075 } 076 077 static public void main(String[] args) { 078 System.err.println(uriToUriOrFile(args[0])); 079 } 080 }