KickJava   Java API By Example, From Geeks To Geeks.

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


1 /**
2  * $Id: MkNewObject.java 180 2007-03-15 12:56:38Z ssmc $
3  * Copyright 2003-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.lang.reflect.Constructor JavaDoc;
32 import java.io.File JavaDoc;
33 import java.io.FileOutputStream JavaDoc;
34 import java.io.IOException JavaDoc;
35 import java.io.PrintWriter JavaDoc;
36 import java.net.URL JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.util.List JavaDoc;
39 import java.util.Properties JavaDoc;
40
41 import org.apache.tools.ant.BuildException;
42 import org.apache.tools.ant.Project;
43 import org.apache.tools.ant.types.FilterSet;
44 import org.apache.tools.ant.types.FilterSetCollection;
45 import org.apache.tools.ant.types.PropertySet;
46 import org.apache.tools.ant.util.FileUtils;
47
48 import com.idaremedia.antx.AntXFixture;
49 import com.idaremedia.antx.AssertableTask;
50 import com.idaremedia.antx.Iteration;
51 import com.idaremedia.antx.helpers.Tk;
52 import com.idaremedia.antx.ownhelpers.LocalTk;
53 import com.idaremedia.antx.starters.StringItemListHandle;
54
55 /**
56  * Skeleton starter for tasks that create or copy file system objects. Implements
57  * the common "copy prototype" functionality.
58  *
59  * @since JWare/AntX 0.3 (Extracted from MkTempObject)
60  * @author ssmc, &copy;2003-2004 <a HREF="http://www.jware.info">iDare&nbsp;Media,&nbsp;Inc.</a>
61  * @version 0.5
62  * @.safety single
63  * @.group impl,helper
64  * @.todo Support for classpath when specifying copy-source resource
65  **/

66
67 public abstract class MkNewObject extends AssertableTask
68 {
69     /**
70      * Initializes a new MkNewObject instance.
71      **/

72     protected MkNewObject(String JavaDoc iam)
73     {
74         super(iam);
75     }
76
77
78     /**
79      * Sets the property into which a URL representation of the
80      * temp directory's path is copied.
81      * @param urlproperty the property's name (non-null)
82      * @since JWare/AntX 0.5
83      **/

84     public void setUrlProperty(String JavaDoc urlproperty)
85     {
86         require_(urlproperty!=null,"setUrlProp- nonzro name");
87         m_updateUrlProperty = urlproperty;
88     }
89
90
91
92     /**
93      * Returns the name of the property into which a URL representation
94      * of the temp directory's path will be stored. Returns <i>null</i>
95      * if never set explicitly.
96      * @since JWare/AntX 0.5
97      **/

98     public final String JavaDoc getUrlPathProperty()
99     {
100         return m_updateUrlProperty;
101     }
102
103
104     /**
105      * Returns <i>true</i> if this task will try to mark all created
106      * prototype copies as delete-on-exit. Returns <i>false</i> by
107      * default.
108      **/

109     public boolean isAutoDelete()
110     {
111         return false;
112     }
113
114
115     /**
116      * Sets this task's prototype source file.
117      * @param copyFrom prototype file's path (non-null)
118      * @see #getPrototypePlainFile
119      **/

120     public void setCopyFile(File JavaDoc copyFrom)
121     {
122         require_(copyFrom!=null,"setCopy- nonzro src file");
123         require_(copyFrom.canRead(), "setCopy- existing readable file/dir");
124         m_copyFromFile= copyFrom;
125     }
126
127
128     /**
129      * Returns this task's prototype source file. Returns
130      * <i>null</i> if never specified.
131      **/

132     public File JavaDoc getPrototypePlainFile()
133     {
134         return m_copyFromFile;
135     }
136
137
138     /**
139      * Sets this task's prototype class-based resource.
140      * @param copyFrom resource's name (non-null)
141      * @see #getPrototypeResourceFile
142      **/

143     public void setCopyResource(String JavaDoc copyFrom)
144     {
145         require_(!Tk.isWhitespace(copyFrom),"setCopyRez- nonzro rez name");
146         m_copyFromResource = copyFrom;
147     }
148
149
150     /**
151      * Returns this task's prototype class-based resource. Returns
152      * <i>null</i> if never specified.
153      **/

154     public String JavaDoc getPrototypeResource()
155     {
156         return m_copyFromResource;
157     }
158
159
160     /**
161      * Returns this task's prototype resource's actual file.
162      * Returns <i>null</i> if never defined. All prototype resources
163      * must resolve to physical files.
164      * @throws BuildException if cannot do conversion (or resource is
165      * not a file)
166      **/

167     public File JavaDoc getPrototypeResourceFile()
168     {
169         if (m_copyFromRezFile==null && getPrototypeResource()!=null) {
170             File JavaDoc rezfile = getFileFromResource(getPrototypeResource());
171             m_copyFromRezFile = rezfile;
172         }
173         return m_copyFromRezFile;
174     }
175
176
177     /**
178      * Adds a new filterset to use when copying prototype files.
179      * @since JWare/AntX 0.2
180      **/

181     public void addFilterSet(FilterSet filters)
182     {
183         require_(filters!=null,"addFiltrs- nonzro filtrs");
184         getCopyFiltersNoNull().addFilterSet(filters);
185     }
186
187
188     /**
189      * Returns <i>true</i> if either a prototype file or prototype
190      * resource has been defined.
191      * @.sideeffect Will convert prototype resource name into actual file
192      **/

193     protected final boolean needToCopyFile()
194     {
195         return (getPrototypePlainFile()!=null ||
196                 getPrototypeResourceFile()!=null);
197     }
198
199
200     /**
201      * Converts a named class resource to a filesystem entity.
202      * @throws BuildException if cannot do conversion (or resource is
203      * not a file)
204      **/

205     protected final File JavaDoc getFileFromResource(String JavaDoc resource)
206         throws BuildException
207     {
208         require_(resource!=null,"rezToFile- nonzro rez");
209
210         File JavaDoc rezfile = null;
211         URL JavaDoc url = LocalTk.getSystemResource(resource,getProject());
212         if (url!=null) {
213             rezfile = Tk.toFile(url);
214             if (rezfile!=null && !rezfile.canRead()) {
215                 rezfile=null;
216             }
217         }
218         if (rezfile==null) {
219             String JavaDoc ermsg = uistrs().get("mktemp.cant.read.resource",resource);
220             log(ermsg, Project.MSG_ERR);
221             throw new BuildException(ermsg,getLocation());
222         }
223         return rezfile;
224     }
225
226
227     /**
228      * Copies the prototype file to a target directory. Any defined
229      * filters are automatically applied to the new destination file. Will
230      * mark new file for deletion-on-exit if {@linkplain #isAutoDelete
231      * isAutoDelete} returns <i>true</i>.
232      * @param fromFile source prototype file (non-null)
233      * @param inDir target directory (non-null, must exist)
234      * @throws IOException if unable to copy file
235      **/

236     protected File JavaDoc copyPrototypeFile(File JavaDoc fromFile, File JavaDoc inDir)
237         throws IOException JavaDoc
238     {
239         File JavaDoc toFile = new File JavaDoc(inDir, fromFile.getName());
240
241         getFileUtils().copyFile(fromFile,toFile,getCopyFilters(),false);
242
243         if (isAutoDelete()) {
244             toFile.deleteOnExit();
245         }
246         return toFile;
247     }
248
249
250
251     /**
252      * Returns this task's pre-allocated Ant file utilities helper.
253      **/

254     protected final FileUtils getFileUtils()
255     {
256         return AntXFixture.fileUtils();
257     }
258
259
260     /**
261      * Returns this task's underlying filterset collection. Will
262      * return <i>null</i> if no filters ever added.
263      * @.safety single
264      **/

265     protected final FilterSetCollection getCopyFilters()
266     {
267         return m_copyFilters;
268     }
269
270
271     /**
272      * Returns this task's underlying filterset collection
273      * creating a new empty collection if necessary.
274      * @.safety single
275      **/

276     protected final FilterSetCollection getCopyFiltersNoNull()
277     {
278         if (m_copyFilters==null) {
279             m_copyFilters = new FilterSetCollection();
280         }
281         return m_copyFilters;
282     }
283
284
285     /**
286      * Returns this task's list of prototype file lines creating
287      * a new empty list if necessary. Contents of this list must
288      * be either InnerStrings, Strings, or some other stringifiable
289      * object.
290      * @since JWare/AntX 0.3
291      **/

292     protected List JavaDoc getPrototypeLinesNoNull()
293     {
294         if (m_prototypeLines==null) {
295             m_prototypeLines = AntXFixture.newList();
296         }
297         return m_prototypeLines;
298     }
299
300
301     /**
302      * Returns this task's list of prototype file line contents.
303      * Will return <i>null</i> if not lines added to this task.
304      * @since JWare/AntX 0.3
305      **/

306     protected List JavaDoc getPrototypeLines()
307     {
308         return m_prototypeLines;
309     }
310
311
312     /**
313      * Copies this task's list of prototype file line contents
314      * to existing file. Does nothing if no prototype lines defined.
315      * @param newFile the target file (non-null)
316      * @param append <i>true</i> if lines should be appended
317      * @since JWare/AntX 0.3
318      * @throws BuildException if any I/O error occurs or lines improperly
319      * defined.
320      **/

321     protected void copyPrototypeLines(File JavaDoc newFile, boolean append)
322     {
323         List JavaDoc l = getPrototypeLines();
324         if (l!=null && !l.isEmpty()) {
325             try {
326                 final Project P = getProject();
327                 FileOutputStream JavaDoc fos = newFOS(newFile,append);
328                 PrintWriter JavaDoc w = new PrintWriter JavaDoc(fos);
329                 for (int i=0,N=l.size();i<N;i++) {
330                     Object JavaDoc o = l.get(i);
331                     if (o instanceof StringItemListHandle) {
332                         Iterator JavaDoc itr= ((StringItemListHandle)o).readonlyStringIterator(P);
333                         while (itr.hasNext()) {
334                             w.println(itr.next().toString());
335                         }
336                     } else if (o instanceof PropertySet) {
337                         Properties JavaDoc ps = ((PropertySet)o).getProperties();
338                         if (!ps.isEmpty()) {
339                             w.flush();
340                             ps.store(fos,null);
341                         }
342                         ps.clear();
343                         ps=null;//gc
344
} else {
345                         w.println(Iteration.lenientStringifer().stringFrom(o,P));
346                     }
347                 }
348                 w.flush();
349                 w.close();
350             } catch(IOException JavaDoc iox) {
351                 throw new BuildException(iox,getLocation());
352             }
353         }
354     }
355
356
357
358     /**
359      * Apply any common update properties to final file system object.
360      * @param finalObject file system object (non-null)
361      * @param strict <i>true</i> if should fail if unable to set update properties
362      * @since JWare/AntX 0.5
363      **/

364     protected void saveFinalPath(File JavaDoc finalObject, boolean strict)
365     {
366         if (getUrlPathProperty()!=null) {
367             checkIfProperty_(getUrlPathProperty(),!strict);
368             String JavaDoc urlPath = AntXFixture.fileUtils().toURI(finalObject.getPath());
369             getProject().setNewProperty(getUrlPathProperty(),urlPath);
370         }
371     }
372
373
374
375     /**
376      * Create a FileOutputStream with custom append option if active
377      * JVM supports it.
378      **/

379     private FileOutputStream JavaDoc newFOS(File JavaDoc newFile, boolean append)
380         throws IOException JavaDoc
381     {
382         if (append) {
383             try {
384                 Class JavaDoc[] sig = new Class JavaDoc[]{File JavaDoc.class,boolean.class};
385                 Constructor JavaDoc ctor = FileOutputStream JavaDoc.class.getConstructor(sig);
386                 Object JavaDoc[] args = new Object JavaDoc[]{newFile, (append ? Boolean.TRUE : Boolean.FALSE)};
387                 return (FileOutputStream JavaDoc)ctor.newInstance(args);
388             } catch(Exception JavaDoc anyX) {/*burp*/}
389         }
390         return new FileOutputStream JavaDoc(newFile);
391     }
392
393     private File JavaDoc m_copyFromFile, m_copyFromRezFile;
394     private String JavaDoc m_copyFromResource;
395     private FilterSetCollection m_copyFilters;
396     private List JavaDoc m_prototypeLines;
397     private String JavaDoc m_updateUrlProperty;
398 }
399
400 /* end-of-MkNewObject.java */
401
Popular Tags