KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejen > ext > FileUtil


1 //
2
// Ejen (code generation system)
3
// Copyright (C) 2001, 2002 François Wolff (ejen@noos.fr).
4
//
5
// This file is part of Ejen.
6
//
7
// Ejen is free software; you can redistribute it and/or modify
8
// it under the terms of the GNU General Public License as published by
9
// the Free Software Foundation; either version 2 of the License, or
10
// (at your option) any later version.
11
//
12
// Ejen is distributed in the hope that it will be useful,
13
// but WITHOUT ANY WARRANTY; without even the implied warranty of
14
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
// GNU General Public License for more details.
16
//
17
// You should have received a copy of the GNU General Public License
18
// along with Ejen; if not, write to the Free Software
19
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
//
21
package org.ejen.ext;
22
23 import org.ejen.util.XSLUtil;
24 import org.ejen.util.DOMUtil;
25 import java.io.File JavaDoc;
26 import java.io.FileFilter JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.net.MalformedURLException JavaDoc;
29 import org.w3c.dom.Document JavaDoc;
30 import org.w3c.dom.Element JavaDoc;
31 import org.apache.regexp.RE;
32 import org.apache.xpath.NodeSet;
33 import org.apache.xml.utils.WrappedRuntimeException;
34 import org.apache.xalan.extensions.ExpressionContext;
35
36 /**
37  * File utility (static methods).
38  * <p>
39  * <table class="usage">
40  * <tr><th class="usage">Usage (XSL stylesheet)</th></tr>
41  * <tr><td class="usage"><pre>
42  *
43  * &lt;?xml version="1.0" encoding="iso-8859-1"?&gt;
44  *
45  * &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
46  * ...
47  * <b>xmlns:fiu="org.ejen.ext.FileUtil"
48  * exclude-result-prefixes="fiu ..."</b>
49  * version="1.0"&gt;
50  *
51  * &lt;xsl:output method="xml" encoding="iso-8859-1"/&gt;
52  *
53  * &lt;xsl:template match="ejen"&gt;
54  *
55  * &lt;xsl:copy-of select="fiu:{@link #properties(ExpressionContext,String) properties}($file-name)"/&gt;
56  *
57  * &lt;xsl:copy-of select="fiu:{@link #listFiles(ExpressionContext,String) listFiles}('../../src')"/&gt;
58  * &lt;xsl:copy-of select="fiu:{@link #listFiles(ExpressionContext,String,String) listFiles}('../../src','\.java$|\.jjt$')"/&gt;
59  * &lt;xsl:copy-of select="fiu:{@link #listFiles(ExpressionContext,String,String,boolean) listFiles}('../../src','\.java$|\.jjt$',true())"/&gt;
60  *
61  * &lt;/xsl:template&gt;
62  *
63  * &lt;/xsl:stylesheet&gt;
64  * </pre></td></tr></table>
65  * @author F. Wolff
66  * @version 1.0
67  */

68 public class FileUtil {
69     public static final String JavaDoc S_TRUE = "true";
70     public static final String JavaDoc S_FALSE = "false";
71
72     /**
73      * Protected constructor (prevents instanciation).
74      */

75     protected FileUtil() {}
76
77     /**
78      * Returns a NodeSet that contains informations about the fileName file.
79      * <p>
80      * <table class="usage"><tr><td class="usage"><pre>
81      *
82      * &lt;xsl:value-of select="fiu:properties('$file-name')"/&gt;
83      * </pre></td></tr></table>
84      * <p>
85      * The returned NodeSet will have the following structure:
86      * <p>
87      * <table class="usage"><tr><td class="usage"><pre>
88      *
89      * &lt;raw&gt;&lt;![CDATA[../../ejb-1.1/bmp-jboss-hsqldb/out/test/src/org/ejb/test/EJB_DOUBLE_UNIQUE_PK.java]]&gt;&lt;/raw&gt;
90      * &lt;name&gt;&lt;![CDATA[EJB_DOUBLE_UNIQUE_PK.java]]&gt;&lt;/name&gt;
91      * &lt;name-no-ext&gt;&lt;![CDATA[EJB_DOUBLE_UNIQUE_PK]]&gt;&lt;/name-no-ext&gt;
92      * &lt;parent&gt;&lt;![CDATA[../../ejb-1.1/bmp-jboss-hsqldb/out/test/src/org/ejb/test]]&gt;&lt;/parent&gt;
93      * &lt;path&gt;&lt;![CDATA[../../ejb-1.1/bmp-jboss-hsqldb/out/test/src/org/ejb/test/EJB_DOUBLE_UNIQUE_PK.java]]&gt;&lt;/path&gt;
94      * &lt;is-absolute&gt;&lt;![CDATA[false]]&gt;&lt;/is-absolute&gt;
95      * &lt;absolute-path&gt;&lt;![CDATA[/devs/java/ejen-1.0-pre2/examples/simples/file/../../ejb-1.1/bmp-jboss-hsqldb/out/test/src/org/ejb/test/EJB_DOUBLE_UNIQUE_PK.java]]&gt;&lt;/absolute-path&gt;
96      * &lt;canonical-path&gt;&lt;![CDATA[/devs/java/ejen-1.0-pre2/examples/ejb-1.1/bmp-jboss-hsqldb/out/test/src/org/ejb/test/EJB_DOUBLE_UNIQUE_PK.java]]&gt;&lt;/canonical-path&gt;
97      * &lt;url&gt;&lt;![CDATA[file:/devs/java/ejen-1.0-pre2/examples/simples/file/../../ejb-1.1/bmp-jboss-hsqldb/out/test/src/org/ejb/test/EJB_DOUBLE_UNIQUE_PK.java]]&gt;&lt;/url&gt;
98      * &lt;can-read&gt;&lt;![CDATA[true]]&gt;&lt;/can-read&gt;
99      * &lt;can-write&gt;&lt;![CDATA[true]]&gt;&lt;/can-write&gt;
100      * &lt;exists&gt;&lt;![CDATA[true]]&gt;&lt;/exists&gt;
101      * &lt;is-directory&gt;&lt;![CDATA[false]]&gt;&lt;/is-directory&gt;
102      * &lt;is-hidden&gt;&lt;![CDATA[false]]&gt;&lt;/is-hidden&gt;
103      * &lt;last-modified&gt;&lt;![CDATA[1016763382000]]&gt;&lt;/last-modified&gt;
104      * &lt;length&gt;&lt;![CDATA[2380]]&gt;&lt;/length&gt;
105      * </pre></td></tr></table>
106      * <p>
107      * "raw" node contains simply the fileName parameter value. Some of those Nodes may
108      * not be available (MalformedURLException [url], IOException [canonical-path],
109      * or SecurityException [can-read, can-write, ..., length]).
110      * <p>
111      * See {@link java.io.File}.
112      * <p>
113      * <dd><dl><dt><b>XSLT parameters:</b>
114      * <dd><b>[Mandatory/AVT]</b> name of the file.
115      * </dl></dd>
116      * <p>
117      * @param context automatically passed by the xalan extension mechanism.
118      * @param fileName name of the file.
119      * @return file properties.
120      * @throws org.apache.xml.utils.WrappedRuntimeException DOM error.
121      */

122     public static NodeSet properties(ExpressionContext context, String JavaDoc fileName) {
123         fileName = XSLUtil.evaluate(context, fileName);
124         Document JavaDoc doc = XSLUtil.getContextDocument(context);
125
126         try {
127             File JavaDoc f = new File JavaDoc(fileName);
128             NodeSet ns = new NodeSet();
129
130             ns.addElement(DOMUtil.createCDATANode(doc, "raw", fileName));
131             String JavaDoc s = f.getName();
132
133             ns.addElement(DOMUtil.createCDATANode(doc, "name", s));
134             int i = s.indexOf('.');
135
136             ns.addElement(DOMUtil.createCDATANode(doc, "name-no-ext",
137                     ((i != -1) ? s.substring(0, i) : s)));
138             s = f.getParent();
139             ns.addElement(DOMUtil.createCDATANode(doc, "parent",
140                     ((s != null) ? s : "")));
141             ns.addElement(DOMUtil.createCDATANode(doc, "path", f.getPath()));
142             ns.addElement(DOMUtil.createCDATANode(doc, "is-absolute",
143                     (f.isAbsolute() ? S_TRUE : S_FALSE)));
144             ns.addElement(DOMUtil.createCDATANode(doc, "absolute-path",
145                     f.getAbsolutePath()));
146             try {
147                 ns.addElement(DOMUtil.createCDATANode(doc, "canonical-path",
148                         f.getCanonicalPath()));
149             } catch (IOException JavaDoc e) {}
150             try {
151                 ns.addElement(DOMUtil.createCDATANode(doc, "url",
152                         f.toURL().toString()));
153             } catch (MalformedURLException JavaDoc e) {}
154             try {
155                 ns.addElement(DOMUtil.createCDATANode(doc, "can-read",
156                         (f.canRead() ? S_TRUE : S_FALSE)));
157             } catch (SecurityException JavaDoc e) {}
158             try {
159                 ns.addElement(DOMUtil.createCDATANode(doc, "can-write",
160                         (f.canWrite() ? S_TRUE : S_FALSE)));
161             } catch (SecurityException JavaDoc e) {}
162             try {
163                 ns.addElement(DOMUtil.createCDATANode(doc, "exists",
164                         (f.exists() ? S_TRUE : S_FALSE)));
165             } catch (SecurityException JavaDoc e) {}
166             try {
167                 ns.addElement(DOMUtil.createCDATANode(doc, "is-directory",
168                         (f.isDirectory() ? S_TRUE : S_FALSE)));
169             } catch (SecurityException JavaDoc e) {}
170             try {
171                 ns.addElement(DOMUtil.createCDATANode(doc, "is-hidden",
172                         (f.isHidden() ? S_TRUE : S_FALSE)));
173             } catch (SecurityException JavaDoc e) {}
174             try {
175                 ns.addElement(DOMUtil.createCDATANode(doc, "last-modified",
176                         Long.toString(f.lastModified())));
177             } catch (SecurityException JavaDoc e) {}
178             try {
179                 ns.addElement(DOMUtil.createCDATANode(doc, "length",
180                         Long.toString(f.length())));
181             } catch (SecurityException JavaDoc e) {}
182             
183             return ns;
184         } catch (WrappedRuntimeException e) {
185             throw e;
186         } catch (Exception JavaDoc e) {
187             throw new WrappedRuntimeException(e);
188         }
189     }
190     
191     /**
192      * Returns a NodeSet that contains files list for a given directory.
193      * <p>
194      * This method does not filter anything but directories (only regular file
195      * names are returned) and is not recursive (only file names in the given
196      * directory are listed).
197      * <p>
198      * <table class="usage"><tr><td class="usage"><pre>
199      *
200      * &lt;xsl:value-of select="fiu:listFiles('../../src/org/ejen/ext')"/&gt;
201      * </pre></td></tr></table>
202      * <p>
203      * The returned NodeSet will have the following structure:
204      * <p>
205      * <table class="usage"><tr><td class="usage"><pre>
206      *
207      * &lt;file&gt;
208      * &lt;path&gt;&lt;![CDATA[/devs/java/ejen-1.0-pre3/src/org/ejen/ext]]&gt;&lt;/path&gt;
209      * &lt;sep&gt;&lt;![CDATA[/]]&gt;&lt;/sep&gt;
210      * &lt;name&gt;&lt;![CDATA[XMLInclude.java]]&gt;&lt;/name&gt;
211      * &lt;/file&gt;
212      * &lt;file&gt;
213      * &lt;path&gt;&lt;![CDATA[/devs/java/ejen-1.0-pre3/src/org/ejen/ext]]&gt;&lt;/path&gt;
214      * &lt;sep&gt;&lt;![CDATA[/]]&gt;&lt;/sep&gt;
215      * &lt;name&gt;&lt;![CDATA[FileUtil.java]]&gt;&lt;/name&gt;
216      * &lt;/file&gt;
217      * ...
218      * </pre></td></tr></table>
219      * <p>
220      * "path" Nodes contain "canonical" paths (absolute, without symbolic
221      * links, etc.). Because this method is not recursive, "path" Nodes will
222      * be always equal to the canonical representation of the "path" argument.
223      * <p>
224      * <dd><dl><dt><b>XSLT parameters:</b>
225      * <dd><b>[Mandatory/AVT]</b> directory path.
226      * </dl></dd>
227      * <p>
228      * @param context automatically passed by the xalan extension mechanism.
229      * @param path directory path.
230      * @return a NodeSet that contains "file" Nodes.
231      * @throws org.apache.xml.utils.WrappedRuntimeException DOM or IO errors...
232      */

233     public static NodeSet listFiles(ExpressionContext context, String JavaDoc path) {
234         return listFiles(context, path, null, false);
235     }
236     
237     /**
238      * Returns a NodeSet that contains a filtered files list for a given directory.
239      * <p>
240      * This method is not recursive (only file names in the given
241      * directory are listed). The "filter" argument must be a regular expression
242      * (see {@link org.apache.regexp.RE}) and only refers to regular file names (neither
243      * directory names nor full path file names).
244      * <p>
245      * Tips: "<code>\.java$</code>" means "accept file names that end with
246      * '<code>.java</code>'". "<code>\.java$|\.jjt$</code>" means "accept file names
247      * that end with '<code>.java</code>' or '<code>.jjt</code>'".
248      * <p>
249      * <table class="usage"><tr><td class="usage"><pre>
250      *
251      * &lt;xsl:value-of select="fiu:listFiles('../../src','\.java$|\.jjt$')"/&gt;
252      * </pre></td></tr></table>
253      * <p>
254      * See {@link #listFiles(ExpressionContext, String)}.
255      * <p>
256      * <dd><dl><dt><b>XSLT parameters:</b>
257      * <dd><b>[Mandatory/AVT]</b> directory path.
258      * <dd><b>[Mandatory/AVT]</b> file name filter.
259      * </dl></dd>
260      * <p>
261      * @param context automatically passed by the xalan extension mechanism.
262      * @param path directory path.
263      * @param filter file name filter.
264      * @return a NodeSet that contains "file" Nodes.
265      * @throws org.apache.xml.utils.WrappedRuntimeException DOM or IO errors...
266      */

267     public static NodeSet listFiles(ExpressionContext context, String JavaDoc path,
268             String JavaDoc filter) {
269         return listFiles(context, path, filter, false);
270     }
271     
272     /**
273      * Returns a NodeSet that contains a filtered files list for a given directory
274      * and (optionally) for its sub-directories.
275      * <p>
276      * This method is recursive if the "rec" argument is true. The "filter" argument must
277      * be a regular expression (see {@link #listFiles(ExpressionContext, String,String)}).
278      * <p>
279      * <table class="usage"><tr><td class="usage"><pre>
280      *
281      * &lt;xsl:value-of select="fiu:listFiles('../../src','\.java$|\.jjt$',true())"/&gt;
282      * </pre></td></tr></table>
283      * <p>
284      * <dd><dl><dt><b>XSLT parameters:</b>
285      * <dd><b>[Mandatory/AVT]</b> directory path.
286      * <dd><b>[Mandatory/AVT]</b> file name filter.
287      * <dd><b>[Mandatory]</b> true() or false(): list recursively or not.
288      * </dl></dd>
289      * <p>
290      * @param context automatically passed by the xalan extension mechanism.
291      * @param path directory path.
292      * @param filter file name filter.
293      * @param rec true (recursive) or false.
294      * @return a NodeSet that contains "file" Nodes.
295      * @throws org.apache.xml.utils.WrappedRuntimeException DOM or IO errors...
296      */

297     public static NodeSet listFiles(ExpressionContext context, String JavaDoc path,
298             String JavaDoc filter, boolean rec) {
299         path = XSLUtil.evaluate(context, path);
300         final String JavaDoc ffilter = (filter != null)
301                 ? XSLUtil.evaluate(context, filter)
302                 : null;
303         Document JavaDoc doc = XSLUtil.getContextDocument(context);
304
305         try {
306             File JavaDoc f = new File JavaDoc(path);
307
308             if (!f.isDirectory()) {
309                 throw new IllegalArgumentException JavaDoc(path + " is not a directory.");
310             }
311             FileFilter JavaDoc ff = null;
312
313             if (ffilter != null) {
314                 ff = new FileFilter JavaDoc() {
315                     RE _re = new RE(ffilter);
316                     public boolean accept(File JavaDoc f) {
317                         return f.isDirectory() || _re.match(f.getName());
318                     }
319
320                     public String JavaDoc getDescription() {
321                         return ffilter;
322                     }
323                 };
324             }
325             File JavaDoc[] files = f.listFiles(ff);
326             NodeSet ns = new NodeSet();
327
328             appendFiles(doc, ns, files, ff, rec);
329             return ns;
330         } catch (Exception JavaDoc e) {
331             throw new WrappedRuntimeException(e);
332         }
333     }
334     
335     /**
336      * Creates "file" Nodes and adds them to a NodeSet.
337      * <p>
338      * @param doc Document to be used for Node creation.
339      * @param ns NodeSet (where Nodes have to be added).
340      * @param files files list.
341      * @param ff FileFilter to use.
342      * @param rec true (recursive) or false.
343      * @throws org.apache.xml.utils.WrappedRuntimeException DOM or IO errors...
344      */

345     protected static void appendFiles(Document JavaDoc doc, NodeSet ns, File JavaDoc[] files,
346             FileFilter JavaDoc ff, boolean rec) throws Exception JavaDoc {
347         for (int i = 0; i < files.length; i++) {
348             File JavaDoc f = files[i];
349
350             if (!f.isDirectory()) {
351                 Element JavaDoc file = doc.createElement("file");
352                 Element JavaDoc elt = doc.createElement("path");
353                 String JavaDoc path = f.getCanonicalFile().getParent();
354
355                 elt.appendChild(doc.createCDATASection((path != null)
356                         ? path
357                         : ""));
358                 file.appendChild(elt);
359                 elt = doc.createElement("sep");
360                 elt.appendChild(doc.createCDATASection(f.separator));
361                 file.appendChild(elt);
362                 elt = doc.createElement("name");
363                 elt.appendChild(doc.createCDATASection(f.getName()));
364                 file.appendChild(elt);
365                 ns.addElement(file);
366             } else if (rec) {
367                 appendFiles(doc, ns, f.listFiles(ff), ff, rec);
368             }
369         }
370     }
371 }
372
Popular Tags