KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > util > FileUtils


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

5
6 package com.hp.hpl.jena.util;
7
8 import java.io.*;
9
10 import java.net.URL JavaDoc;
11 import java.nio.charset.Charset JavaDoc ;
12
13 import com.hp.hpl.jena.shared.JenaException;
14 import com.hp.hpl.jena.shared.WrappedIOException;
15 import com.hp.hpl.jena.JenaRuntime ;
16
17 public class FileUtils
18 {
19     public static final String JavaDoc langXML = "RDF/XML" ;
20     public static final String JavaDoc langXMLAbbrev = "RDF/XML-ABBREV" ;
21     public static final String JavaDoc langNTriple = "N-TRIPLE" ;
22     public static final String JavaDoc langN3 = "N3" ;
23     public static final String JavaDoc langTurtle = "TURTLE" ;
24     // Non-standard
25
public static final String JavaDoc langBDB = "RDF/BDB" ;
26     public static final String JavaDoc langSQL = "RDF/SQL" ;
27     
28     static Charset JavaDoc utf8 = null ;
29     static {
30         try {
31             utf8 = Charset.forName("utf-8") ;
32         } catch (Throwable JavaDoc ex) {}
33     }
34     
35     
36     /** Create a reader that uses UTF-8 encoding */
37     
38     static public Reader asUTF8(InputStream in) {
39         if ( JenaRuntime.runUnder(JenaRuntime.featureNoCharset) )
40             return new InputStreamReader(in) ;
41         return new InputStreamReader(in, utf8);
42     }
43
44     /** Create a buffered reader that uses UTF-8 encoding */
45     
46     static public BufferedReader asBufferedUTF8(InputStream in) {
47         return new BufferedReader(asUTF8(in)) ;
48     }
49
50     /** Create a writer that uses UTF-8 encoding */
51
52     static public Writer asUTF8(OutputStream out) {
53         if ( JenaRuntime.runUnder(JenaRuntime.featureNoCharset) )
54             return new OutputStreamWriter(out) ;
55         return new OutputStreamWriter(out, utf8);
56     }
57
58     /** Create a print writer that uses UTF-8 encoding */
59
60     static public PrintWriter asPrintWriterUTF8(OutputStream out) {
61         return new PrintWriter(asUTF8(out));
62     }
63     
64     /** Guess the language/type of model data. Updated by Chris, hived off the
65      * model-suffix part to FileUtils as part of unifying it with similar code in FileGraph.
66      *
67      * <ul>
68      * <li> If the URI of the model starts jdbc: it is assumed to be an RDB model</li>
69      * <li> If the URI ends ".rdf", it is assumed to be RDF/XML</li>
70      * <li> If the URI end .nt, it is assumed to be N-Triples</li>
71      * <li> If the URI end .bdb, it is assumed to be BerkeleyDB model [suppressed at present]</li>
72      * </ul>
73      * @param name URL to base the guess on
74      * @param otherwise Default guess
75      * @return String Guessed syntax - or the default supplied
76      */

77
78     public static String JavaDoc guessLang( String JavaDoc name, String JavaDoc otherwise )
79     {
80         if ( name.startsWith("jdbc:") || name.startsWith("JDBC:") )
81             return langSQL ;
82         
83         String JavaDoc suffix = getFilenameExt( name );
84         if (suffix.equals( "n3" )) return langN3;
85         if (suffix.equals( "nt" )) return langNTriple;
86         if (suffix.equals( "ttl" )) return langTurtle ;
87         if (suffix.equals( "rdf" )) return langXML;
88         if (suffix.equals( "owl" )) return langXML;
89         return otherwise;
90     }
91    
92    
93     /** Guess the language/type of model data
94      *
95      * <ul>
96      * <li> If the URI of the model starts jdbc: it is assumed to be an RDB model</li>
97      * <li> If the URI ends .rdf, it is assumed to be RDF/XML</li>
98      * <li> If the URI ends .n3, it is assumed to be N3</li>
99      * <li> If the URI ends .nt, it is assumed to be N-Triples</li>
100      * <li> If the URI ends .bdb, it is assumed to be BerkeleyDB model</li>
101      * </ul>
102      * @param urlStr URL to base the guess on
103      * @return String Guessed syntax - default is RDF/XML
104      */

105
106     public static String JavaDoc guessLang(String JavaDoc urlStr)
107     {
108         return guessLang(urlStr, langXML) ;
109     }
110
111     /** Turn a file: URL or file name into a plain file name */
112     
113     public static String JavaDoc toFilename(String JavaDoc filenameOrURI)
114     {
115         if ( !isFile(filenameOrURI) )
116             return null ;
117
118         String JavaDoc fn = filenameOrURI ;
119         if ( fn.startsWith("file://localhost/") )
120             // NB Leaves the leading slash on.
121
return fn.substring("file://localhost".length()) ;
122             
123         if ( fn.startsWith("file:") )
124             return fn.substring("file:".length()) ;
125         
126         return fn ;
127     }
128     
129     /** Check whether 'name' is possibly a file reference
130      *
131      * @param name
132      * @return boolean False if clearly not a filename.
133      */

134     public static boolean isFile(String JavaDoc name)
135     {
136         String JavaDoc scheme = getScheme(name) ;
137         
138         if ( scheme == null )
139             // No URI scheme - treat as filename
140
return true ;
141         
142         if ( scheme.equals("file") )
143             // file: URI scheme
144
return true ;
145             
146         // Windows: "c:" etc
147
if ( scheme.length() == 1 )
148             // file: URI scheme
149
return true ;
150         
151         return false ;
152
153         //return name.startsWith("file:") || ! isURI(name) ;
154
}
155     
156     /** Check whether a name is an absolute URI (has a scheme name)
157      *
158      * @param name
159      * @return boolean True if there is a scheme name
160      */

161     public static boolean isURI(String JavaDoc name)
162     {
163         // Java 1.4+
164
// if ( name.matches("[^/:]*:.*") )
165
// return true ;
166

167         return (getScheme(name) != null) ;
168     }
169
170     public static String JavaDoc getScheme(String JavaDoc uri)
171     {
172         // Nicer in Java 1.4
173
for ( int i = 0 ; i < uri.length() ; i++ )
174         {
175             char ch = uri.charAt(i) ;
176             if ( ch == ':' )
177                 return uri.substring(0,i) ;
178             if ( ! isASCIILetter(ch) )
179                 // Some illegal character before the ':'
180
break ;
181         }
182         return null ;
183     }
184     
185     private static boolean isASCIILetter(char ch)
186     {
187         return ( ch >= 'a' && ch <= 'z' ) || ( ch >= 'A' && ch <= 'Z' ) ;
188     }
189     
190     /**
191      * Get the directory part of a filename
192      * @param filename
193      * @return Directory name
194      */

195     public static String JavaDoc getDirname(String JavaDoc filename)
196     {
197         File f = new File(filename) ;
198         return f.getParent() ;
199     }
200
201     /** Get the basename of a filename
202      *
203      * @param filename
204      * @return Base filename.
205      */

206     public static String JavaDoc getBasename(String JavaDoc filename)
207     {
208         File f = new File(filename) ;
209         return f.getName() ;
210     }
211
212     /**
213      Get the suffix part of a file name or a URL in file-like format.
214      */

215     public static String JavaDoc getFilenameExt( String JavaDoc filename)
216     {
217         int iSlash = filename.lastIndexOf( '/' );
218         int iBack = filename.lastIndexOf( '\\' );
219         int iExt = filename.lastIndexOf( '.' );
220         if (iBack > iSlash) iSlash = iBack;
221         return iExt > iSlash ? filename.substring( iExt+1 ).toLowerCase() : "";
222     }
223
224     /**
225      create a temporary file that will be deleted on exit, and do something
226      sensible with any IO exceptions - namely, throw them up wrapped in
227      a JenaException.
228      
229      @param prefix the prefix for File.createTempFile
230      @param suffix the suffix for File.createTempFile
231      @return the temporary File
232      */

233     public static File tempFileName( String JavaDoc prefix, String JavaDoc suffix )
234     {
235         File result = new File( getTempDirectory(), prefix + randomNumber() + suffix );
236         if (result.exists()) return tempFileName( prefix, suffix );
237         result.deleteOnExit();
238         return result;
239     }
240     
241     /**
242      Answer a File naming a freshly-created directory in the temporary directory. This
243      directory should be deleted on exit.
244      TODO handle threading issues, mkdir failure, and better cleanup
245      
246      @param prefix the prefix for the directory name
247      @return a File naming the new directory
248      */

249     public static File getScratchDirectory( String JavaDoc prefix )
250     {
251         File result = new File( getTempDirectory(), prefix + randomNumber() );
252         if (result.exists()) return getScratchDirectory( prefix );
253         if (result.mkdir() == false) throw new JenaException( "mkdir failed on " + result );
254         result.deleteOnExit();
255         return result;
256     }
257     
258     public static String JavaDoc getTempDirectory()
259     { return System.getProperty( "java.io.tmpdir" ); }
260
261     private static int counter = 0;
262     
263     private static int randomNumber()
264     {
265         return ++counter;
266     }
267
268     // TODO Replace with a FileManager
269
/**
270      Answer a BufferedReader than reads from the named resource file as
271      UTF-8, possibly throwing WrappedIOExceptions.
272      */

273     public static BufferedReader openResourceFile( String JavaDoc filename )
274     {
275         try
276         {
277             InputStream is = FileUtils.openResourceFileAsStream( filename );
278             return new BufferedReader(new InputStreamReader(is, "UTF-8"));
279         }
280         catch (IOException e)
281         { throw new WrappedIOException( e ); }
282     }
283     
284     /**
285      * Open an resource file for reading.
286      */

287     public static InputStream openResourceFileAsStream(String JavaDoc filename)
288     throws FileNotFoundException {
289         InputStream is = ClassLoader.getSystemResourceAsStream(filename);
290         if (is == null) {
291             // Try local loader with absolute path
292
is = FileUtils.class.getResourceAsStream("/" + filename);
293             if (is == null) {
294                 // Can't find it on classpath, so try relative to current directory
295
is = new FileInputStream(filename);
296             }
297         }
298         return is;
299     }
300
301     // TODO Replace with FileManager
302
public static BufferedReader readerFromURL( String JavaDoc urlStr )
303     {
304         try { return asBufferedUTF8( new URL JavaDoc(urlStr).openStream() ); }
305         catch (java.net.MalformedURLException JavaDoc e)
306         { // Try as a plain filename.
307
try { return asBufferedUTF8( new FileInputStream( urlStr ) ); }
308             catch (FileNotFoundException f) { throw new WrappedIOException( f ); }
309         }
310         catch (IOException e)
311         { throw new WrappedIOException( e ); }
312     }
313
314     /** Read a whole file as UTF-8
315      * @param filename
316      * @return String
317      * @throws IOException
318      */

319     
320     public static String JavaDoc readWholeFileAsUTF8(String JavaDoc filename) throws IOException {
321         InputStream in = new FileInputStream(filename) ;
322         return readWholeFileAsUTF8(in) ;
323     }
324
325     /** Read a whole stream as UTF-8
326      *
327      * @param in InputStream to be read
328      * @return String
329      * @throws IOException
330      */

331     public static String JavaDoc readWholeFileAsUTF8(InputStream in) throws IOException
332     {
333         Reader r = new BufferedReader(asUTF8(in),1024) ;
334         return readWholeFileAsUTF8(r) ;
335     }
336     
337     /** Read a whole file as UTF-8
338      *
339      * @param r
340      * @return String The whole file
341      * @throws IOException
342      */

343     
344     // Private worker as we are trying to force UTF-8.
345
private static String JavaDoc readWholeFileAsUTF8(Reader r) throws IOException
346     {
347         StringWriter sw = new StringWriter(1024);
348         char buff[] = new char[1024];
349         while (r.ready()) {
350             int l = r.read(buff);
351             if (l <= 0)
352                 break;
353             sw.write(buff, 0, l);
354         }
355         r.close();
356         sw.close();
357         return sw.toString();
358     }
359
360 }
361
362 /*
363  * (c) Copyright 2002, 2003, 2004, 2005 Hewlett-Packard Development Company, LP
364  * All rights reserved.
365  *
366  * Redistribution and use in source and binary forms, with or without
367  * modification, are permitted provided that the following conditions
368  * are met:
369  * 1. Redistributions of source code must retain the above copyright
370  * notice, this list of conditions and the following disclaimer.
371  * 2. Redistributions in binary form must reproduce the above copyright
372  * notice, this list of conditions and the following disclaimer in the
373  * documentation and/or other materials provided with the distribution.
374  * 3. The name of the author may not be used to endorse or promote products
375  * derived from this software without specific prior written permission.
376  *
377  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
378  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
379  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
380  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
381  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
382  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
383  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
384  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
385  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
386  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
387  */

388
Popular Tags