KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > oddjob > launch > Locator


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2003 The Apache Software Foundation. All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if
20  * any, must include the following acknowlegement:
21  * "This product includes software developed by the
22  * Apache Software Foundation (http://www.apache.org/)."
23  * Alternately, this acknowlegement may appear in the software itself,
24  * if and wherever such third-party acknowlegements normally appear.
25  *
26  * 4. The names "Ant" and "Apache Software
27  * Foundation" must not be used to endorse or promote products derived
28  * from this software without prior written permission. For written
29  * permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache"
32  * nor may "Apache" appear in their names without prior written
33  * permission of the Apache Group.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation. For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  */

54 package org.oddjob.launch;
55
56 import java.net.MalformedURLException JavaDoc;
57
58 import java.net.URL JavaDoc;
59 import java.io.File JavaDoc;
60 import java.io.FilenameFilter JavaDoc;
61 import java.text.CharacterIterator JavaDoc;
62 import java.text.StringCharacterIterator JavaDoc;
63
64 /**
65  * The Locator is a utility class which is used to find certain items
66  * in the environment
67  *
68  * @author Conor MacNeill
69  * @since Ant 1.6
70  */

71 public final class Locator {
72     /**
73      * Not instantiable
74      */

75     private Locator() {
76     }
77
78     /**
79      * Find the directory or jar file the class has been loaded from.
80      *
81      * @param c the class whose location is required.
82      * @return the file or jar with the class or null if we cannot
83      * determine the location.
84      *
85      * @since Ant 1.6
86      */

87     public static File JavaDoc getClassSource(Class JavaDoc c) {
88         String JavaDoc classResource = c.getName().replace('.', '/') + ".class";
89         return getResourceSource(c.getClassLoader(), classResource);
90     }
91
92     /**
93      * Find the directory or jar a give resource has been loaded from.
94      *
95      * @param c the classloader to be consulted for the source
96      * @param resource the resource whose location is required.
97      *
98      * @return the file with the resource source or null if
99      * we cannot determine the location.
100      *
101      * @since Ant 1.6
102      */

103     public static File JavaDoc getResourceSource(ClassLoader JavaDoc c, String JavaDoc resource) {
104         if (c == null) {
105             c = Locator.class.getClassLoader();
106         }
107
108         URL JavaDoc url = c.getResource(resource);
109         if (url != null) {
110             String JavaDoc u = url.toString();
111             if (u.startsWith("jar:file:")) {
112                 int pling = u.indexOf("!");
113                 String JavaDoc jarName = u.substring(4, pling);
114                 return new File JavaDoc(fromURI(jarName));
115             } else if (u.startsWith("file:")) {
116                 int tail = u.indexOf(resource);
117                 String JavaDoc dirName = u.substring(0, tail);
118                 return new File JavaDoc(fromURI(dirName));
119             }
120         }
121         return null;
122     }
123
124     /**
125      * Constructs a file path from a <code>file:</code> URI.
126      *
127      * <p>Will be an absolute path if the given URI is absolute.</p>
128      *
129      * <p>Swallows '%' that are not followed by two characters,
130      * doesn't deal with non-ASCII characters.</p>
131      *
132      * @param uri the URI designating a file in the local filesystem.
133      * @return the local file system path for the file.
134      * @since Ant 1.6
135      */

136     public static String JavaDoc fromURI(String JavaDoc uri) {
137         if (!uri.startsWith("file:")) {
138             throw new IllegalArgumentException JavaDoc("Can only handle file: URIs");
139         }
140         if (uri.startsWith("file://")) {
141             uri = uri.substring(7);
142         } else {
143             uri = uri.substring(5);
144         }
145
146         uri = uri.replace('/', File.separatorChar);
147         if (File.pathSeparatorChar == ';' && uri.startsWith("\\") && uri.length() > 2
148             && Character.isLetter(uri.charAt(1)) && uri.lastIndexOf(':') > -1) {
149             uri = uri.substring(1);
150         }
151
152         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
153         CharacterIterator JavaDoc iter = new StringCharacterIterator JavaDoc(uri);
154         for (char c = iter.first(); c != CharacterIterator.DONE;
155              c = iter.next()) {
156             if (c == '%') {
157                 char c1 = iter.next();
158                 if (c1 != CharacterIterator.DONE) {
159                     int i1 = Character.digit(c1, 16);
160                     char c2 = iter.next();
161                     if (c2 != CharacterIterator.DONE) {
162                         int i2 = Character.digit(c2, 16);
163                         sb.append((char) ((i1 << 4) + i2));
164                     }
165                 }
166             } else {
167                 sb.append(c);
168             }
169         }
170
171         String JavaDoc path = sb.toString();
172         return path;
173     }
174
175
176     /**
177      * Get the File necessary to load the Sun compiler tools. If the classes
178      * are available to this class, then no additional URL is required and
179      * null is returned. This may be because the classes are explicitly in the
180      * class path or provided by the JVM directly
181      *
182      * @return the tools jar as a File if required, null otherwise
183      */

184     public static File JavaDoc getToolsJar() {
185         // firstly check if the tools jar is already in the classpath
186
boolean toolsJarAvailable = false;
187
188         try {
189             // just check whether this throws an exception
190
Class.forName("com.sun.tools.javac.Main");
191             toolsJarAvailable = true;
192         } catch (Exception JavaDoc e) {
193             try {
194                 Class.forName("sun.tools.javac.Main");
195                 toolsJarAvailable = true;
196             } catch (Exception JavaDoc e2) {
197                 // ignore
198
}
199         }
200
201         if (toolsJarAvailable) {
202             return null;
203         }
204
205         // couldn't find compiler - try to find tools.jar
206
// based on java.home setting
207
String JavaDoc javaHome = System.getProperty("java.home");
208         if (javaHome.endsWith("jre")) {
209             javaHome = javaHome.substring(0, javaHome.length() - 4);
210         }
211         File JavaDoc toolsJar = new File JavaDoc(javaHome + "/lib/tools.jar");
212         if (!toolsJar.exists()) {
213             System.out.println("Unable to locate tools.jar. "
214                  + "Expected to find it in " + toolsJar.getPath());
215             return null;
216         }
217         return toolsJar;
218     }
219
220     /**
221      * Get an array or URLs representing all of the jar files in the
222      * given location. If the location is a file, it is returned as the only
223      * element of the array. If the location is a directory, it is scanned for
224      * jar files
225      *
226      * @param location the location to scan for Jars
227      *
228      * @return an array of URLs for all jars in the given location.
229      *
230      * @exception MalformedURLException if the URLs for the jars cannot be
231      * formed
232      */

233     public static URL JavaDoc[] getLocationURLs(File JavaDoc location)
234          throws MalformedURLException JavaDoc {
235         return getLocationURLs(location, new String JavaDoc[]{".jar"});
236     }
237
238     /**
239      * Get an array or URLs representing all of the files of a given set of
240      * extensions in the given location. If the location is a file, it is
241      * returned as the only element of the array. If the location is a
242      * directory, it is scanned for matching files
243      *
244      * @param location the location to scan for files
245      * @param extensions an array of extension that are to match in the
246      * directory search
247      *
248      * @return an array of URLs of matching files
249      * @exception MalformedURLException if the URLs for the files cannot be
250      * formed
251      */

252     public static URL JavaDoc[] getLocationURLs(File JavaDoc location,
253                                         final String JavaDoc[] extensions)
254          throws MalformedURLException JavaDoc {
255         URL JavaDoc[] urls = new URL JavaDoc[0];
256
257         if (!location.exists()) {
258             return urls;
259         }
260
261         if (!location.isDirectory()) {
262             urls = new URL JavaDoc[1];
263             String JavaDoc path = location.getPath();
264             for (int i = 0; i < extensions.length; ++i) {
265                 if (path.toLowerCase().endsWith(extensions[i])) {
266                     urls[0] = location.toURL();
267                     break;
268                 }
269             }
270             return urls;
271         }
272
273         File JavaDoc[] matches = location.listFiles(
274             new FilenameFilter JavaDoc() {
275                 public boolean accept(File JavaDoc dir, String JavaDoc name) {
276                     for (int i = 0; i < extensions.length; ++i) {
277                         if (name.toLowerCase().endsWith(extensions[i])) {
278                             return true;
279                         }
280                     }
281                     return false;
282                 }
283             });
284
285         urls = new URL JavaDoc[matches.length];
286         for (int i = 0; i < matches.length; ++i) {
287             urls[i] = matches[i].toURL();
288         }
289         return urls;
290     }
291 }
292
293
Popular Tags