KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > idaremedia > antx > mktemp > ListDirTask


1 /**
2  * $Id: ListDirTask.java 180 2007-03-15 12:56:38Z ssmc $
3  * Copyright 2004 iDare Media, Inc. All rights reserved.
4  *
5  * Originally written by iDare Media, Inc. for release into the public domain. This
6  * library, source form and binary form, is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public License (LGPL) as published
8  * by the Free Software Foundation; either version 2.1 of the License, or (at your option)
9  * any later version.<p>
10  *
11  * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
12  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13  * See the GNU LGPL for more details.<p>
14  *
15  * You should have received a copy of the GNU Lesser General Public License along with this
16  * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite
17  * 330, Boston, MA 02111-1307 USA. The GNU LGPL can be found online at
18  * http://www.fsf.org/copyleft/lesser.html<p>
19  *
20  * This product has been influenced by several projects within the open-source community.
21  * The JWare developers wish to acknowledge the open-source community's support. For more
22  * information regarding the open-source products used within JWare, please visit the
23  * JWare website.
24  *----------------------------------------------------------------------------------------*
25  * WEBSITE- http://www.jware.info EMAIL- inquiries@jware.info
26  *----------------------------------------------------------------------------------------*
27  **/

28
29 package com.idaremedia.antx.mktemp;
30
31 import java.io.File JavaDoc;
32
33 import org.apache.tools.ant.BuildException;
34 import org.apache.tools.ant.DirectoryScanner;
35 import org.apache.tools.ant.Project;
36 import org.apache.tools.ant.types.FileSet;
37
38 import com.idaremedia.antx.AntX;
39 import com.idaremedia.antx.AntXFixture;
40 import com.idaremedia.antx.AssertableTask;
41 import com.idaremedia.antx.FixtureExaminer;
42 import com.idaremedia.antx.apis.Requester;
43 import com.idaremedia.antx.helpers.Tk;
44 import com.idaremedia.antx.parameters.TransformHelper;
45 import com.idaremedia.antx.parameters.ValueTransform;
46
47 /**
48  * Utility task that lets you copy a directory's listing into the current project
49  * as a string list. You can list either the directory's immediate contents (the
50  * default) or all of its contents including sub-directories (requires a filter).
51  * The ListDirTask is useful when you need to iteratively process (identically) the
52  * contents of a directory, but do not know before hand the contents of the directory.
53  * <p/>
54  * The ListDirTask supports a single <span class="src">FileSet</span> that describes
55  * what it will return in its list. You can define this file set (under the
56  * <span class="src">&lt;filter&gt;</span> element) like you would any other Ant
57  * file set. Note that the shortcut filter parameters (like
58  * <span class="src">onlyFiles</span>) are applied to the output of the filter if
59  * any.
60  * <p/>
61  * Once you've loaded the listing into the project, you must use the AntX item list
62  * value URIs to read the list or the AntX flow control tasks to iterate the list.
63  * <p/>
64  * <b>Example Usage:</b><pre>
65  * &lt;<b>listdir</b> path="${basedir}" torefid="basedir.files" onlyfiles="yes"/&gt;
66  *
67  * &lt;<b>listdir</b> path="file:///builds/${user.name}/.ini" torefid="ini.ls" &gt;
68  * &lt;filter defaultexcludes="no"&gt;
69  * &lt;include name="*.xml,in"/&gt;
70  * &lt;/filter&gt;
71  * &lt;/listdir&gt;
72  * &lt;callforeach i="file" items="ini.ls" functions="..."/&gt;
73  * </pre>
74  *
75  * @since JWare/AntX 0.5
76  * @author ssmc, &copy;2004 <a HREF="http://www.jware.info">iDare&nbsp;Media,&nbsp;Inc.</a>
77  * @version 0.5
78  * @.safety single
79  * @.group api,helper
80  **/

81
82 public final class ListDirTask extends AssertableTask
83 {
84     /**
85      * Initializes a new listdir task instance.
86      **/

87     public ListDirTask()
88     {
89         super(AntX.mktemp+"ListDirTask");
90     }
91
92
93
94     /**
95      * Sets the directory being listed. If additional filtering
96      * information is specified, this path is used as the base
97      * directory for the associated <span class="src">FileSet</span>.
98      * @param pathOrUrl the directory information (non-null)
99      **/

100     public void setPath(String JavaDoc pathOrUrl)
101     {
102         require_(pathOrUrl!=null,"setDir- nonzro path");
103         m_path = new File JavaDoc(TransformHelper.apply(ValueTransform.OSPATH,
104                           pathOrUrl, getProject()));
105     }
106
107
108
109     /**
110      * Returns the directory being listed. Will return <i>null</i>
111      * if path was not set explicitly.
112      **/

113     public final File JavaDoc getPath()
114     {
115         return m_path;
116     }
117
118
119
120
121     /**
122      * Returns the directory that will be processed taking the
123      * nested filter (FileSet) into account. This method looks
124      * at the script supplied {@linkplain #getPath path}; if that
125      * was not set, it looks at the basedir option for any nested
126      * {@linkplain #createFilter filter}. Will return <i>null</i>
127      * if neither of these options have been set.
128      **/

129     public final File JavaDoc getListDirectory()
130     {
131         if (m_path!=null) {
132             return m_path;
133         }
134         if (m_fspec!=null) {
135             return m_fspec.getDir(getProject());
136         }
137         return null;
138     }
139
140
141
142     /**
143      * Sets the name of the string item list to which the listing
144      * should be written. This reference must not exist.
145      * @param refid the name of the (new) string list (non-null)
146      **/

147     public void setToRefId(String JavaDoc refid)
148     {
149         require_(!Tk.isWhitespace(refid), "setToRefId- nonzro name");
150         m_outlistRefId = refid;
151     }
152
153
154
155     /**
156      * Returns the name of the string item list created by this
157      * task. Will return <i>null</i> if not set explicitly. This
158      * attribute must be set before this task is executed.
159      **/

160     public final String JavaDoc getOutListRefId()
161     {
162         return m_outlistRefId;
163     }
164
165
166     /**
167      * Tells this task to only include non-directories in this list.
168      * Exactly what a "non-directory" includes depends on the Ant
169      * <span class="src">FileSet</span> implementation.
170      * @param onlyFiles <i>true</i> if only non-directories should be
171      * included.
172      **/

173     public void setOnlyFiles(boolean onlyFiles)
174     {
175         verifyNotDefined(m_onlyDirs);
176         m_onlyFiles = onlyFiles;
177     }
178
179
180
181     /**
182      * Tells this task to only include directories in this list.
183      * @param onlyDirs <i>true</i> if only directories should be included.
184      **/

185     public void setOnlyDirs(boolean onlyDirs)
186     {
187         verifyNotDefined(m_onlyFiles);
188         m_onlyDirs = onlyDirs;
189     }
190
191
192
193     /**
194      * Tells this task to include only the item's base names in the
195      * listing.
196      * @param onlyBase <i>true</i> to only include base names.
197      **/

198     public void setBaseNamesOnly(boolean onlyBase)
199     {
200         m_onlyBasename = onlyBase;
201     }
202
203
204
205     /**
206      * Returns <i>true</i> if only the items' base names will be
207      * included in the saved list. Defaults <i>off</i>; the full,
208      * absolute path is usually saved.
209      **/

210     public final boolean isBaseNamesOnly()
211     {
212         return m_onlyBasename;
213     }
214
215
216
217     /**
218      * Returns the filter (<span class="src">FileSet</span>) used by
219      * this task. Only one filter can be nested per list task instance.
220      * @return the new file set (never <i>null</i>)
221      * @throws BuildException if a filter file set already specified.
222      **/

223     public FileSet createFilter()
224     {
225         if (m_fspec!=null) {
226             String JavaDoc error = getAntXMsg("task.one.specialtask",
227                                 getTaskName(), "filter");
228             log(error, Project.MSG_ERR);
229             throw new BuildException(error, getLocation());
230         }
231         m_fspec = new FileSet();
232         if (m_path!=null) {
233             m_fspec.setDir(m_path);
234         }
235         return m_fspec;
236     }
237
238
239     /**
240      * Ensures all of this listing's required attributes have been
241      * properly defined. Also ensure the named directory exists and
242      * is a readable directory.
243      * @throws BuildException if unable to proceed in current state.
244      */

245     protected void verifyCanExecute_(String JavaDoc calr)
246     {
247         super.verifyCanExecute_(calr);
248
249         final Project P = getProject();
250         String JavaDoc refid = getOutListRefId();
251         String JavaDoc error = null;
252
253         // 1. No storage specified
254
if (refid==null) {
255             error = getAntXMsg("task.needs.this.attr",getTaskName(),"outlist");
256         } else {
257             // 2. Existing storage specified
258
FixtureExaminer.checkIfReference(P,m_rqlink,refid,true);
259
260             // 3. Directory not specified at all
261
if (m_fspec==null && m_path==null) {
262                 error = getAntXMsg("mktemp.ls.needs.path",getTaskName());
263             }
264             else if (m_fspec!=null) {
265                 // 4. Directory not specified as part of filter fileset.
266
File JavaDoc specDir = m_fspec.getDir(P);
267                 if (specDir==null) {
268                     if (m_path==null) {
269                         error = getAntXMsg("mktemp.ls.needs.path",getTaskName());
270                     } else {
271                         m_fspec.setDir(m_path);
272                     }
273                     // 5. Two different directories specified (?!)
274
} else if (m_path!=null &&
275                            !AntXFixture.fileUtils().fileNameEquals(m_path,specDir)) {
276                     error = getAntXMsg("mktemp.ls.diff.paths",m_path.getPath(),
277                                        specDir.getPath());
278                 }
279             } else {
280                 if (m_fspec==null) {
281                     createFilter().setDir(m_path);
282                 }
283             }
284         }
285         // 6. Non-existing directory (or non-directory) specified.
286
if (error==null) {
287             File JavaDoc lsDir = getListDirectory();
288             if (!lsDir.isDirectory()) {
289                 error = getAntXMsg("mktemp.ls.bad.dirpath",lsDir.getPath());
290             }
291         }
292         if (error!=null) {
293             log(error, Project.MSG_ERR);
294             throw new BuildException(error, getLocation());
295         }
296     }
297
298
299
300     /**
301      * Creates the string list containing the matched contents of the named
302      * directory. Will create an empty list if no items match filter criteria.
303      * The main directory and its parent directory ("." and "..") are
304      * <em>not</em> included.
305      * @throws BuildException if unable to execute in current state.
306      */

307     public void execute()
308     {
309         verifyCanExecute_("exec");
310
311         //NB: Limit to just the directory iff no other filter given!!
312
if (!m_fspec.hasPatterns() && !m_fspec.hasSelectors()) {
313             m_fspec.createInclude().setName("*");
314         }
315
316         DirectoryListing list = new DirectoryListing(m_onlyBasename);
317         DirectoryScanner ds = m_fspec.getDirectoryScanner(getProject());
318
319         if (m_onlyFiles || !m_onlyDirs) {
320             list.addIncludes(ds.getIncludedFiles(),ds);
321         }
322         if (m_onlyDirs || !m_onlyFiles) {
323             list.addIncludes(ds.getIncludedDirectories(),ds);
324         }
325
326         getProject().addReference(getOutListRefId(),list);
327     }
328
329
330
331
332     /**
333      * Verifies not trying to list onlyFile and onlyDirs at the same time.
334      **/

335     private void verifyNotDefined(boolean other)
336     {
337         if (other) {
338             String JavaDoc error = getAntXMsg("task.one.or.other.attr",
339                 "onlyfiles", "onlydirs");
340             log(error, Project.MSG_ERR);
341             throw new BuildException(error, getLocation());
342         }
343     }
344
345
346     private Requester m_rqlink = new Requester.ForComponent(this);
347     private String JavaDoc m_outlistRefId;//NB:required
348
private File JavaDoc m_path;//NB:required
349
private FileSet m_fspec;
350     private boolean m_onlyDirs, m_onlyFiles, m_onlyBasename;
351 }
352
353 /* end-of-ListDirTask.java */
Popular Tags