KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > prefuse > util > io > IOLib


1 package prefuse.util.io;
2
3 import java.awt.Component JavaDoc;
4 import java.io.File JavaDoc;
5 import java.io.FileInputStream JavaDoc;
6 import java.io.IOException JavaDoc;
7 import java.io.InputStream JavaDoc;
8 import java.net.URL JavaDoc;
9 import java.util.logging.Logger JavaDoc;
10 import java.util.zip.GZIPInputStream JavaDoc;
11
12 import javax.swing.JFileChooser JavaDoc;
13
14 import prefuse.data.Graph;
15 import prefuse.data.Table;
16 import prefuse.data.io.CSVTableReader;
17 import prefuse.data.io.DelimitedTextTableReader;
18 import prefuse.data.io.GraphMLReader;
19 import prefuse.data.io.GraphReader;
20 import prefuse.data.io.TableReader;
21 import prefuse.data.io.TreeMLReader;
22 import prefuse.util.StringLib;
23 import prefuse.util.collections.ByteArrayList;
24
25 /**
26  * Library routines for input/output tasks.
27  *
28  * @author <a HREF="http://jheer.org">jeffrey heer</a>
29  */

30 public class IOLib {
31
32     private IOLib() {
33         // disallow instantiation
34
}
35     
36     /**
37      * Indicates if a given String is a URL string. Checks to see if the string
38      * begins with the "http:/", "ftp:/", or "file:/" protocol strings.
39      * @param s the string to check
40      * @return true if a url string matching the listed protocols,
41      * false otherwise
42      */

43     public static boolean isUrlString(String JavaDoc s) {
44         return s.startsWith("http:/") ||
45                s.startsWith("ftp:/") ||
46                s.startsWith("file:/");
47     }
48     
49     /**
50      * From a string description, attempt to generate a URL object. The string
51      * may point to an Internet location (e.g., http:// or ftp:// URL),
52      * a resource on the class path (resulting in a resource URL that points
53      * into the current classpath), or a file on the local filesystem
54      * (resulting in a file:// URL). The String will be checked in that order
55      * in an attempt to resolve it to a valid URL.
56      * @param location the location string for which to get a URL object
57      * @return a URL object, or null if the location string could not be
58      * resolved
59      */

60     public static URL JavaDoc urlFromString(String JavaDoc location) {
61         return urlFromString(location, null, true);
62     }
63     
64     /**
65      * From a string description, attempt to generate a URL object. The string
66      * may point to an Internet location (e.g., http:// or ftp:// URL),
67      * a resource on the class path (resulting in a resource URL that points
68      * into the current classpath), or, if the <code>includeFileSystem</code>
69      * flag is true, a file on the local filesystem
70      * (resulting in a file:// URL). The String will be checked in that order
71      * in an attempt to resolve it to a valid URL.
72      * @param location the location string for which to get a URL object
73      * @param referrer the class to check for classpath resource items, the
74      * location string will be resolved against the package/folder containing
75      * this class
76      * @param includeFileSystem indicates if the file system should be
77      * included in the search to resolve the location String
78      * @return a URL object, or null if the location string could not be
79      * resolved
80      */

81     public static URL JavaDoc urlFromString(String JavaDoc location, Class JavaDoc referrer,
82                                     boolean includeFileSystem)
83     {
84         URL JavaDoc url = null;
85         if ( isUrlString(location) ) {
86             // explicit URL string
87
try {
88                 url = new URL JavaDoc(location);
89             } catch ( Exception JavaDoc e ) {
90                 e.printStackTrace();
91             }
92         } else {
93             // attempt to get a URL pointing into the classpath
94
if ( referrer != null )
95                 url = referrer.getResource(location);
96             else
97                 url = IOLib.class.getResource(location);
98
99             if ( url == null && !location.startsWith("/") )
100                 url = IOLib.class.getResource("/"+location);
101             
102             if ( includeFileSystem && url == null ) {
103                 // if still not found, check the file system
104
if ( (new File JavaDoc(location)).exists() ) {
105                     try {
106                         url = new URL JavaDoc("file:///"+location);
107                     } catch ( Exception JavaDoc e ) {}
108                 }
109             }
110         }
111         return url;
112     }
113     
114     /**
115      * Get an input string corresponding to the given location string. The
116      * string will first be resolved to a URL and an input stream will be
117      * requested from the URL connection. If this fails, the location will
118      * be resolved against the file system. Also, if a gzip file is found,
119      * the input stream will also be wrapped by a GZipInputStream. If the
120      * location string can not be resolved, a null value is returned
121      * @param location the location string
122      * @return an InputStream for the resolved location string
123      * @throws IOException if an input/ouput error occurs
124      */

125     public static InputStream JavaDoc streamFromString(String JavaDoc location)
126         throws IOException JavaDoc
127     {
128         InputStream JavaDoc is = null;
129         
130         // try to get a working url from the string
131
URL JavaDoc url = urlFromString(location, null, false);
132         if ( url != null ) {
133             is = url.openStream();
134         } else {
135             // if that failed, try the file system
136
File JavaDoc f = new File JavaDoc(location);
137             if ( f.exists() )
138                 is = new FileInputStream JavaDoc(f);
139         }
140         
141         if ( is == null ) {
142             return null; // couldn't find it
143
} else if ( isGZipFile(location) ) {
144             return new GZIPInputStream JavaDoc(is);
145         } else {
146             return is;
147         }
148     }
149     
150     /**
151      * Returns the extension for a file or null if there is none
152      * @param f the input file
153      * @return the file extension, or null if none
154      */

155     public static String JavaDoc getExtension(File JavaDoc f) {
156         return (f != null ? getExtension(f.getName()) : null);
157     }
158     
159     /**
160      * Indicates if the given file ends with a file extension of
161      * ".gz" or ".Z", indicating a GZip file.
162      * @param file a String of the filename or URL of the file
163      * @return true if the extension is ".gz" or ".Z", false otherwise
164      */

165     public static boolean isGZipFile(String JavaDoc file) {
166         String JavaDoc ext = getExtension(file);
167         return "gz".equals(ext) || "z".equals(ext);
168     }
169     
170     /**
171      * Indicates if the given file ends with a file extension of
172      * ".zip", indicating a Zip file.
173      * @param file a String of the filename or URL of the file
174      * @return true if the extension is ".zip", false otherwise
175      */

176     public static boolean isZipFile(String JavaDoc file) {
177         return "zip".equals(getExtension(file));
178     }
179     
180     /**
181      * Returns the extension for a file or null if there is none
182      * @param filename the input filename
183      * @return the file extension, or null if none
184      */

185     public static String JavaDoc getExtension(String JavaDoc filename) {
186         int i = filename.lastIndexOf('.');
187         if ( i>0 && i<filename.length()-1 ) {
188             return filename.substring(i+1).toLowerCase();
189         } else {
190             return null;
191         }
192     }
193     
194     /**
195      * Reads an input stream into a list of byte values.
196      * @param is the input stream to read
197      * @return a ByteArrayList containing the contents of the input stream
198      * @throws IOException if an input/ouput error occurs
199      */

200     public static ByteArrayList readAsBytes(InputStream JavaDoc is) throws IOException JavaDoc {
201         ByteArrayList buf = new ByteArrayList();
202         byte[] b = new byte[8192];
203         int nread = -1;
204         while ( (nread=is.read(b)) >= 0 ) {
205             buf.add(b, 0, nread);
206         }
207         return buf;
208     }
209     
210     /**
211      * Reads an input stream into a single String result.
212      * @param is the input stream to read
213      * @return a String containing the contents of the input stream
214      * @throws IOException if an input/ouput error occurs
215      */

216     public static String JavaDoc readAsString(InputStream JavaDoc is) throws IOException JavaDoc {
217         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
218         byte[] b = new byte[8192];
219         int nread = -1;
220         while ( (nread=is.read(b)) >= 0 ) {
221             String JavaDoc s = new String JavaDoc(b, 0, nread);
222             buf.append(s);
223         }
224         return buf.toString();
225     }
226     
227     /**
228      * Reads data pulled from the given location string into a single String
229      * result. The method attempts to retrieve an InputStream using the
230      * {@link #streamFromString(String)} method, then read the input stream
231      * into a String result.
232      * @param location the location String
233      * @return a String with the requested data
234      * @throws IOException if an input/ouput error occurs
235      * @see #streamFromString(String)
236      */

237     public static String JavaDoc readAsString(String JavaDoc location) throws IOException JavaDoc {
238         return readAsString(streamFromString(location));
239     }
240     
241     // ------------------------------------------------------------------------
242

243     /**
244      * Present a file chooser dialog for loading a Table data set.
245      * @param c user interface component from which the request is being made
246      * @return a newly loaded Table, or null if not found or action canceled
247      */

248     public static Table getTableFile(Component JavaDoc c) {
249         JFileChooser JavaDoc jfc = new JFileChooser JavaDoc();
250         jfc.setDialogType(JFileChooser.OPEN_DIALOG);
251         jfc.setDialogTitle("Open Table File");
252         jfc.setAcceptAllFileFilterUsed(false);
253         
254         SimpleFileFilter ff;
255         
256         // TODO: have this generate automatically
257
// tie into PrefuseConfig??
258

259         // CSV
260
ff = new SimpleFileFilter("csv",
261                 "Comma Separated Values (CSV) File (*.csv)",
262                 new CSVTableReader());
263         ff.addExtension("gz");
264         jfc.setFileFilter(ff);
265
266         // Pipe-Delimited
267
ff = new SimpleFileFilter("txt",
268                 "Pipe-Delimited Text File (*.txt)",
269                 new DelimitedTextTableReader("|"));
270         ff.addExtension("gz");
271         jfc.setFileFilter(ff);
272
273         // Tab-Delimited
274
ff = new SimpleFileFilter("txt",
275                 "Tab-Delimited Text File (*.txt)",
276                 new DelimitedTextTableReader());
277         ff.addExtension("gz");
278         jfc.setFileFilter(ff);
279         
280         int retval = jfc.showOpenDialog(c);
281         if (retval != JFileChooser.APPROVE_OPTION)
282             return null;
283         
284         File JavaDoc f = jfc.getSelectedFile();
285         ff = (SimpleFileFilter)jfc.getFileFilter();
286         TableReader tr = (TableReader)ff.getUserData();
287         
288         try {
289             return tr.readTable(streamFromString(f.getAbsolutePath()));
290         } catch ( Exception JavaDoc e ) {
291             Logger.getLogger(IOLib.class.getName()).warning(
292                 e.getMessage() + "\n" + StringLib.getStackTrace(e));
293             return null;
294         }
295     }
296     
297     /**
298      * Present a file chooser dialog for loading a Graph or Tree data set.
299      * @param c user interface component from which the request is being made
300      * @return a newly loaded Graph, or null if not found or action canceled
301      */

302     public static Graph getGraphFile(Component JavaDoc c) {
303         JFileChooser JavaDoc jfc = new JFileChooser JavaDoc();
304         jfc.setDialogType(JFileChooser.OPEN_DIALOG);
305         jfc.setDialogTitle("Open Graph or Tree File");
306         jfc.setAcceptAllFileFilterUsed(false);
307         
308         SimpleFileFilter ff;
309         
310         // TODO: have this generate automatically
311
// tie into PrefuseConfig??
312

313         // TreeML
314
ff = new SimpleFileFilter("xml",
315                 "TreeML File (*.xml, *.treeml)",
316                 new TreeMLReader());
317         ff.addExtension("treeml");
318         ff.addExtension("gz");
319         jfc.setFileFilter(ff);
320         
321         // GraphML
322
ff = new SimpleFileFilter("xml",
323                 "GraphML File (*.xml, *.graphml)",
324                 new GraphMLReader());
325         ff.addExtension("graphml");
326         ff.addExtension("gz");
327         jfc.setFileFilter(ff);
328         
329         int retval = jfc.showOpenDialog(c);
330         if (retval != JFileChooser.APPROVE_OPTION)
331             return null;
332         
333         File JavaDoc f = jfc.getSelectedFile();
334         ff = (SimpleFileFilter)jfc.getFileFilter();
335         GraphReader gr = (GraphReader)ff.getUserData();
336         
337         try {
338             return gr.readGraph(streamFromString(f.getAbsolutePath()));
339         } catch ( Exception JavaDoc e ) {
340             Logger.getLogger(IOLib.class.getName()).warning(
341                 e.getMessage() + "\n" + StringLib.getStackTrace(e));
342             return null;
343         }
344     }
345     
346 } // end of class IOLib
347
Popular Tags