1 package org.sapia.resource; 2 3 import java.io.File ; 4 import java.io.FileNotFoundException ; 5 import java.io.IOException ; 6 import java.io.InputStream ; 7 import java.net.URI ; 8 import java.net.URISyntaxException ; 9 10 32 public class FileResourceHandler implements ResourceHandler, Schemes { 33 34 private boolean _fallBackToClasspath = true; 35 private String _basedir = System.getProperty("user.dir"); 36 37 public Resource getResourceObject(String uri) throws IOException { 38 String fileUri = mangleUri(uri); 39 File f = getFile(fileUri); 40 41 if(f.exists()){ 42 return new FileResource(f); 43 } else if (f.getAbsoluteFile().exists()) { 44 return new FileResource(f.getAbsoluteFile()); 45 } else if(_fallBackToClasspath) { 46 return new ClasspathResourceHandler().getResourceObject(uri); 47 } else { 48 throw new ResourceNotFoundException(uri); 49 } 50 } 51 52 57 public File getFile(String uri) throws IOException { 58 uri = mangleUri(uri); 59 return new File (uri); 60 } 61 62 public InputStream getResource(String uri) throws IOException { 63 String fileUri = mangleUri(uri); 64 File f = getFile(fileUri); 65 66 if(f.exists()) { 67 return f.toURL().openStream(); 68 } else if(_fallBackToClasspath) { 69 return new ClasspathResourceHandler().getResourceObject(uri) 70 .getInputStream(); 71 } 72 else{ 73 throw new FileNotFoundException (uri); 74 } 75 } 76 77 82 public void setFallBackToClasspath(boolean fallback) { 83 _fallBackToClasspath = fallback; 84 } 85 86 92 public void setBasedir(String basedir) { 93 _basedir = basedir; 94 } 95 96 public boolean accepts(String uri) { 97 return doAccepts(Utils.getScheme(uri)); 98 } 99 100 public boolean accepts(URI uri) { 101 return doAccepts(uri.getScheme()); 102 } 103 104 private boolean doAccepts(String scheme){ 105 if(scheme == null || scheme.length() == 0 || scheme.equals(SCHEME_FILE)) { 106 return true; 107 } 108 return false; 109 } 110 111 private String mangleUri(String uri) throws IOException { 112 URI u; 113 if(Utils.hasScheme(uri)){ 114 u = Utils.toURIObject(uri); 115 } 116 else{ 117 try{ 118 u = new URI (SCHEME_FILE+":"+uri); 119 }catch(URISyntaxException e){ 120 throw new IOException (e.getMessage()); 121 } 122 } 123 124 if((_basedir != null) && !Utils.isAbsolute(u)) { 125 return Utils.getRelativePath(_basedir, uri, false); 126 } else { 127 return Utils.chopScheme(uri); 128 } 129 } 130 } 131 | Popular Tags |