KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > idaremedia > antx > ownhelpers > LocalTk


1 /**
2  * $Id: LocalTk.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.ownhelpers;
30
31 import java.lang.reflect.Constructor JavaDoc;
32 import java.lang.reflect.Method JavaDoc;
33 import java.io.File JavaDoc;
34 import java.io.InputStream JavaDoc;
35 import java.net.URL JavaDoc;
36
37 import org.apache.tools.ant.BuildEvent;
38 import org.apache.tools.ant.BuildException;
39 import org.apache.tools.ant.DirectoryScanner;
40 import org.apache.tools.ant.Location;
41 import org.apache.tools.ant.Project;
42 import org.apache.tools.ant.launch.Locator;
43 import org.apache.tools.ant.types.Reference;
44 import org.apache.tools.ant.util.ClasspathUtils;
45 import org.apache.tools.ant.util.FileUtils;
46
47 import com.idaremedia.antx.AntX;
48 import com.idaremedia.antx.AntXFixture;
49 import com.idaremedia.antx.Iteration;
50 import com.idaremedia.antx.apis.ScriptLocatable;
51 import com.idaremedia.antx.helpers.Tk;
52
53 /**
54  * Collection of independent but AntX-specific utility methods. These utilities can
55  * use classes from the root-level 'helpers' and 'antx' packages only.
56  *
57  * @since JWare/AntX 0.4
58  * @author ssmc, &copy;2004 <a HREF="http://www.jware.info">iDare&nbsp;Media,&nbsp;Inc.</a>
59  * @version 0.5
60  * @.safety multiple
61  * @.group impl,helper
62  **/

63
64 public final class LocalTk
65 {
66     private static final String JavaDoc IAM_= AntX.AntX+"LocalTk:";
67
68
69     /**
70      * Factory method that calls the right constructor based on active
71      * Ant runtime. Before Ant 1.6.3, a reference's project was determined
72      * by each API; post 1.6.2 you must pass in the project at construction.
73      * @param refid the reference id (non-null)
74      * @param project the owning project of reference (non-null)
75      * @return new reference (never <i>null</i>)
76      * @since JWare/AntX 0.5
77      **/

78     public static final Reference referenceFor(String JavaDoc refid, Project project)
79     {
80         return new Reference(refid);
81     }
82
83
84     /**
85      * Like {@linkplain #referenceFor referenceFor(refid,project)} but
86      * where the new reference is based on any existing object. Useful
87      * from constructors and clone methods.
88      * @param ref existing reference (non-null)
89      * @return new reference (never <i>null</i>)
90      * @since JWare/AntX 0.5
91      **/

92     public static final Reference referenceFor(Reference ref)
93     {
94         return referenceFor(ref.getRefId(),null/*until require 1.6.3*/);
95     }
96
97
98
99     /**
100      * Used as loaderId to cache and reuse project-based class loaders.
101      **/

102     private static final String JavaDoc ANTX_SYSLOADER_ =
103         AntX.ANTX_INTERNAL_ID+"SystemResourcesClassLoader";
104
105
106     /**
107      * Tries to load a "system" resource from within Ant environment. This
108      * method uses an Ant runtime class loader to load resource to avoid
109      * all of the issues Ant vs. JUnit vs. Eclipse vs. Universe+Dog seem to
110      * trigger on occasion. Replaces typical calls to
111      * <span class="src">ClassLoader.getSystemResource()</span>.
112      * @param resource resource to be loaded (not-null, not-class)
113      * @param P project on whose behalf resource loading performed
114      * @return resource URL or <i>null</i> if cannot find resource.
115      **/

116     public static final URL JavaDoc getSystemResource(String JavaDoc resource, Project P)
117     {
118         AntX.require_(P!=null,IAM_,"getSysRez- nonzro project");
119         AntX.require_(resource!=null,IAM_,"getSysRez- nonzro resource");
120
121         ClassLoader JavaDoc cL = ClasspathUtils.getClassLoaderForPath
122             (P, null/*systempath*/, ANTX_SYSLOADER_, false, true);
123
124         return cL.getResource(resource);
125     }
126
127
128
129     /**
130      * Like {@linkplain #getSystemResource getSystemResource(&#8230;)} but
131      * returns resource as an input stream.
132      * @param resource resource to be opened (not-null, not-class)
133      * @param P project on whose behalf resource loading performed
134      * @return resource stream or <i>null</i> if cannot find resource
135      */

136     public static final InputStream JavaDoc getSystemResourceAsStream
137         (String JavaDoc resource, Project P)
138     {
139         AntX.require_(P!=null,IAM_,"getSysRez- nonzro project");
140         AntX.require_(resource!=null,IAM_,"getSysRez- nonzro resource");
141
142         ClassLoader JavaDoc cL = ClasspathUtils.getClassLoaderForPath
143             (P, null/*systempath*/, ANTX_SYSLOADER_, false, true);
144
145         return cL.getResourceAsStream(resource);
146     }
147
148
149
150     /**
151      * Returns location of a named system resource. Will return <i>null</i>
152      * if unable to locate resource. Like Ant's Locator method but using
153      * our class loader.
154      * @param resource resource to be loaded (not-null, not-class)
155      * @param P project on whose behalf resource loading performed
156      * @return resource's directory or <i>null</i> if cannot find resource.
157      * @since JWare/AntX 0.5
158      **/

159     public static final File JavaDoc getSystemResourceSource(String JavaDoc resource, Project P)
160     {
161         URL JavaDoc url = getSystemResource(resource,P);
162         return getFilesystemSource(url,resource,P);
163     }
164
165
166
167     /**
168      * Like {@linkplain #getSystemResource getSystemResource(&#8230;)}
169      * but for an arbitrary resource with a custom class path.
170      * @param resource the resource to locate (non-null)
171      * @param pathref the classpath to use (if null, system classpath used)
172      * @param project the project on whose behalf resource loading done (non-null)
173      * @return resource's URL or <i>null</i> if cannot locate resource.
174      **/

175     public static final URL JavaDoc getResource(String JavaDoc resource, String JavaDoc pathref,
176         Project project)
177     {
178         if (pathref==null) {
179             return getSystemResource(resource,project);
180         }
181         AntX.require_(project!=null,IAM_,"getRez- nonzro project");
182         AntX.require_(resource!=null,IAM_,"getRez- nonzro resource");
183
184         ClassLoader JavaDoc cL = ClasspathUtils.getClassLoaderForPath
185                             (project, referenceFor(pathref, project), false);
186         return cL.getResource(resource);
187     }
188
189
190
191     /**
192      * Like {@linkplain #getSystemResourceAsStream getSystemResourceAsStream(&#8230;)}
193      * but for an arbitrary resource with a custom class path.
194      * @param resource the resource to locate (non-null)
195      * @param pathref the classpath to use (if null, system classpath used)
196      * @param project the project on whose behalf resource loading done (non-null)
197      * @return resource's URL or <i>null</i> if cannot locate resource.
198      **/

199     public static final InputStream JavaDoc getResourceAsStream(String JavaDoc resource,
200         String JavaDoc pathref, Project project)
201     {
202         if (pathref==null) {
203             return getSystemResourceAsStream(resource,project);
204         }
205         AntX.require_(project!=null,IAM_,"getRez- nonzro project");
206         AntX.require_(resource!=null,IAM_,"getRez- nonzro resource");
207
208         ClassLoader JavaDoc cL = ClasspathUtils.getClassLoaderForPath
209                             (project, referenceFor(pathref,project), false);
210         return cL.getResourceAsStream(resource);
211     }
212
213
214
215     /**
216      * Like {@linkplain #getSystemResourceSource getSystemResourceSource(&#8230;)}
217      * but for an arbitrary resource with a custom class path.
218      * @param resource the resource to locate (non-null)
219      * @param pathref the classpath to use (if null, system classpath used)
220      * @param project the project on whose behalf resource loading done (non-null)
221      * @return resource's URL or <i>null</i> if cannot locate resource.
222      **/

223     public static final File JavaDoc getResourceSource(String JavaDoc resource,
224         String JavaDoc pathref, Project project)
225     {
226         URL JavaDoc url = getResource(resource, pathref, project);
227         return getFilesystemSource(url, resource, project);
228     }
229
230
231
232     /**
233      * Returns location of a named system resource. Will return <i>null</i>
234      * if unable to locate resource. Like Ant's Locator method but using
235      * our class loader.
236      * @param url URL for resource to be translated to file (non-null)
237      * @param resource the resource's id as passed by application (non-null)
238      * @param P project on whose behalf resource loading performed
239      * @return resource's location as a file or <i>null</i> if cannot
240      * find resource.
241      * @since JWare/AntX 0.5
242      **/

243     public static final File JavaDoc getFilesystemSource(URL JavaDoc url, String JavaDoc resource, Project P)
244     {
245         /**
246          * Following snipped (verbatim) from Ant's Locator
247          * source to deal w/ jars.
248          */

249         if (url != null) {
250             String JavaDoc u = url.toString();
251             if (u.startsWith("jar:file:")) {
252                 int pling = u.indexOf("!");
253                 String JavaDoc jarName = u.substring(4, pling);
254                 return new File JavaDoc(Locator.fromURI(jarName));
255             } else if (u.startsWith("file:")) {
256                 int tail = u.indexOf(resource);
257                 String JavaDoc dirName = u.substring(0, tail);
258                 return new File JavaDoc(Locator.fromURI(dirName));
259             }
260         }
261         return null;
262     }
263
264
265
266     /**
267      * Ensures all file names from a directory scanner are
268      * fully-resolved absolute path names.
269      * @param filesOrDirs items to be resolved (non-null)
270      * @param dirscan the scanner resolution based on (non-null)
271      * @param basenameOnly <i>true</i> if only the items base
272      * names should be saved
273      * @since JWare/AntX 0.5
274      **/

275     public static final void resolveAllFilesOrDirs(String JavaDoc[] filesOrDirs,
276             DirectoryScanner dirscan, boolean basenameOnly)
277     {
278         FileUtils fileUtils = AntXFixture.fileUtils();
279         File JavaDoc wrt = dirscan.getBasedir();
280         for (int i=0;i<filesOrDirs.length;i++) {
281             File JavaDoc rf= fileUtils.resolveFile(wrt,filesOrDirs[i]);
282             if (basenameOnly) {
283                 filesOrDirs[i]= rf.getName();
284             } else {
285                 filesOrDirs[i]= rf.getAbsolutePath();
286             }
287         }
288     }
289
290
291
292     /**
293      * Creates a log message that is labeled w/ task|target if possible.
294      * @param e the event (non-null 'messageLogged' event)
295      * @since JWare/AntX 0.4
296      **/

297     public static final String JavaDoc purtyEventMsg(BuildEvent e)
298     {
299         if (e.getTask()!=null || e.getTarget()!=null) {
300             StringBuffer JavaDoc sb = new StringBuffer JavaDoc(e.getMessage().length()+50);
301             sb.append("[");
302             if (e.getTask()!=null) {
303                 sb.append(e.getTask().getTaskName());
304             } else {
305                 sb.append(e.getTarget().getName());
306             }
307             sb.append("] ");
308             sb.append(e.getMessage());
309             return sb.substring(0);
310         }
311         return e.getMessage();
312     }
313
314
315
316     /**
317      * Makes a Location string human-readable (manageable) if
318      * application's defaults allow it.
319      * @param l the location to be stringified (non-null)
320      * @since JWare/AntX 0.5
321      **/

322     public static String JavaDoc purtyLocation(Location l)
323     {
324         return Tk.shortStringFrom
325             (Iteration.defaultdefaults().isShortLocationsEnabled(),l);
326     }
327
328
329
330     /**
331      * Feedback helper that replaces one build exception with another
332      * one (usually script-specified). This method returns the old
333      * error if it is unable to create a new one for any reason. The
334      * newly generated exception is <em>always</em> a
335      * <span class="src">BuildException</em>; the incoming exception
336      * does not have to be.
337      * @param oldX the current exception (non-null)
338      * @param fallbackLoc location used if current exception has none
339      * @param newXclass the new build exception's class (non-null)
340      * @throws IllegalArgumentException if old exception or new class
341      * is <i>null</i>
342      * @since JWare/AntX 0.4
343      **/

344     public static Exception JavaDoc replaceError(Exception JavaDoc oldX,
345                                          Location fallbackLoc,
346                                          Class JavaDoc newXclass)
347     {
348         AntX.require_(oldX!=null && newXclass!=null,IAM_,
349                       "replErr- nonzro args");
350
351         Constructor JavaDoc ctor=null;
352         BuildException newX= null;
353         try {
354             if (!BuildException.class.isAssignableFrom(newXclass)) {
355                 return oldX;
356             }
357             Location loc;
358             if (oldX instanceof BuildException) {
359                 BuildException oldBX = (BuildException)oldX;
360                 loc = oldBX.getLocation();
361                 if (loc==Location.UNKNOWN_LOCATION) {
362                     if (oldBX.getCause() instanceof BuildException) {//only 1 down!
363
loc = ((BuildException)oldBX.getCause()).getLocation();
364                         if (loc==Location.UNKNOWN_LOCATION) {
365                             loc = fallbackLoc;
366                         }
367                     } else {
368                         loc = fallbackLoc;
369                     }
370                 }
371             } else if (oldX instanceof ScriptLocatable) {
372                 loc = ((ScriptLocatable)oldX).getLocation();
373                 if (loc==Location.UNKNOWN_LOCATION) {
374                     loc = fallbackLoc;
375                 }
376             } else {
377                 loc = fallbackLoc;
378             }
379             try {
380                 ctor = newXclass.getConstructor(AFE_SIG2);
381                 newX = (BuildException)ctor.newInstance
382                             (new Object JavaDoc[]{oldX.getMessage(),loc});
383             } catch(Exception JavaDoc igx) {
384                 ctor = newXclass.getConstructor(AFE_SIG1);
385                 newX = (BuildException)ctor.newInstance
386                             (new Object JavaDoc[]{oldX.getMessage()});
387             }
388             try {
389                 Method JavaDoc m= newXclass.getMethod("initCause",AFE_SIG0);
390                 m.invoke(newX, new Object JavaDoc[]{oldX});
391             } catch(Exception JavaDoc jre13X) {/*burp*/}
392         } catch(Exception JavaDoc anyX) {
393             /*burp*/
394         }
395         return (newX!=null) ? newX : oldX;
396     }
397
398
399
400     /**
401      * Feedback helper that replaces on build error with another
402      * (usually script specified) one.
403      * @param oldX the current exception (non-null)
404      * @param fallbackLoc location used if current exception has none
405      * @param newXclass the new exception's class name (non-null)
406      * @since JWare/AntX 0.4
407      **/

408     public static Exception JavaDoc replaceError(Exception JavaDoc oldX,
409                                          Location fallbackLoc,
410                                          String JavaDoc newXclass)
411     {
412         AntX.require_(oldX!=null && newXclass!=null, IAM_,
413                       "replErr- nonzro args");
414         try {
415             return replaceError(oldX,fallbackLoc,Class.forName(newXclass));
416         } catch(Exception JavaDoc anyX) {
417             return oldX;
418         }
419     }
420
421
422     /**
423      * Helper that tries to install a cause into a new Throwable
424      * using reflection instead of direct JRE 1.4 APIs.
425      * @param newerX the throwable to be updated (non-null)
426      * @param causeX the original boo-boo (non-null)
427      * @since JWare/AntX 0.4
428      **/

429     public static void tryInitCause(Throwable JavaDoc newerX, Throwable JavaDoc causeX)
430     {
431         AntX.require_(newerX!=null && causeX!=null, IAM_,
432                      "initCause- nonzro args");
433
434         try {
435             Method JavaDoc m= newerX.getClass().getMethod("initCause",AFE_SIG0);
436             m.invoke(newerX, new Object JavaDoc[]{causeX});
437         } catch(Exception JavaDoc jre13OrInitedX) {/*burp*/}
438     }
439
440
441     private static final Class JavaDoc[] AFE_SIG0= new Class JavaDoc[]{Throwable JavaDoc.class};
442     private static final Class JavaDoc[] AFE_SIG1= new Class JavaDoc[]{String JavaDoc.class};
443     private static final Class JavaDoc[] AFE_SIG2= new Class JavaDoc[]{String JavaDoc.class,Location.class};
444
445
446     /**
447      * Prevent; only public static utility methods.
448      **/

449     private LocalTk()
450     {
451     }
452 }
453
454 /* end-of-LocalTk.java */
455
Popular Tags