KickJava   Java API By Example, From Geeks To Geeks.

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


1 /**
2  * $Id: MkTempObject.java 180 2007-03-15 12:56:38Z ssmc $
3  * Copyright 2002-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 as published by the
8  * Free Software Foundation; either version 2.1 of the License, or (at your option) any
9  * 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 (GNU Lesser General Public License) 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 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.IOException JavaDoc;
33
34 import org.apache.tools.ant.BuildException;
35 import org.apache.tools.ant.Project;
36 import org.apache.tools.ant.util.FileUtils;
37
38 import com.idaremedia.antx.AntX;
39 import com.idaremedia.antx.ExportedProperties;
40 import com.idaremedia.antx.helpers.Tk;
41
42 /**
43  * A factory task for temporary files and directories. Used to aid with testing other
44  * task implementations but is generally useful if your build process creates temporary
45  * or intermediate files.
46  * <p>
47  * <b> Examples:</b><pre>
48  * &lt;mktmpdir prefix=".sql-" pathproperty="sql.root"/&gt;
49  *
50  * &lt;mktmpfile prefix="sot" copyresource="antx/testfiles/broken-build.xml"
51  * pathproperty="scratch.file0"/&gt;
52  * </pre>
53  *
54  * @since JWare/AntX 0.1
55  * @author ssmc, &copy;2002-2004 <a HREF="http://www.jware.info">iDare&nbsp;Media,&nbsp;Inc.</a>
56  * @version 0.5
57  * @.safety guarded
58  * @.group api,helper
59  * @see TempLocator
60  **/

61
62 public abstract class MkTempObject extends MkNewObject
63 {
64     /** The default temp-object file prefix. **/
65     protected static final String JavaDoc DEFAULT_PREFIX= "qat";
66
67
68     /**
69      * Initializes a new MkTempObject task.
70      **/

71     protected MkTempObject()
72     {
73         super(AntX.mktemp);
74     }
75
76
77     /**
78      * Initializes a new CV-labeled MkTempObject task.
79      **/

80     protected MkTempObject(String JavaDoc iam)
81     {
82         super(iam);
83     }
84
85
86     /**
87      * Returns the preferred (prefix) filler character. Used
88      * when a prefix doesn't met minimum length requirements.
89      * Should return a simple ASCII character to be safe.
90      **/

91     protected char getFillerChar()
92     {
93         return '_';
94     }
95
96
97     /**
98      * Returns this class's default prefix if none specified.
99      * Looks for build-supplied default in appropriate project
100      * property; if none defined, uses {@linkplain #DEFAULT_PREFIX}.
101      * @param forFile <i>true</i> if query is for a file
102      **/

103     protected final String JavaDoc getDefaultPrefix(boolean forFile)
104     {
105         String JavaDoc pfx = Tk.getTheProperty
106             (getProject(), AntX.DEFAULT_TEMPOBJECT_PREFIX_PROP);
107
108         return (pfx!=null) ? pfx : MkTempObject.DEFAULT_PREFIX;
109     }
110
111
112     /**
113      * Sets a user-defined prefix for new temporary items.
114      * This prefix might be adjusted to platform-required
115      * rules if necessary (like minimum length).
116      **/

117     public void setPrefix(String JavaDoc prefix)
118     {
119         require_(prefix!=null,"setPfx- nonzro pfx");
120         m_prefix = prefix;
121     }
122
123
124     /**
125      * Returns the user-defined prefix; returns <i>null</i>
126      * if never set.
127      **/

128     public String JavaDoc getPrefix()
129     {
130         return m_prefix;
131     }
132
133
134     /**
135      * Returns the calculated prefix to-be used with a new
136      * temporary item. The returned prefix mets all Java API
137      * prerequisites for length, form, etc.
138      * @param forFile <i>true</i> if query is for a file
139      **/

140     public final String JavaDoc getEffectivePrefix(boolean forFile)
141     {
142         String JavaDoc pfx = getPrefix();
143         if (pfx!=null && pfx.length()<3) {
144             char filler = getFillerChar();
145             for (int i=3-pfx.length();i>0;i--) {
146                 pfx += filler;
147             }
148         }
149         return (pfx!=null) ? pfx : getDefaultPrefix(forFile);
150     }
151
152
153     /**
154      * Sets a user-defined suffix for new temporary items.
155      * This suffix might be adjusted to platform-required
156      * rules if necessary (like minimum length).
157      **/

158     public void setSuffix(String JavaDoc suffix)
159     {
160         require_(suffix!=null,"setSfx- nonzro sfx");
161         m_suffix = suffix;
162     }
163
164
165     /**
166      * Returns the user-defined suffix; returns <i>null</i>
167      * if never set.
168      **/

169     public String JavaDoc getSuffix()
170     {
171         return m_suffix;
172     }
173
174
175     /**
176      * Returns the calculated suffix to-be used with a new
177      * temporary item. The returned suffix mets all Java API
178      * prerequisites for length, form, etc.
179      * @param forFile <i>true</i> if query is for a file
180      **/

181     public final String JavaDoc getEffectiveSuffix(boolean forFile)
182     {
183         String JavaDoc sfx = getSuffix();
184         if (sfx!=null && forFile) {
185             if (sfx.length()>0 && sfx.charAt(0)!='.') {
186                 sfx = "."+sfx;
187             }
188         }
189         return (sfx!=null) ? sfx : (forFile ? ".tmp" : "");
190     }
191
192
193     /**
194      * Sets the property to be created with the temporary
195      * object's full path.
196      * @param property property to be created (non-null)
197      * @since JWare/AntX 0.3
198      **/

199     public void setPathProperty(String JavaDoc property)
200     {
201         require_(property!=null,"setProp- nonzro nam");
202         m_updateProperty = property;
203     }
204
205
206     /**
207      * Returns the property created with the temporary item's
208      * full path. Returns <i>null</i> if never set.
209      **/

210     public final String JavaDoc getPathProperty()
211     {
212         return m_updateProperty;
213     }
214
215
216     /**
217      * Sets the variable to be updated with the temporary
218      * object's full path.
219      * @param variable variable to be updated (non-null)
220      * @since JWare/AntX 0.5
221      **/

222     public void setPathVariable(String JavaDoc variable)
223     {
224         require_(variable!=null,"setVar- nonzro nam");
225         m_updateVar = variable;
226     }
227
228
229     /**
230      * Returns the variable updated with the temporary item's
231      * full path. Returns <i>null</i> if never set.
232      * @since JWare/AntX 0.5
233      **/

234     public final String JavaDoc getPathVariable()
235     {
236         return m_updateVar;
237     }
238
239
240     /**
241      * Sets the parent directory of any created temporary object. The
242      * specified directory must be an existing, writable directory.
243      * @see TempLocator
244      **/

245     public void setIn(File JavaDoc inDir)
246     {
247         require_(inDir!=null,"setIn- nonzro dir");
248         require_(inDir.canWrite(), "setIn- existing writable directory");
249         m_inDir= inDir;
250     }
251
252
253     /**
254      * Returns the root directory into which all other temporary
255      * objects (files and directories) created. Never returns
256      * <i>null</i>; defaults the OS's default temporary directory.
257      **/

258     public File JavaDoc getInDir()
259     {
260         return m_inDir;
261     }
262
263
264     /**
265      * Defines whether this task will mark all temporary objects
266      * as delete-on-exit.
267      * @param leaveOnExit <i>true</i> if items should not be deleted
268      **/

269     public void setPersist(boolean leaveOnExit)
270     {
271         m_autoDelete = !leaveOnExit;
272     }
273
274
275     /**
276      * Returns <i>true</i> if this task will try to mark all
277      * temporary objects (files and directories) as delete-on-exit.
278      **/

279     public boolean isAutoDelete()
280     {
281         return m_autoDelete;
282     }
283
284
285     /**
286      * Grunt work of creating a new scratch file in specified location.
287      * If a prototype source file/resource is defined, its contents
288      * are copied to new file.
289      * @param inDir new scratch file's parent directory (non-null)
290      * @throws BuildException if unable to create parent directory or new file
291      **/

292     protected final File JavaDoc createFile(File JavaDoc inDir) throws BuildException
293     {
294         File JavaDoc newFile=null;
295         FileUtils fsu= getFileUtils();
296
297         try {
298             //NB: Use Ant's temp file facilities which don't create actual files
299
// since would be wasteful to create a file if it was just going
300
// to be stomped on with a copy. Also is safer to use a single
301
// source of tempfile names to make sure chance for name-collisions
302
// is minimized (ssmc).
303
newFile = fsu.createTempFile
304                 (getEffectivePrefix(true),getEffectiveSuffix(true),inDir);
305
306             if (getPrototypePlainFile()!=null) {
307                 fsu.copyFile(getPrototypePlainFile(),newFile,
308                              getCopyFilters(),false);
309             }
310             else if (getPrototypeResourceFile()!=null) {
311                 fsu.copyFile(getPrototypeResourceFile(),newFile,
312                              getCopyFilters(),false);
313             } else {
314                 newFile.createNewFile();
315                 copyPrototypeLines(newFile,false);
316             }
317         } catch(IOException JavaDoc iox) {
318             throw new BuildException(iox, getLocation());
319         }
320
321         if (isAutoDelete()) {
322             newFile.deleteOnExit();
323         }
324         return newFile;
325     }
326
327
328     /**
329      * Grunt work of creating a directory (plus prototype entities)
330      * in specified location.
331      * @param inDir temp directory's location (non-null)
332      * @return new directory's full path
333      * @throws BuildException if unable to create or verify directory
334      **/

335     protected final File JavaDoc createDirectory(File JavaDoc inDir) throws BuildException
336     {
337         File JavaDoc newDir=null;
338         FileUtils fsu= getFileUtils();
339
340         try {
341             newDir = fsu.createTempFile
342                 (getEffectivePrefix(false),getEffectiveSuffix(false),inDir);
343
344             newDir.mkdir();
345
346             if (!newDir.isDirectory() || !newDir.canWrite()) {
347                 String JavaDoc ermsg = uistrs().get
348                     ("mktemp.cant.make.tmpdir",
349                      inDir.getPath(), newDir.getName());
350                 log(ermsg, Project.MSG_ERR);
351                 throw new BuildException(ermsg,getLocation());
352             }
353
354             if (getPrototypePlainFile()!=null) {
355                 copyPrototypeFile(getPrototypePlainFile(), newDir);
356             }
357             else if (getPrototypeResourceFile()!=null) {
358                 copyPrototypeFile(getPrototypeResourceFile(), newDir);
359             }
360
361         } catch(IOException JavaDoc iox) {
362             throw new BuildException(iox, getLocation());
363         }
364         return newDir;
365     }
366
367
368
369     /**
370      * Ensure any update properties are set to new object's path information.
371      * @since JWare/AntX 0.5
372      */

373     protected void saveFinalPath(File JavaDoc finalObject, boolean strict)
374     {
375         String JavaDoc finalPath = finalObject.getPath();
376         if (getPathProperty()!=null) {
377             checkIfProperty_(getPathProperty(),!strict);
378             getProject().setNewProperty(getPathProperty(),finalPath);
379         }
380         if (getPathVariable()!=null) {
381             ExportedProperties.set(getPathVariable(),finalPath);
382         }
383
384         super.saveFinalPath(finalObject,strict);
385     }
386
387
388     private String JavaDoc m_prefix = null;//NB: required for files
389
private String JavaDoc m_suffix = null;//NB: will be made '.tmp'
390
private String JavaDoc m_updateProperty;
391     private String JavaDoc m_updateVar;
392     private File JavaDoc m_inDir= TempLocator.getSystemTempDir();
393     private boolean m_autoDelete=true;
394 }
395
396 /* end-of-MkTempObject.java */
397
Popular Tags