KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > joseki > server > FileManager


1 /*
2  * (c) Copyright 2003, 2004 Hewlett-Packard Development Company, LP
3  * [See end of file]
4  */

5
6 package org.joseki.server;
7
8 import java.io.* ;
9 import java.util.* ;
10 import org.apache.commons.logging.*;
11 import javax.servlet.* ;
12
13 import java.net.URL JavaDoc;
14 import java.net.MalformedURLException JavaDoc;
15
16 import com.hp.hpl.jena.rdf.model.* ;
17 import com.hp.hpl.jena.util.ModelLoader ;
18
19
20 /** <p>A class to encapsulate accessing a file, whether it is
21  * in the local file system (various places), in a JAR file or a URL.
22  * Places to look for a file with a relative path name are: the servlet context,
23  * webserver current directory.</p>
24  *
25  * <p>Error handling: on errors, a log message is written and nulls are returned</p>
26  *
27  * @author Andy Seaborne
28  * @version $Id: FileManager.java,v 1.10 2004/04/30 14:13:13 andy_seaborne Exp $
29  */

30  
31 public class FileManager
32 {
33     static Log logger = LogFactory.getLog(FileManager.class) ;
34
35     static FileManager instance = null ;
36
37     List handler = new ArrayList() ;
38     ServletContext servletContext = null ;
39
40     private FileManager()
41     {
42         handler.add(new FileLocator()) ;
43         handler.add(new ServletResourceLocator()) ;
44
45         handler.add(new ClassLoaderLocator(Thread.currentThread().getContextClassLoader())) ;
46         //handler.add(new ClassLoaderLocator(this.getClass().getClassLoader())) ;
47
handler.add(new ClassLoaderLocator(ClassLoader.getSystemClassLoader())) ;
48     }
49
50     /** Get the file manager.
51      * @return the file manager
52      */

53     public static FileManager getInstance()
54     {
55         // Sungleton pattern adopted in case we later have several file managers.
56
if ( instance == null )
57             instance = new FileManager() ;
58         return instance ;
59     }
60     
61     public void setServletContext(ServletContext _servletContext)
62     {
63         logger.trace("Setting servlet context") ;
64         servletContext = _servletContext ;
65     }
66     
67     /** Load a model from a file (local or remote).
68      * Guesses the syntax of the file based on filename extension,
69      * defaulting to RDF/XML.
70      * @param filenameOrURI The filename or a URI (file:, http:)
71      * @return a new model, or null on error.
72      */

73
74     public Model loadModel(String JavaDoc filenameOrURI)
75     { return loadModel(filenameOrURI, null) ; }
76
77     /** Load a model from a file (local or remote).
78      * Guesses the syntax of the file based on filename extension,
79      * defaulting to RDF/XML.
80      *
81      * @param filenameOrURI The filename or a URI (file:, http:)
82      * @param baseURI Base URI for loading the RDF model.
83      * @return a new model, or null on error.
84      */

85
86     public Model loadModel(String JavaDoc filenameOrURI, String JavaDoc baseURI)
87     {
88         Model m = ModelFactory.createDefaultModel() ;
89         return readModel(m, filenameOrURI, null) ;
90     }
91     
92     /**
93      * Read a file of RDF into a model.
94      * @param model
95      * @param filenameOrURI
96      * @return The model or null, if there was an error.
97      */

98
99     public Model readModel(Model model, String JavaDoc filenameOrURI)
100     { return readModel(model, filenameOrURI, null); }
101     
102     /**
103      * Read a file of RDF into a model.
104      * @param model
105      * @param filenameOrURI
106      * @param baseURI
107      * @return The model or null, if there was an error.
108      */

109
110     public Model readModel(Model model, String JavaDoc filenameOrURI, String JavaDoc baseURI)
111     
112     {
113         if ( baseURI == null )
114             baseURI = "" ;
115         
116         //String syntax = ModelLoader.guessLang(filenameOrURI, "RDF/XML") ;
117
String JavaDoc syntax = ModelLoader.guessLang(filenameOrURI) ;
118         if ( syntax == null || syntax.equals("") )
119             syntax = "RDF/XML" ;
120
121         InputStream in = open(filenameOrURI) ;
122         if ( in == null )
123         {
124             logger.debug("Failed to locate '"+filenameOrURI+"'") ;
125             return null ;
126         }
127         model.read(in,baseURI, syntax) ;
128         return model ;
129     }
130
131
132     public InputStream open(String JavaDoc filenameOrURI)
133     {
134         for ( Iterator iter = handler.iterator() ; iter.hasNext() ; )
135         {
136             Locator loc = (Locator)iter.next() ;
137             InputStream in = loc.open(filenameOrURI) ;
138             if ( in != null )
139                 return in ;
140         }
141         return null;
142     }
143  
144
145     private interface Locator
146     {
147         public InputStream open(String JavaDoc filenameOrURI) ;
148     }
149    
150     private class FileLocator implements Locator
151     {
152         FileLocator()
153         {
154             try {
155                 //String wd = System.getProperty("user.dir") ;
156
String JavaDoc wd = new File(".").getCanonicalPath() ;
157                 logger.info("Base directory: "+wd) ;
158             } catch (IOException ex)
159             {
160                 logger.error("Failed to discover the working directory", ex) ;
161             }
162         }
163         
164         public InputStream open(String JavaDoc filenameOrURI)
165         {
166             String JavaDoc fn = toFilename(filenameOrURI) ;
167             if ( fn == null )
168                 return null ;
169                          
170             File f = new File(fn) ;
171         
172             if ( !f.exists() )
173             {
174                 logger.trace("FileLocator: File not found: "+filenameOrURI) ;
175                 return null ;
176             }
177             
178             try {
179                 InputStream in = new FileInputStream(fn) ;
180                 if ( in == null )
181                 {
182                     // Should not happen
183
logger.trace("FileLocator: Failed to open: "+filenameOrURI) ;
184                     return null ;
185                 }
186                 
187                 logger.debug("Read as file: "+filenameOrURI) ;
188                 // Create base -- Java 1.4-isms
189
//base = f.toURI().toURL().toExternalForm() ;
190
//base = base.replaceFirst("^file:/([^/])", "file:///$1") ;
191
return in ;
192             } catch (IOException ioEx)
193             {
194                 // Includes FileNotFoundException
195
// We already tested whether the file exists or not.
196
logger.warn("File unreadable (but exists): "+fn+" Exception: "+ioEx.getMessage()) ;
197                 return null ;
198             }
199         }
200     }
201     
202     private class URLLocator implements Locator
203     {
204         public InputStream open(String JavaDoc filenameOrURI)
205         {
206             if (isFile(filenameOrURI))
207                 return null;
208             try
209             {
210                 URL JavaDoc url = new URL JavaDoc(filenameOrURI);
211                 InputStream in = new BufferedInputStream(url.openStream());
212                 if ( in == null )
213                 {
214                     logger.trace("URLLocator: not found: "+filenameOrURI) ;
215                     return null ;
216                 }
217                 
218                 logger.debug("Read as URL: " + filenameOrURI);
219                 return in;
220             }
221             catch (MalformedURLException JavaDoc ex)
222             {
223                 logger.warn("Malformed URL: " + filenameOrURI);
224                 return null;
225             }
226             catch (IOException ex)
227             {
228                 logger.warn("IO Exception opening URL: " + filenameOrURI);
229                 return null;
230             }
231         }
232     }
233     
234     
235     private class ServletResourceLocator implements Locator
236     {
237         public InputStream open(String JavaDoc filenameOrURI)
238         {
239             if ( servletContext == null)
240                 return null ;
241
242             String JavaDoc fn = toFilename(filenameOrURI) ;
243             if ( fn == null )
244             {
245                 logger.trace("ServletResourceLocator: failed to open: "+filenameOrURI) ;
246                 return null ;
247             }
248
249             InputStream in = servletContext.getResourceAsStream(fn);
250             //base = servletContext.getResource(fn).toExternalForm();
251
if (in != null)
252                 logger.debug("Reading as servlet resource: " + filenameOrURI);
253             return in ;
254         }
255     }
256     
257     private class ClassLoaderLocator implements Locator
258     {
259         ClassLoader JavaDoc classLoader = null ;
260         ClassLoaderLocator(ClassLoader JavaDoc _classLoader)
261         {
262             classLoader =_classLoader ;
263         }
264         
265         
266         public InputStream open(String JavaDoc filenameOrURI)
267         {
268             if ( classLoader == null )
269                 return null ;
270                 
271             String JavaDoc fn = toFilename(filenameOrURI) ;
272             if ( fn == null )
273                 return null ;
274
275             InputStream in = classLoader.getResourceAsStream(fn) ;
276             if ( in == null )
277             {
278                 logger.trace("ClassLoaderLocator: failed to open: "+filenameOrURI) ;
279             }
280             
281             // base = classLoader.getResource(fn).toExternalForm ;
282
logger.debug("Reading as resource: "+filenameOrURI) ;
283             return in ;
284         }
285     }
286     
287     private String JavaDoc toFilename(String JavaDoc filenameOrURI)
288     {
289         if ( !isFile(filenameOrURI) )
290             return null ;
291
292         String JavaDoc fn = filenameOrURI ;
293         if ( fn.startsWith("file:") )
294             fn = fn.substring("file:".length()) ;
295         return fn ;
296     }
297     
298     private boolean isFile(String JavaDoc name)
299     {
300         return name.startsWith("file:") || ! isURI(name) ;
301     }
302     
303     
304     private boolean isURI(String JavaDoc name)
305     {
306         if ( name.matches("[^/:]*:.*") )
307             return true ;
308         return false ;
309     }
310 }
311
312
313
314 /*
315  * (c) Copyright 2003, 2004 Hewlett-Packard Development Company, LP
316  * All rights reserved.
317  *
318  * Redistribution and use in source and binary forms, with or without
319  * modification, are permitted provided that the following conditions
320  * are met:
321  * 1. Redistributions of source code must retain the above copyright
322  * notice, this list of conditions and the following disclaimer.
323  * 2. Redistributions in binary form must reproduce the above copyright
324  * notice, this list of conditions and the following disclaimer in the
325  * documentation and/or other materials provided with the distribution.
326  * 3. The name of the author may not be used to endorse or promote products
327  * derived from this software without specific prior written permission.
328  *
329  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
330  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
331  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
332  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
333  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
334  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
335  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
336  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
337  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
338  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
339  */

340  
341
Popular Tags