1 package org.sapia.resource; 2 3 import java.io.File ; 4 import java.io.FileInputStream ; 5 import java.io.IOException ; 6 import java.io.InputStream ; 7 import java.net.MalformedURLException ; 8 import java.net.URI ; 9 import java.net.URISyntaxException ; 10 11 18 public class FileResource implements Resource { 19 private File _file; 20 21 public FileResource(File f) { 22 _file = f; 23 } 24 25 public String getURI() { 26 try { 27 return _file.toURL().toExternalForm(); 28 } catch(MalformedURLException e) { 29 throw new IllegalStateException ("Could not create URL from resource: " 30 + _file.getAbsolutePath() + "; caught: " + e.getClass().getName() 31 + " - " + e.getMessage()); 32 } 33 } 34 35 public Resource getRelative(String uri) throws IOException { 36 try{ 37 if(Utils.hasScheme(uri)){ 38 URI u = new URI (uri); 39 if(Utils.isAbsolute(u)){ 40 throw new IOException ("URI is absolute: " + uri + "; must be relative"); 41 } 42 } 43 File relative; 44 if(_file != null){ 45 relative = new File (Utils.getRelativePath(_file.getAbsolutePath(), uri, true)); 46 if(!relative.exists()){ 47 relative = new File (uri); 48 } 49 } 50 else{ 51 relative = new File (uri); 52 } 53 return new FileResource(relative); 54 }catch(URISyntaxException e){ 55 throw new IOException (e.getMessage()); 56 } 57 } 58 59 public InputStream getInputStream() throws IOException { 60 return new FileInputStream (_file); 61 } 62 63 public long lastModified() { 64 return _file.lastModified(); 65 } 66 67 public String toString() { 68 return _file.getAbsolutePath(); 69 } 70 } 71 | Popular Tags |