KickJava   Java API By Example, From Geeks To Geeks.

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


1 /**
2  * $Id: TruncateFileTask.java 180 2007-03-15 12:56:38Z ssmc $
3  * Copyright 2004-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.File JavaDoc;
32 import java.io.FileOutputStream 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.FileSet;
39
40 import com.idaremedia.antx.AntX;
41 import com.idaremedia.antx.AntXFixture;
42 import com.idaremedia.antx.AssertableTask;
43 import com.idaremedia.antx.helpers.InnerString;
44 import com.idaremedia.antx.ownhelpers.FileSetsIterator;
45 import com.idaremedia.antx.parameters.FeedbackLevel;
46 import com.idaremedia.antx.parameters.RecoveryEnabled;
47
48 /**
49  * Task that sets the size of a file to zero making it empty. A faster way to do the
50  * next snippet in tests.
51  * <pre>
52  * &lt;replaceregexp flags="s"&gt;
53  * &lt;regexp pattern=".*"/&gt;
54  * &lt;substitution expression=""/&gt;
55  * ...
56  * &lt;/replaceregexp&gt;
57  * </pre>
58  * <b>Example Usage:</b><pre>
59  * &lt;truncatefile file="${dashboard}/build.status" mustexist="yes"/&gt;
60  * &lt;truncatefile projectfile="subbuild.xml"/&gt;
61  * &lt;truncatefile file="subbuild.xml" createIfMissing="yes"/&gt;
62  * &lt;truncatefile projectfile="vars.in" haltIfError="yes"/&gt;
63  *
64  * &lt;truncatefiles haltiferror="yes" feedback="verbose"&gt;
65  * &lt;files dir="${basedir}/etc"&gt;
66  * &lt;include name="*.log"/&gt;
67  * &lt;include name="*.last"/&gt;
68  * &lt;/files&gt;
69  * &lt;file name="build.last"/&gt;
70  * &lt;files dir="${filterfiles}/dynamic"&gt;
71  * &lt;include name="**&#47;*.xml,vars"/&gt;
72  * &lt;include name="*.properties,vars"/&gt;
73  * &lt;/files&gt;
74  * &lt;/truncatefiles&gt;
75  * </pre>
76  *
77  * @since JWare/AntX 0.5
78  * @author ssmc, &copy;2004-2005 <a HREF="http://www.jware.info">iDare&nbsp;Media,&nbsp;Inc.</a>
79  * @version 0.5
80  * @.safety single
81  * @.group impl,helper
82  **/

83
84 public class TruncateFileTask extends AssertableTask
85     implements RecoveryEnabled
86 {
87
88     /**
89      * Initializes a new TruncateFileTask instance.
90      **/

91     public TruncateFileTask()
92     {
93         super(AntX.mktemp+"TruncateFileTask:");
94     }
95
96
97     /**
98      * Initializes a new truncate file subclass instance.
99      * @param iam CV-label (non-null)
100      **/

101     protected TruncateFileTask(String JavaDoc iam)
102     {
103         super(iam);
104     }
105
106
107     /**
108      * Initializes this task instance's field helpers.
109      */

110     public void init()
111     {
112         super.init();
113         m_filerefs = AntXFixture.newList();
114     }
115
116
117
118     /**
119      * Tells this task how much non-diagnostic feedback to generate.
120      * Really only has "loud" vs. "quiet-ish" interpretation. If
121      * set quiet, this task will not issue a warning if it hits a
122      * hard limit.
123      * @param level feedback level (non-null)
124      **/

125     public void setFeedback(String JavaDoc level)
126     {
127         require_(level!=null,"setFeedback- nonzro level");
128         FeedbackLevel fbl = FeedbackLevel.from(level);
129         if (fbl==null) {
130             String JavaDoc e = getAntXMsg("task.illegal.param.value",
131                            getTaskName(), level,"feedback");
132             log(e, Project.MSG_ERR);
133             throw new BuildException(e, getLocation());
134         }
135         m_fbLevel = fbl;
136     }
137
138
139
140     /**
141      * Returns this task's assigned feedback level. Will return
142      * <i>null</i> by default.
143      **/

144     public final FeedbackLevel getFeedbackLevel()
145     {
146         return m_fbLevel;
147     }
148
149
150
151     /**
152      * Tells this task whether it should stop the build
153      * process if unable to empty and existing file or create
154      * a new empty file.
155      * @param halt <i>true</i> if should stop
156      **/

157     public void setHaltIfError(boolean halt)
158     {
159         m_haltIfError= halt;
160     }
161
162
163     /**
164      * Returns <i>true</i> if this task will generate an build
165      * error if it is unable to empty an existing file or create
166      * a new empty file.
167      **/

168     public boolean isHaltIfError()
169     {
170         return m_haltIfError;
171     }
172
173
174     /**
175      * Tells this task whether the file to be emptied must
176      * already exist (and be writable).
177      * @param must <i>true</i> if must exist
178      **/

179     public void setMustExist(boolean must)
180     {
181         m_mustExist = must;
182     }
183
184
185     /**
186      * Returns <i>true</i> if the file to be emptied must
187      * already exist.
188      **/

189     public boolean getMustExist()
190     {
191         return m_mustExist;
192     }
193
194
195     /**
196      * Tells this task whether it's ok to create a new empty
197      * file if file does not exist.
198      * @param create <i>true</i> to create new empty file
199      **/

200     public void setCreateIfMissing(boolean create)
201     {
202         m_createIfMissing = create;
203     }
204
205
206
207     /**
208      * Returns <i>true</i> if will create an empty new file if
209      * it does not already exist.
210      **/

211     public final boolean willCreateIfMissing()
212     {
213         return m_createIfMissing;
214     }
215
216
217
218     /**
219      * Tells this task the path of file to be emptied.
220      * @param filepath the path of file to be emptied (non-null)
221      **/

222     public void setFile(String JavaDoc filepath)
223     {
224         require_(filepath!=null,"setFile- nonzro path");
225         m_filerefs.add(getProject().resolveFile(filepath));
226     }
227
228
229
230     /**
231      * Tells this task the file to be emptied.
232      * @param file the file to be emptied (non-null)
233      **/

234     public void setProjectFile(File JavaDoc file)
235     {
236         require_(file!=null,"setFile- nonzro file");
237         m_filerefs.add(file);
238     }
239
240
241
242     /**
243      * Returns a new fileset for (independent) configuration.
244      * @return new fileset for configuration
245      **/

246     public void addConfiguredFiles(FileSet fs)
247     {
248         require_(fs!=null,"addFiles- nonzro set");
249         m_filerefs.add(fs);
250     }
251
252
253
254     /**
255      * Adds a single file path element to be truncated.
256      * @param path file name (non-null)
257      **/

258     public void addConfiguredFile(InnerString path)
259     {
260         require_(path!=null,"addFile- nonzro path");
261         m_filerefs.add(getProject().resolveFile(path.toString(getProject())));
262     }
263
264
265     /**
266      * Returns an iterator for all of the files to be emptied.
267      * This is an expensive operation potentially because it must
268      * determine matched files from nested filesets. Will return
269      * <i>null</i> if no file has been specified explicitly. The
270      * returned iterator returns <em>file paths</em>.
271      **/

272     public final Iterator JavaDoc getPaths()
273     {
274         if (m_filerefs.isEmpty()) {
275             return null;
276         }
277         return new FileSetsIterator(m_filerefs,getProject());
278     }
279
280
281
282     /**
283      * Ensures we've been given at least one file to truncate.
284      * Whether or not the file is valid is determined by the
285      * execute method.
286      **/

287     protected void verifyCanExecute_(String JavaDoc calr)
288     {
289         verifyInProject_(calr);
290
291         if (m_filerefs.isEmpty()) {
292             String JavaDoc error = getAntXMsg("task.needs.oneof.these.nested",
293                                       getTaskName(),"files|file");
294             log(error,Project.MSG_ERR);
295             throw new BuildException(error,getLocation());
296         }
297     }
298
299
300
301     /**
302      * Ensures the named file is empty; will create a new empty file
303      * if necessary.
304      * @throws BuildException if unable to create/empty file and the
305      * 'haltiferror' option is turned on
306      **/

307     public void execute()
308     {
309         verifyCanExecute_("exec");
310
311         Iterator JavaDoc itr = getPaths();
312
313         while (itr.hasNext()) {
314             File JavaDoc f= new File JavaDoc(itr.next().toString());
315             String JavaDoc problem = truncateFile(f);
316             if (problem!=null) {
317                 throw new BuildException(problem,getLocation());
318             }
319         }
320     }
321
322
323
324     /**
325      * Ensures the named file is empty; will create a new empty file
326      * if necessary.
327      * @return Error message if unable to create/empty file and the
328      * 'haltiferror' option is turned on; otherwise returns <i>null</i>
329      **/

330     protected String JavaDoc truncateFile(File JavaDoc f)
331     {
332         boolean notThere= !f.exists();
333
334         if (notThere) {
335             if (getMustExist()) {
336                 String JavaDoc error = getAntXMsg("task.err.filenotfound",f.getPath());
337                 log(error,Project.MSG_ERR);
338                 return error;
339             }
340             else if (!willCreateIfMissing()) {
341                 return null;//=>done!
342
}
343         }
344         try {
345             if (!FeedbackLevel.isQuietish(m_fbLevel,true)) {
346                 log("Trying: "+f.getPath(), Project.MSG_VERBOSE);
347             }
348             if (notThere) {
349                 f.createNewFile();
350             } else {
351                 if (f.length()!=0) {
352                     FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(f);
353                     fos.write(new byte[0]);//NB:truncate!
354
fos.close();
355                 }
356             }
357         }
358         catch(Exception JavaDoc anyX) {
359             String JavaDoc problem = getAntXMsg("mktemp.truncfile.cant",
360                                         f.getPath(), anyX.getMessage());
361             if (isHaltIfError()) {
362                 log(problem,Project.MSG_ERR);
363                 return problem;
364             }
365             log(problem, Project.MSG_WARN);
366         }
367         return null;
368     }
369
370
371     private FeedbackLevel m_fbLevel=FeedbackLevel.NORMAL;
372     private boolean m_haltIfError;//no
373
private boolean m_mustExist;//no
374
private boolean m_createIfMissing;//no
375
private List JavaDoc m_filerefs;
376 }
377
378 /* end-of-TruncateFileTask.java */
379
Popular Tags