KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > bsh > BshClassManager


1 /*****************************************************************************
2  * *
3  * This file is part of the BeanShell Java Scripting distribution. *
4  * Documentation and updates may be found at http://www.beanshell.org/ *
5  * *
6  * Sun Public License Notice: *
7  * *
8  * The contents of this file are subject to the Sun Public License Version *
9  * 1.0 (the "License"); you may not use this file except in compliance with *
10  * the License. A copy of the License is available at http://www.sun.com *
11  * *
12  * The Original Code is BeanShell. The Initial Developer of the Original *
13  * Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
14  * (C) 2000. All Rights Reserved. *
15  * *
16  * GNU Public License Notice: *
17  * *
18  * Alternatively, the contents of this file may be used under the terms of *
19  * the GNU Lesser General Public License (the "LGPL"), in which case the *
20  * provisions of LGPL are applicable instead of those above. If you wish to *
21  * allow use of your version of this file only under the terms of the LGPL *
22  * and not to allow others to use your version of this file under the SPL, *
23  * indicate your decision by deleting the provisions above and replace *
24  * them with the notice and other provisions required by the LGPL. If you *
25  * do not delete the provisions above, a recipient may use your version of *
26  * this file under either the SPL or the LGPL. *
27  * *
28  * Patrick Niemeyer (pat@pat.net) *
29  * Author of Learning Java, O'Reilly & Associates *
30  * http://www.pat.net/~pat/ *
31  * *
32  *****************************************************************************/

33
34 package bsh;
35
36 import java.net.*;
37 import java.util.*;
38 import java.io.IOException JavaDoc;
39 import java.io.*;
40 import java.lang.reflect.Method JavaDoc;
41 import java.lang.reflect.Modifier JavaDoc;
42
43 /**
44     BshClassManager manages all classloading in BeanShell.
45     It also supports a dynamically loaded extension (bsh.classpath package)
46     which allows classpath extension and class file reloading.
47
48     Currently the extension relies on 1.2 for BshClassLoader and weak
49     references.
50
51     See http://www.beanshell.org/manual/classloading.html for details
52     on the bsh classloader architecture.
53     <p>
54
55     Bsh has a multi-tiered class loading architecture. No class loader is
56     used unless/until the classpath is modified or a class is reloaded.
57     <p>
58 */

59 /*
60     Implementation notes:
61
62     Note: we may need some synchronization in here
63
64     Note on version dependency: This base class is JDK 1.1 compatible,
65     however we are forced to use weak references in the full featured
66     implementation (the optional bsh.classpath package) to accomodate all of
67     the fleeting namespace listeners as they fall out of scope. (NameSpaces
68     must be informed if the class space changes so that they can un-cache
69     names).
70     <p>
71
72     Perhaps a simpler idea would be to have entities that reference cached
73     types always perform a light weight check with a counter / reference
74     value and use that to detect changes in the namespace. This puts the
75     burden on the consumer to check at appropriate times, but could eliminate
76     the need for the listener system in many places and the necessity of weak
77     references in this package.
78     <p>
79 */

80 public class BshClassManager
81 {
82     /** Identifier for no value item. Use a hashtable as a Set. */
83     private static Object JavaDoc NOVALUE = new Object JavaDoc();
84     /**
85         The interpreter which created the class manager
86         This is used to load scripted classes from source files.
87     */

88     private Interpreter declaringInterpreter;
89     
90     /**
91         An external classloader supplied by the setClassLoader() command.
92     */

93     protected ClassLoader JavaDoc externalClassLoader;
94
95     /**
96         Global cache for things we know are classes.
97         Note: these should probably be re-implemented with Soft references.
98         (as opposed to strong or Weak)
99     */

100     protected transient Hashtable absoluteClassCache = new Hashtable();
101     /**
102         Global cache for things we know are *not* classes.
103         Note: these should probably be re-implemented with Soft references.
104         (as opposed to strong or Weak)
105     */

106     protected transient Hashtable absoluteNonClasses = new Hashtable();
107
108     /**
109         Caches for resolved object and static methods.
110         We keep these maps separate to support fast lookup in the general case
111         where the method may be either.
112     */

113     protected transient Hashtable resolvedObjectMethods = new Hashtable();
114     protected transient Hashtable resolvedStaticMethods = new Hashtable();
115
116     protected transient Hashtable definingClasses = new Hashtable();
117     protected transient Hashtable definingClassesBaseNames = new Hashtable();
118
119     /**
120         Create a new instance of the class manager.
121         Class manager instnaces are now associated with the interpreter.
122
123         @see bsh.Interpreter.getClassManager()
124         @see bsh.Interpreter.setClassLoader( ClassLoader )
125     */

126     public static BshClassManager createClassManager( Interpreter interpreter )
127     {
128         BshClassManager manager;
129
130         // Do we have the necessary jdk1.2 packages and optional package?
131
if ( Capabilities.classExists("java.lang.ref.WeakReference")
132             && Capabilities.classExists("java.util.HashMap")
133             && Capabilities.classExists("bsh.classpath.ClassManagerImpl")
134         )
135             try {
136                 // Try to load the module
137
// don't refer to it directly here or we're dependent upon it
138
Class JavaDoc clas = Class.forName( "bsh.classpath.ClassManagerImpl" );
139                 manager = (BshClassManager)clas.newInstance();
140             } catch ( Exception JavaDoc e ) {
141                 throw new InterpreterError("Error loading classmanager: "+e);
142             }
143         else
144             manager = new BshClassManager();
145
146         if ( interpreter == null )
147             interpreter = new Interpreter();
148         manager.declaringInterpreter = interpreter;
149         return manager;
150     }
151
152     public boolean classExists( String JavaDoc name ) {
153         return ( classForName( name ) != null );
154     }
155
156     /**
157         Load the specified class by name, taking into account added classpath
158         and reloaded classes, etc.
159         Note: Again, this is just a trivial implementation.
160         See bsh.classpath.ClassManagerImpl for the fully functional class
161         management package.
162         @return the class or null
163     */

164     public Class JavaDoc classForName( String JavaDoc name )
165     {
166         if ( isClassBeingDefined( name ) )
167             throw new InterpreterError(
168                 "Attempting to load class in the process of being defined: "
169                 +name );
170
171         Class JavaDoc clas = null;
172         try {
173             clas = plainClassForName( name );
174         } catch ( ClassNotFoundException JavaDoc e ) { /*ignore*/ }
175
176         // try scripted class
177
if ( clas == null )
178             clas = loadSourceClass( name );
179
180         return clas;
181     }
182     
183     // Move me to classpath/ClassManagerImpl???
184
protected Class JavaDoc loadSourceClass( String JavaDoc name )
185     {
186         String JavaDoc fileName = "/"+name.replace('.','/')+".java";
187         InputStream in = getResourceAsStream( fileName );
188         if ( in == null )
189             return null;
190
191         try {
192             System.out.println("Loading class from source file: "+fileName);
193             declaringInterpreter.eval( new InputStreamReader(in) );
194         } catch ( EvalError e ) {
195             // ignore
196
System.err.println( e );
197         }
198         try {
199             return plainClassForName( name );
200         } catch ( ClassNotFoundException JavaDoc e ) {
201             System.err.println("Class not found in source file: "+name );
202             return null;
203         }
204     }
205
206     /**
207         Perform a plain Class.forName() or call the externally provided
208         classloader.
209         If a BshClassManager implementation is loaded the call will be
210         delegated to it, to allow for additional hooks.
211         <p/>
212
213         This simply wraps that bottom level class lookup call and provides a
214         central point for monitoring and handling certain Java version
215         dependent bugs, etc.
216
217         @see #classForName( String )
218         @return the class
219     */

220     public Class JavaDoc plainClassForName( String JavaDoc name )
221         throws ClassNotFoundException JavaDoc
222     {
223         Class JavaDoc c = null;
224
225         try {
226             if ( externalClassLoader != null )
227                 c = externalClassLoader.loadClass( name );
228             else
229                 c = Class.forName( name );
230
231             cacheClassInfo( name, c );
232
233         /*
234             Original note: Jdk under Win is throwing these to
235             warn about lower case / upper case possible mismatch.
236             e.g. bsh.console bsh.Console
237     
238             Update: Prior to 1.3 we were squeltching NoClassDefFoundErrors
239             which was very annoying. I cannot reproduce the original problem
240             and this was never a valid solution. If there are legacy VMs that
241             have problems we can include a more specific test for them here.
242         */

243         } catch ( NoClassDefFoundError JavaDoc e ) {
244             throw noClassDefFound( name, e );
245         }
246
247         return c;
248     }
249
250     /**
251         Get a resource URL using the BeanShell classpath
252         @param path should be an absolute path
253     */

254     public URL getResource( String JavaDoc path )
255     {
256         URL url = null;
257         if ( externalClassLoader != null )
258         {
259             // classloader wants no leading slash
260
url = externalClassLoader.getResource( path.substring(1) );
261         }
262         if ( url == null )
263             url = Interpreter.class.getResource( path );
264
265         return url;
266     }
267     /**
268         Get a resource stream using the BeanShell classpath
269         @param path should be an absolute path
270     */

271     public InputStream getResourceAsStream( String JavaDoc path )
272     {
273         InputStream in = null;
274         if ( externalClassLoader != null )
275         {
276             // classloader wants no leading slash
277
in = externalClassLoader.getResourceAsStream( path.substring(1) );
278         }
279         if ( in == null )
280             in = Interpreter.class.getResourceAsStream( path );
281
282         return in;
283     }
284
285     /**
286         Cache info about whether name is a class or not.
287         @param value
288             if value is non-null, cache the class
289             if value is null, set the flag that it is *not* a class to
290             speed later resolution
291     */

292     public void cacheClassInfo( String JavaDoc name, Class JavaDoc value ) {
293         if ( value != null )
294             absoluteClassCache.put( name, value );
295         else
296             absoluteNonClasses.put( name, NOVALUE );
297     }
298
299     /**
300         Cache a resolved (possibly overloaded) method based on the
301         argument types used to invoke it, subject to classloader change.
302         Static and Object methods are cached separately to support fast lookup
303         in the general case where either will do.
304     */

305     public void cacheResolvedMethod(
306         Class JavaDoc clas, Class JavaDoc [] types, Method JavaDoc method )
307     {
308         if ( Interpreter.DEBUG )
309             Interpreter.debug(
310                 "cacheResolvedMethod putting: " + clas +" "+ method );
311         
312         SignatureKey sk = new SignatureKey( clas, method.getName(), types );
313         if ( Modifier.isStatic( method.getModifiers() ) )
314             resolvedStaticMethods.put( sk, method );
315         else
316             resolvedObjectMethods.put( sk, method );
317     }
318
319     /**
320         Return a previously cached resolved method.
321         @param onlyStatic specifies that only a static method may be returned.
322         @return the Method or null
323     */

324     protected Method JavaDoc getResolvedMethod(
325         Class JavaDoc clas, String JavaDoc methodName, Class JavaDoc [] types, boolean onlyStatic )
326     {
327         SignatureKey sk = new SignatureKey( clas, methodName, types );
328
329         // Try static and then object, if allowed
330
// Note that the Java compiler should not allow both.
331
Method JavaDoc method = (Method JavaDoc)resolvedStaticMethods.get( sk );
332         if ( method == null && !onlyStatic)
333             method = (Method JavaDoc)resolvedObjectMethods.get( sk );
334
335         if ( Interpreter.DEBUG )
336         {
337             if ( method == null )
338                 Interpreter.debug(
339                     "getResolvedMethod cache MISS: " + clas +" - "+methodName );
340             else
341                 Interpreter.debug(
342                     "getResolvedMethod cache HIT: " + clas +" - " +method );
343         }
344         return method;
345     }
346
347     /**
348         Clear the caches in BshClassManager
349         @see public void #reset() for external usage
350     */

351     protected void clearCaches()
352     {
353         absoluteNonClasses = new Hashtable();
354         absoluteClassCache = new Hashtable();
355         resolvedObjectMethods = new Hashtable();
356         resolvedStaticMethods = new Hashtable();
357     }
358
359     /**
360         Set an external class loader. BeanShell will use this at the same
361         point it would otherwise use the plain Class.forName().
362         i.e. if no explicit classpath management is done from the script
363         (addClassPath(), setClassPath(), reloadClasses()) then BeanShell will
364         only use the supplied classloader. If additional classpath management
365         is done then BeanShell will perform that in addition to the supplied
366         external classloader.
367         However BeanShell is not currently able to reload
368         classes supplied through the external classloader.
369     */

370     public void setClassLoader( ClassLoader JavaDoc externalCL )
371     {
372         externalClassLoader = externalCL;
373         classLoaderChanged();
374     }
375
376     public void addClassPath( URL path )
377         throws IOException JavaDoc {
378     }
379
380     /**
381         Clear all loaders and start over. No class loading.
382     */

383     public void reset() {
384         clearCaches();
385     }
386
387     /**
388         Set a new base classpath and create a new base classloader.
389         This means all types change.
390     */

391     public void setClassPath( URL [] cp )
392         throws UtilEvalError
393     {
394         throw cmUnavailable();
395     }
396
397     /**
398         Overlay the entire path with a new class loader.
399         Set the base path to the user path + base path.
400
401         No point in including the boot class path (can't reload thos).
402     */

403     public void reloadAllClasses() throws UtilEvalError {
404         throw cmUnavailable();
405     }
406
407     /**
408         Reloading classes means creating a new classloader and using it
409         whenever we are asked for classes in the appropriate space.
410         For this we use a DiscreteFilesClassLoader
411     */

412     public void reloadClasses( String JavaDoc [] classNames )
413         throws UtilEvalError
414     {
415         throw cmUnavailable();
416     }
417
418     /**
419         Reload all classes in the specified package: e.g. "com.sun.tools"
420
421         The special package name "<unpackaged>" can be used to refer
422         to unpackaged classes.
423     */

424     public void reloadPackage( String JavaDoc pack )
425         throws UtilEvalError
426     {
427         throw cmUnavailable();
428     }
429
430     /**
431         This has been removed from the interface to shield the core from the
432         rest of the classpath package. If you need the classpath you will have
433         to cast the classmanager to its impl.
434
435         public BshClassPath getClassPath() throws ClassPathException;
436     */

437
438     /**
439         Support for "import *;"
440         Hide details in here as opposed to NameSpace.
441     */

442     protected void doSuperImport()
443         throws UtilEvalError
444     {
445         throw cmUnavailable();
446     }
447
448     /**
449         A "super import" ("import *") operation has been performed.
450     */

451     protected boolean hasSuperImport()
452     {
453         return false;
454     }
455
456     /**
457         Return the name or null if none is found,
458         Throw an ClassPathException containing detail if name is ambigous.
459     */

460     protected String JavaDoc getClassNameByUnqName( String JavaDoc name )
461         throws UtilEvalError
462     {
463         throw cmUnavailable();
464     }
465
466     public void addListener( Listener l ) { }
467
468     public void removeListener( Listener l ) { }
469
470     public void dump( PrintWriter pw ) {
471         pw.println("BshClassManager: no class manager.");
472     }
473
474     /**
475         Flag the class name as being in the process of being defined.
476         The class manager will not attempt to load it.
477     */

478     /*
479         Note: this implementation is temporary. We currently keep a flat
480         namespace of the base name of classes. i.e. BeanShell cannot be in the
481         process of defining two classes in different packages with the same
482         base name. To remove this limitation requires that we work through
483         namespace imports in an analogous (or using the same path) as regular
484         class import resolution. This workaround should handle most cases
485         so we'll try it for now.
486     */

487     protected void definingClass( String JavaDoc className ) {
488         String JavaDoc baseName = Name.suffix(className,1);
489         int i = baseName.indexOf("$");
490         if ( i != -1 )
491             baseName = baseName.substring(i+1);
492         String JavaDoc cur = (String JavaDoc)definingClassesBaseNames.get( baseName );
493         if ( cur != null )
494             throw new InterpreterError("Defining class problem: "+className
495                 +": BeanShell cannot yet simultaneously define two or more "
496                 +"dependant classes of the same name. Attempt to define: "
497                 + className +" while defining: "+cur
498             );
499         definingClasses.put( className, NOVALUE );
500         definingClassesBaseNames.put( baseName, className );
501     }
502
503     protected boolean isClassBeingDefined( String JavaDoc className ) {
504         return definingClasses.get( className ) != null;
505     }
506
507     /**
508         This method is a temporary workaround used with definingClass.
509         It is to be removed at some point.
510     */

511     protected String JavaDoc getClassBeingDefined( String JavaDoc className ) {
512         String JavaDoc baseName = Name.suffix(className,1);
513         return (String JavaDoc)definingClassesBaseNames.get( baseName );
514     }
515
516     /**
517         Indicate that the specified class name has been defined and may be
518         loaded normally.
519     */

520     protected void doneDefiningClass( String JavaDoc className ) {
521         String JavaDoc baseName = Name.suffix(className,1);
522         definingClasses.remove( className );
523         definingClassesBaseNames.remove( baseName );
524     }
525
526     /*
527         The real implementation in the classpath.ClassManagerImpl handles
528         reloading of the generated classes.
529     */

530     public Class JavaDoc defineClass( String JavaDoc name, byte [] code )
531     {
532         throw new InterpreterError("Can't create class ("+name
533             +") without class manager package.");
534     /*
535         Old implementation injected classes into the parent classloader.
536         This was incorrect behavior for several reasons. The biggest problem
537         is that classes could therefore only be defined once across all
538         executions of the script...
539
540         ClassLoader cl = this.getClass().getClassLoader();
541         Class clas;
542         try {
543             clas = (Class)Reflect.invokeObjectMethod(
544                 cl, "defineClass",
545                 new Object [] {
546                     name, code,
547                     new Primitive( (int)0 )/offset/,
548                     new Primitive( code.length )/len/
549                 },
550                 (Interpreter)null, (CallStack)null, (SimpleNode)null
551             );
552         } catch ( Exception e ) {
553             e.printStackTrace();
554             throw new InterpreterError("Unable to define class: "+ e );
555         }
556         absoluteNonClasses.remove( name ); // may have been axed previously
557         return clas;
558     */

559     }
560
561     protected void classLoaderChanged() { }
562
563     /**
564         Annotate the NoClassDefFoundError with some info about the class
565         we were trying to load.
566     */

567     protected static Error JavaDoc noClassDefFound( String JavaDoc className, Error JavaDoc e ) {
568         return new NoClassDefFoundError JavaDoc(
569             "A class required by class: "+className +" could not be loaded:\n"
570             +e.toString() );
571     }
572
573     protected static UtilEvalError cmUnavailable() {
574         return new Capabilities.Unavailable(
575             "ClassLoading features unavailable.");
576     }
577
578     public static interface Listener
579     {
580         public void classLoaderChanged();
581     }
582
583     /**
584         SignatureKey serves as a hash of a method signature on a class
585         for fast lookup of overloaded and general resolved Java methods.
586         <p>
587     */

588     /*
589         Note: is using SignatureKey in this way dangerous? In the pathological
590         case a user could eat up memory caching every possible combination of
591         argument types to an untyped method. Maybe we could be smarter about
592         it by ignoring the types of untyped parameter positions? The method
593         resolver could return a set of "hints" for the signature key caching?
594
595         There is also the overhead of creating one of these for every method
596         dispatched. What is the alternative?
597     */

598     static class SignatureKey
599     {
600         Class JavaDoc clas;
601         Class JavaDoc [] types;
602         String JavaDoc methodName;
603         int hashCode = 0;
604
605         SignatureKey( Class JavaDoc clas, String JavaDoc methodName, Class JavaDoc [] types ) {
606             this.clas = clas;
607             this.methodName = methodName;
608             this.types = types;
609         }
610
611         public int hashCode()
612         {
613             if ( hashCode == 0 )
614             {
615                 hashCode = clas.hashCode() * methodName.hashCode();
616                 if ( types == null ) // no args method
617
return hashCode;
618                 for( int i =0; i < types.length; i++ ) {
619                     int hc = types[i] == null ? 21 : types[i].hashCode();
620                     hashCode = hashCode*(i+1) + hc;
621                 }
622             }
623             return hashCode;
624         }
625
626         public boolean equals( Object JavaDoc o ) {
627             SignatureKey target = (SignatureKey)o;
628             if ( types == null )
629                 return target.types == null;
630             if ( clas != target.clas )
631                 return false;
632             if ( !methodName.equals( target.methodName ) )
633                 return false;
634             if ( types.length != target.types.length )
635                 return false;
636             for( int i =0; i< types.length; i++ )
637             {
638                 if ( types[i]==null )
639                 {
640                     if ( !(target.types[i]==null) )
641                         return false;
642                 } else
643                     if ( !types[i].equals( target.types[i] ) )
644                         return false;
645             }
646
647             return true;
648         }
649     }
650 }
651
Popular Tags