KickJava   Java API By Example, From Geeks To Geeks.

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


1 /**
2  * $Id: MkdirsTask.java 186 2007-03-16 13:42:35Z ssmc $
3  * Copyright 2005 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.BufferedReader JavaDoc;
32 import java.io.File JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.List JavaDoc;
35
36 import org.apache.tools.ant.BuildException;
37 import org.apache.tools.ant.Project;
38 import org.apache.tools.ant.types.FileList;
39 import org.apache.tools.ant.util.FileUtils;
40
41 import com.idaremedia.antx.AntX;
42 import com.idaremedia.antx.AntXFixture;
43 import com.idaremedia.antx.AssertableTask;
44 import com.idaremedia.antx.FlexString;
45 import com.idaremedia.antx.apis.Requester;
46 import com.idaremedia.antx.helpers.Tk;
47 import com.idaremedia.antx.parameters.FeedbackLevel;
48 import com.idaremedia.antx.parameters.RecoveryEnabled;
49 import com.idaremedia.antx.starters.ListFriendly;
50
51 /**
52  * Utility task that lets you create a slew of directories with compact instruction.
53  * Bypasses need to create looping construct around a simple &lt;mkdir&gt; task.
54  * <p/>
55  * <b>Example Usage:</b><pre>
56  * &lt;<b>mkdirs</b> base="${workspace}" names="sources,outputs,documents"/&gt;
57  * &lt;<b>mkdirs</b> base="${workspace}" namesfile="${layoutfile}"/&gt;
58  * &lt;<b>mkdirs</b> haltiferror="yes"&gt;
59  * &lt;filelist dir="${root}" files="build,release,workspace"/&gt;
60  * &lt;filelist dir="${root}/workspace" files="sources,outputs,documents"/&gt;
61  * &lt;/mkdirs&gt;
62  * </pre>
63  *
64  * @since JWare/AntX 0.5
65  * @author ssmc, &copy;2005 <a HREF="http://www.jware.info">iDare&nbsp;Media,&nbsp;Inc.</a>
66  * @version 0.5
67  * @.safety single
68  * @.group api,helper
69  **/

70
71 public final class MkdirsTask extends AssertableTask implements RecoveryEnabled
72 {
73     private static final int BY_NAME=0;
74     private static final int BY_NAMELIST=BY_NAME+1;
75     private static final int BY_NAMEFILE=BY_NAMELIST+1;
76
77
78     /**
79      * Initializes a new mkdirs task instance.
80      **/

81     public MkdirsTask()
82     {
83         super(AntX.mktemp+"MkdirsTask:");
84     }
85
86
87     /**
88      * Tells this task whether problems making named directories
89      * should signal a build error. Defaults "off" if never set.
90      */

91     public void setHaltIfError(boolean halt)
92     {
93         m_haltIfError = halt;
94     }
95     
96
97     /**
98      * Returns whether this task will signal a build error if
99      * it encounters any problems making (or verifying) directory.
100      * Returns "true" if never set.
101      * @see #setHaltIfError setHaltIfError(&#8230;)
102      */

103     public boolean isHaltIfError()
104     {
105         return m_haltIfError;
106     }
107
108
109     /**
110      * Sets this task's diagnostic feedback level. For no feedback
111      * except build errors (haltiferror=true), set level to "none"
112      * or "veryquiet".
113      * @param fb the feedback level (non-null)
114      * @throws BuildException if feedback level unrecognized.
115      */

116     public void setFeedback(String JavaDoc fb)
117     {
118         require_(fb!=null,"setFeedback- nonzro value");
119         FeedbackLevel fbLevel = FeedbackLevel.from(fb);
120         if (fbLevel==null) {
121             String JavaDoc error = getAntXMsg("task.illegal.param.value",
122                                      getTaskName(), fb, "feedback");
123             log(error, Project.MSG_ERR);
124             throw new BuildException(error,getLocation());
125         }
126         m_fbLevel = fbLevel;
127     }
128
129
130     /**
131      * Factory method for a nested filelist element. Ensures new
132      * filelist is added to this task's list of to-be-made
133      * directories.
134      * @return new filelist (never null)
135      * @.impl We cannot default the filelist's -dir here because
136      * we must support the -refid parameter.
137      */

138     public FileList createFileList()
139     {
140         FileList fl = new FileList();
141         fl.setProject(getProject());
142
143         m_dirs.add(fl);
144         return fl;
145     }
146
147
148     /**
149      * Returns this task's builtin filelist. The builtin filelist
150      * is configured using the various "names*" parameters. Never
151      * returns <i>null</i>.
152      **/

153     private FileList builtinFileList()
154     {
155         if (m_builtin==null) {
156             m_builtin = createFileList();
157             m_builtin.setDir(getProject().getBaseDir());
158         }
159         return m_builtin;
160     }
161
162
163
164     /**
165      * Sets this task's default base directory for all filelists.
166      * @param baseDir the base directory (non-null)
167      * @throws IllegalArgumentException if baseDir is <i>null</i>.
168      **/

169     public void setBase(File JavaDoc baseDir)
170     {
171         require_(baseDir!=null,"setBase- nonzro dirname");
172         builtinFileList().setDir(baseDir);
173     }
174
175
176
177     /**
178      * Sets this task's list of directories as a comma-delimited
179      * list of names. Will update the builtin filelist only.
180      * @param subdirNames the comma-delimited list (non-null)
181      * @throws IllegalArgumentException if subdirNames is <i>null</i>.
182      **/

183     public void setNames(String JavaDoc subdirNames)
184     {
185         require_(subdirNames!=null,"setNames- nonzro namelst");
186         setByMethod(BY_NAME,subdirNames);
187     }
188
189
190     /**
191      * Pre-execution processing for builtin filelist when specified
192      * as a comma-delimited list of directory names.
193      **/

194     private void handleByNames()
195     {
196         List JavaDoc nl = Tk.splitList(m_sourceString);
197         if (!nl.isEmpty()) {
198             FileList builtin = builtinFileList();
199             for (int i=0,N=nl.size();i<N;i++) {
200                 FileList.FileName fn = new FileList.FileName();
201                 fn.setName((String JavaDoc)nl.get(i));
202                 builtin.addConfiguredFile(fn);
203             }
204         }
205     }
206
207
208
209     /**
210      * Sets this task's list of directories as a reference to a
211      * string list of names. Will update the builtin filelist only.
212      * @param listsRefId the reference id of the string list (non-null)
213      * @throws IllegalArgumentException if listsRefId is <i>null</i>.
214      **/

215     public void setNamesList(String JavaDoc listsRefId)
216     {
217         require_(listsRefId!=null,"setNamesList- nonzro refid");
218         setByMethod(BY_NAMELIST,listsRefId);
219     }
220
221
222
223     /**
224      * Pre-execution processing for the builtin filelist when
225      * specified as an AntX StringItemList of some kind.
226      * @throws BuildException if referred-to thing is not list-friendly.
227      **/

228     private void handleByNamesList()
229     {
230         ListFriendly list = (ListFriendly)getReferencedObject
231             (null,m_sourceString,ListFriendly.class);
232         if (!list.isEmpty()) {
233             FileList builtin = builtinFileList();
234             Iterator JavaDoc itr= list.readonlyStringIterator(getProject());
235             while (itr.hasNext()) {
236                 FileList.FileName fn = new FileList.FileName();
237                 fn.setName(itr.next().toString());
238                 builtin.addConfiguredFile(fn);
239             }
240         }
241     }
242
243
244
245     /**
246      * Sets this task's list of directories as an external listing
247      * file. Will update the builtin filelist only.
248      * @param listsFile the path to the external file (non-null)
249      * @throws IllegalArgumentException if listsFile is <i>null</i>.
250      **/

251     public void setNamesFile(String JavaDoc listsFile)
252     {
253         require_(listsFile!=null,"setNamesFile- nonzro filename");
254         setByMethod(BY_NAMEFILE,listsFile);
255     }
256
257
258
259     /**
260      * Pre-execution processing for the builtin filelist when
261      * specified as an external listing file.
262      * @throws BuildException if unable to read information for
263      * any reason and haltiferror=true.
264      **/

265     private void handleByNamesFile()
266     {
267         final Project myproject = getProject();
268         File JavaDoc file = myproject.resolveFile(m_sourceString);
269         if (file.exists()) {
270             if (!file.canRead()) {
271                 String JavaDoc message = getAntXMsg("task.bad.configfile",file.getPath(),
272                     "Cannot read file");
273                 if (isHaltIfError()) {
274                     log(message,Project.MSG_ERR);
275                     throw new BuildException(message,getLocation());
276                 }
277                 log(message,Project.MSG_WARN);
278                 return;
279             }
280             try {
281                 BufferedReader JavaDoc fr = new BufferedReader JavaDoc(new java.io.FileReader JavaDoc(file));
282                 FileList builtin = builtinFileList();
283                 FlexString filter = (FlexString)m_modifiers.clone();
284                 String JavaDoc next;
285                 while ((next=fr.readLine())!=null) {
286                     filter.set(next);
287                     next = filter.getValue();
288                     if (next!=null) {
289                         FileList.FileName fn = new FileList.FileName();
290                         fn.setName(Tk.resolveString(myproject,next));
291                         builtin.addConfiguredFile(fn);
292                     }
293                 }
294             } catch(Exception JavaDoc ioxOrbuildX) {
295                 String JavaDoc message = getAntXMsg("task.bad.configfile",file.getPath(),
296                     ioxOrbuildX.getMessage());
297                 if (isHaltIfError()) {
298                     log(message,Project.MSG_ERR);
299                     throw new BuildException(message,getLocation());
300                 }
301                 log(message,Project.MSG_WARN);
302             }
303         }//exists
304
}
305
306
307     /**
308      * Sets this task's builtin filelist's directory information.
309      * Ensures only one shorthand method is defined.
310      * @param method the shorthand method
311      * @param source the information descriptor (non-null0
312      * @throws BuildException if builtin filelist already defined.
313      **/

314     private void setByMethod(int method, String JavaDoc source)
315     {
316         if (m_byMethod>=BY_NAME) {
317             String JavaDoc error = getAntXMsg("task.only.oneof.attr",
318                                       "names|nameslist|namesfile");
319             log(error,Project.MSG_ERR);
320             throw new BuildException(error,getLocation());
321         }
322         m_byMethod = method;
323         m_sourceString = source;
324     }
325
326
327
328     /**
329      * Creates all the named directories, including any parent dirs.
330      * Does nothing to existing directories.
331      * @throws BuildException if unable to create or verify all dirs
332      * and -haltiferror is turned on.
333      */

334     public void execute()
335     {
336         verifyCanExecute_("exec");
337
338         if (m_sourceString!=null) {
339             switch(m_byMethod) {
340                 case BY_NAME: handleByNames(); break;
341                 case BY_NAMELIST: handleByNamesList(); break;
342                 default: handleByNamesFile();
343             }
344         } else if (m_builtin!=null) {
345             m_dirs.remove(m_builtin);//OK, filelists already inited!
346
m_builtin = null;
347         }
348
349         final Project myproject = getProject();
350         Requester rqlink = new Requester.ForComponent(this);
351         FileUtils fu = AntXFixture.fileUtils();
352
353         for (int i=0,N=m_dirs.size();i<N;i++) {
354             FileList fl = (FileList)m_dirs.get(i);
355             String JavaDoc[] dirnames = fl.getFiles(myproject);
356             File JavaDoc basedir = fl.getDir(myproject);
357             for (int j=0;j<dirnames.length;j++) {
358                 File JavaDoc dir = fu.resolveFile(basedir,dirnames[j]);
359                 Mkdirs.run(dir,m_haltIfError,m_fbLevel,rqlink);
360             }
361         }
362     }
363
364
365
366     /**
367      * Verifies that at least one directory named for creation. If
368      * empty an alert is issued unless feedback=none|*quiet.
369      */

370     protected void verifyCanExecute_(String JavaDoc calr)
371     {
372         super.verifyCanExecute_(calr);
373
374         if (!FeedbackLevel.isQuietish(m_fbLevel,false,false)) {
375             if (m_sourceString==null && m_builtin!=null && m_dirs.size()==1) {
376                 String JavaDoc alert = getAntXMsg("mktemp.mkdirs.nothin");
377                 log(alert,Project.MSG_INFO);
378             }
379         }
380
381         defaultFileListDirs();
382     }
383
384
385
386     /**
387      * This is an obscene hack that is required because Ant's
388      * ordering of nested item creation and parent parameter
389      * initialization is (delicately speaking) as*-backwards.
390      * @since JWare/AntX 0.5
391      **/

392     private void defaultFileListDirs()
393     {
394         if (m_builtin!=null) {
395             final Project myproject = getProject();
396             File JavaDoc defaultDir= m_builtin.getDir(myproject);
397             if (defaultDir!=myproject.getBaseDir()) { //NB: identity-compare OK
398
for (int i=0,N=m_dirs.size();i<N;i++) {
399                     FileList fl= (FileList)m_dirs.get(i);
400                     if (fl!=m_builtin && !fl.isReference() && fl.getDir(myproject)==null) {
401                         fl.setDir(defaultDir);
402                     }
403                 }
404             }
405         }
406     }
407
408
409     private boolean m_haltIfError=false;
410     private List JavaDoc m_dirs = AntXFixture.newList();
411     private FileList m_builtin;//NB:used by shorthand "names*" parameters
412
private String JavaDoc m_sourceString;
413     private int m_byMethod= -1;
414     private FeedbackLevel m_fbLevel= FeedbackLevel.NORMAL;
415     private FlexString m_modifiers = new FlexString();
416 }
417
418 /* end-of-MkdirsTask.java */
Popular Tags