001 package de.mospace.lang;
002
003 import java.io.File;
004 import java.io.Serializable;
005 import java.io.IOException;
006 import java.net.MalformedURLException;
007 import java.net.URI;
008 import java.net.URISyntaxException;
009 import java.net.URL;
010 import java.net.URLClassLoader;
011 import java.util.HashSet;
012 import java.util.List;
013 import java.util.Set;
014 import java.util.Vector;
015
016 /** A fully functional implementation of the {@link ClassLoaderProvider}
017 * interface. Libraries can be registered with a DefaultClassLoaderProvider
018 * and class loaders that look for class files in these libraries
019 * can be obtained with the {@link #getClassLoader} method. **/
020 public class DefaultClassLoaderProvider extends MinimalClassLoaderProvider implements Serializable{
021 /** serialization version id */
022 public static final long serialVersionUID = -7115012927531022705L;
023 /** The parent class loader for class loaders returned by future
024 * calls to {@link #getClassLoader}.
025 */
026 private transient ClassLoader classloader; //we don't want to store the class loader itself
027
028 /** A set of URLs containing the jar files and directories in the class
029 * path of the last class loader. */
030 private final Set jars = new HashSet();
031
032 /** A set of URLs containing newly registered jar files and directories. */
033 private final Set newJars = new HashSet(); //can't make this transient because it's final
034
035 /** Constructs a new ClassLoaderProvider whose {@link #getClassLoader}
036 * method will return class loaders that finally delegate to
037 * the system class loader.
038 **/
039 public DefaultClassLoaderProvider(){
040 classloader = ClassLoader.getSystemClassLoader();
041 }
042
043 /** Constructs a new ClassLoaderProvider whose {@link #getClassLoader}
044 * method will return class loaders that finally delegate to
045 * the specified class loader.
046 * @param parent the delegating-parent for all class loaders returned
047 * by this ClassLoaderProvider's {@link #getClassLoader} method, may be
048 * <code>null</code>.
049 **/
050 public DefaultClassLoaderProvider(ClassLoader parent){
051 classloader = parent;
052 }
053
054 /** Tries to determine the directory that is or that contains the
055 * class path element from which the specified class has been loaded.
056 * @param klass a class loaded from the local file system
057 * @throws IllegalArgumentException if the repository root of the
058 * specified class is not a file.
059 */
060 public static File getRepositoryRootDir(Class klass){
061 File f = new File(getRepositoryRoot(klass));
062 return (f == null || f.isDirectory())? f : f.getAbsoluteFile().getParentFile();
063 }
064
065 /** Tries to determine the class path
066 * element from which the specified class has been loaded.
067 * @param klass a non-null class object
068 * @return the URI of the class path element from which <code>klass</code>
069 * has been loaded
070 **/
071 public static URI getRepositoryRoot(Class klass){
072 /* Constructs the resource name for this Class by replacing
073 dots with slashes, prepending a slash, and appending the
074 .class extension */
075 String resourceName =
076 "/" + klass.getName().replaceAll("\\.","/") + ".class";
077 /* gets the resource for the class resource name as an url */
078 URL classResource = klass.getResource(resourceName);
079 /* deletes the resource name from the class resource url
080 * and thus extracts the class repository url
081 */
082 String s_resource = classResource.toString().replaceFirst("\\Q"+resourceName+"\\E$","");
083 /* deletes a leading "jar:" as well as the first occurrance of "!$"
084 * from the class repository url */
085 s_resource = s_resource.replaceFirst("^jar:","").replaceFirst("!$","");
086 ///* extracts the directory part of the class repository url */
087 //s_resource = s_resource.substring(0,s_resource.lastIndexOf("/"));
088 URI result = null;
089 try{
090 /* tries to construct a new File for the directory part of the
091 * class repository url */
092 result = new URI(s_resource);
093 } catch (URISyntaxException ignore){
094 throw new Error(ignore);
095 }
096 return result;
097 }
098
099 /** Determines whether the path of the specified file starts with
100 * the directory specified in the Java system property
101 * java.io.tmpdir.
102 * @param file a non-null file object
103 * @return whether the specified file resides in the java temporary
104 * directory or one of its sub-directories
105 * @see java.lang.System#getProperty
106 **/
107 public static boolean isTemporary(File file){
108 boolean result = false;
109 try{
110 String tempdir = System.getProperty("java.io.tmpdir");
111 if(tempdir != null && tempdir.length() != 0){
112 tempdir = (new File(tempdir)).getCanonicalPath();
113 result = file.getCanonicalPath().startsWith(tempdir);
114 }
115 } catch (IOException ignore){
116 result = false;
117 }
118 return result;
119 }
120
121 /** Returns all libraries that have been registered with this
122 * ClassLoaderProvider, so far.
123 * @return an array containing the URLs of all libraries registered with
124 * this ClassLoaderProvider.
125 **/
126 public final synchronized URL[] getLibraries(){
127 updateClassLoader();
128 return (URL[]) jars.toArray(new URL[jars.size()]);
129 }
130
131 /** Returns the library files that have been registered with this
132 * ClassLoaderProvider, so far.
133 * @return an array containing the library files registered with
134 * this ClassLoaderProvider.**/
135 public final synchronized File[] getLibraryFiles(){
136 URL[] urls = getLibraries();
137 List jarFiles = new Vector(urls.length);
138 for(int i=0; i<urls.length; i++){
139 try{
140 jarFiles.add(new File(new URI(urls[i].toString())));
141 } catch (URISyntaxException ex){
142 throw new Error(ex);
143 }
144 }
145 return (File[]) jarFiles.toArray(new File[jarFiles.size()]);
146 }
147
148 /** Returns a class loader that looks for class files in all libraries
149 * that have been successfully registered with this ClassLoaderProvider,
150 * so far.
151 * Subsequent calls to this method will return the same class loader
152 * or class loaders that delegate to all class loaders previously returned.
153 * @return a ClassLoader that looks for class files in all successfully
154 * registered libraries.
155 */
156 public final synchronized ClassLoader getClassLoader(){
157 return updateClassLoader();
158 }
159
160 /** Requests that the specified jar file be registered, so that it is
161 * in the class path of all class loaders returned by future calls to
162 * {@link #getClassLoader}.
163 * @param jarFile a jar archive with Java class files
164 * @return true if the library had not been registered before and
165 * was successfully registered with this ClassLaoderProvider.
166 * @throws IllegalArgumentException if jarFile does not exist
167 * or is not a jar file
168 **/
169 public final synchronized boolean registerLibrary(File jarFile){
170 super.registerLibrary(jarFile); //will throw the required Exceptions
171 return addLib(jarFile);
172 }
173
174 /** Requests that the specified jar files be registered, so that they are
175 * in the class path of all class loaders returned by future calls to
176 * {@link #getClassLoader}.
177 * @param jarFiles an array of jar archives with Java class files
178 * @return true if at least one jarFile was newly registered
179 **/
180 public final synchronized boolean registerLibraries(File[] jarFiles){
181 boolean result = false;
182 for(int i = 0; i<jarFiles.length; i++){
183 result = addLib(jarFiles[i]) || result;
184 }
185 return result;
186 }
187
188 /** Requests that all jar files in the specified directory be
189 * registered, so that they are in the class path of all class loaders
190 * returned by future calls to
191 * {@link #getClassLoader}.
192 * @param dir a directory with jar archives. The client must assure that
193 * dir exists and is a directory. dir may contain non-jar files
194 * @return true if there was at least one jar archive in <code>dir</code>,
195 * for wich the request was honored.
196 * @throws IllegalArgumentException if <code>dir</code> is not a directory
197 */
198 public final synchronized boolean registerLibraryDirectory(File dir){
199 super.registerLibraryDirectory(dir); //will throw the right Exceptions
200 return addLibDir(dir);
201 }
202
203 /** Requests that all jar files in the specified directories be
204 * registered, so that they are in the class path of all class loaders
205 * returned by future calls to {@link #getClassLoader}.
206 * Non-directory files in <code>dirs</code> will be ignored.
207 * @param dirs an array of directories with jar archives
208 * @return true if there was at least one jar archive in <code>dirs</code>,
209 * for wich the request was honored.
210 **/
211 public final synchronized boolean registerLibraryDirectories(File[] dirs){
212 boolean result = false;
213 for(int i=0; i < dirs.length; i++){
214 if(dirs[i].isDirectory()){
215 result = registerLibraryDirectory(dirs[i]) || result;
216 }
217 }
218 return result;
219 }
220
221 /** Requests that the specified directory be
222 * registered, so that it is on the class path of all class loaders
223 * returned by future calls to {@link #getClassLoader}.
224 * @param dir a non-null directory with Java class files
225 * @return true if the directory was newly registered
226 **/
227 public final synchronized boolean registerDirectory(File dir){
228 boolean result = false;
229 if (dir.isDirectory()){
230 try{
231 URL newURL = dir.toURI().toURL();
232 if(! jars.contains(newURL) ){
233 //System.out.println("adding " + newURL);
234 result = newJars.add(newURL);
235 }
236 } catch (MalformedURLException ex){
237 IllegalArgumentException ex2 = new IllegalArgumentException(ex.getMessage());
238 ex2.initCause(ex);
239 throw ex2;
240 }
241 }
242 return result;
243 }
244
245 /** Requests that the specified jar file be registered, so that it is
246 * in the class path of all class loaders returned by future calls to
247 * {@link #getClassLoader}.
248 * @param jarFile a jar archive with Java class files
249 * @return true if the library had not been registered before and
250 * was successfully registered with this ClassLaoderProvider.
251 **/
252 private final boolean addLib(File jar){
253 boolean result = false;
254 if (jar.isFile() && jar.getName().endsWith(".jar")){
255 try{
256 URL newURL = jar.toURI().toURL();
257 if(! jars.contains(newURL) ){
258 //System.out.println("adding " + newURL);
259 result = newJars.add(newURL);
260 }
261 } catch (MalformedURLException ex){
262 IllegalArgumentException ex2 = new IllegalArgumentException(ex.getMessage());
263 ex2.initCause(ex);
264 throw ex2;
265 }
266 }
267 return result;
268 }
269
270 /** Requests that all jar files in the specified directory be
271 * registered, so that they are in the class path of all class loaders
272 * returned by future calls to
273 * {@link #getClassLoader}.
274 * @param dir a directory with jar archives. The client must assure that
275 * dir exists and is a directory. dir may contain non-jar files
276 * @return true if there was at least one jar archive in
277 * <code>libDir</code>, for wich the request was honored.
278 */
279 private final boolean addLibDir(File libDir){
280 boolean result = false;
281 if(libDir.isDirectory()){
282 File[] libs = libDir.listFiles();
283 for(int i=0; i<libs.length; i++){
284 result = addLib(libs[i]) || result;
285 }
286 }
287 return result;
288 }
289
290 /** Updates the classloader member if new libraries have been
291 * registered.
292 */
293 private final ClassLoader updateClassLoader(){
294 if (!newJars.isEmpty()){
295 classloader = new URLClassLoader(
296 (URL[]) newJars.toArray(new URL[newJars.size()]), classloader );
297 jars.addAll(newJars);
298 newJars.clear();
299 //System.out.println(Arrays.asList(((URLClassLoader) classloader).getURLs()));
300 }
301 return classloader;
302 }
303
304 /** Serialization. */
305 private void writeObject(java.io.ObjectOutputStream out)
306 throws IOException{
307 updateClassLoader();
308 out.defaultWriteObject();
309 }
310
311 /** De-serialization. */
312 private void readObject(java.io.ObjectInputStream in)
313 throws IOException, ClassNotFoundException{
314 in.defaultReadObject();
315 if(jars.isEmpty()){
316 classloader = new URLClassLoader(
317 (URL[]) newJars.toArray(new URL[newJars.size()]), classloader );
318 }
319 }
320 }