001    /*****************************************************************************
002     *                                                                           *
003     *  This file is part of the BeanShell Java Scripting distribution.          *
004     *  Documentation and updates may be found at http://www.beanshell.org/      *
005     *                                                                           *
006     *  Sun Public License Notice:                                               *
007     *                                                                           *
008     *  The contents of this file are subject to the Sun Public License Version  *
009     *  1.0 (the "License"); you may not use this file except in compliance with *
010     *  the License. A copy of the License is available at http://www.sun.com    *
011     *                                                                           *
012     *  The Original Code is BeanShell. The Initial Developer of the Original    *
013     *  Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright     *
014     *  (C) 2000.  All Rights Reserved.                                          *
015     *                                                                           *
016     *  GNU Public License Notice:                                               *
017     *                                                                           *
018     *  Alternatively, the contents of this file may be used under the terms of  *
019     *  the GNU Lesser General Public License (the "LGPL"), in which case the    *
020     *  provisions of LGPL are applicable instead of those above. If you wish to *
021     *  allow use of your version of this file only under the  terms of the LGPL *
022     *  and not to allow others to use your version of this file under the SPL,  *
023     *  indicate your decision by deleting the provisions above and replace      *
024     *  them with the notice and other provisions required by the LGPL.  If you  *
025     *  do not delete the provisions above, a recipient may use your version of  *
026     *  this file under either the SPL or the LGPL.                              *
027     *                                                                           *
028     *  Patrick Niemeyer (pat@pat.net)                                           *
029     *  Author of Learning Java, O'Reilly & Associates                           *
030     *  http://www.pat.net/~pat/                                                 *
031     *                                                                           *
032     *****************************************************************************/
033    
034    package bsh;
035    
036    import java.net.*;
037    import java.util.*;
038    import java.util.logging.Logger;
039    import java.io.IOException;
040    import java.io.*;
041    import java.lang.reflect.Method;
042    import java.lang.reflect.Modifier;
043    
044    /**
045        BshClassManager manages all classloading in BeanShell.
046        It also supports a dynamically loaded extension (bsh.classpath package)
047        which allows classpath extension and class file reloading.
048    
049        Currently the extension relies on 1.2 for BshClassLoader and weak
050        references.
051    
052        See http://www.beanshell.org/manual/classloading.html for details
053        on the bsh classloader architecture.
054        <p>
055    
056        Bsh has a multi-tiered class loading architecture.  No class loader is
057        used unless/until the classpath is modified or a class is reloaded.
058        <p>
059    */
060    /*
061        Implementation notes:
062    
063        Note: we may need some synchronization in here
064    
065        Note on version dependency:  This base class is JDK 1.1 compatible,
066        however we are forced to use weak references in the full featured
067        implementation (the optional bsh.classpath package) to accomodate all of
068        the fleeting namespace listeners as they fall out of scope.  (NameSpaces
069        must be informed if the class space changes so that they can un-cache
070        names).
071        <p>
072    
073        Perhaps a simpler idea would be to have entities that reference cached
074        types always perform a light weight check with a counter / reference
075        value and use that to detect changes in the namespace.  This puts the
076        burden on the consumer to check at appropriate times, but could eliminate
077        the need for the listener system in many places and the necessity of weak
078        references in this package.
079        <p>
080    */
081    public class BshClassManager
082    {
083        private static final Logger logger = Logger.getLogger(BshClassManager.class.getPackage().getName());
084    
085        /** Identifier for no value item.  Use a hashtable as a Set. */
086        private static Object NOVALUE = new Object();
087        /**
088            The interpreter which created the class manager
089            This is used to load scripted classes from source files.
090        */
091        private Interpreter declaringInterpreter;
092    
093        /**
094            An external classloader supplied by the setClassLoader() command.
095        */
096        protected ClassLoader externalClassLoader;
097    
098        /**
099            Global cache for things we know are classes.
100            Note: these should probably be re-implemented with Soft references.
101            (as opposed to strong or Weak)
102        */
103        protected transient Hashtable absoluteClassCache = new Hashtable();
104        /**
105            Global cache for things we know are *not* classes.
106            Note: these should probably be re-implemented with Soft references.
107            (as opposed to strong or Weak)
108        */
109        protected transient Hashtable absoluteNonClasses = new Hashtable();
110    
111        /**
112            Caches for resolved object and static methods.
113            We keep these maps separate to support fast lookup in the general case
114            where the method may be either.
115        */
116        protected transient Hashtable resolvedObjectMethods = new Hashtable();
117        protected transient Hashtable resolvedStaticMethods = new Hashtable();
118    
119        protected transient Hashtable definingClasses = new Hashtable();
120        protected transient Hashtable definingClassesBaseNames = new Hashtable();
121    
122        /**
123            Create a new instance of the class manager.
124            Class manager instnaces are now associated with the interpreter.
125    
126            @see bsh.Interpreter.getClassManager()
127            @see bsh.Interpreter.setClassLoader( ClassLoader )
128        */
129        public static BshClassManager createClassManager( Interpreter interpreter )
130        {
131            BshClassManager manager;
132    
133            // Do we have the necessary jdk1.2 packages and optional package?
134            if ( Capabilities.classExists("java.lang.ref.WeakReference")
135                && Capabilities.classExists("java.util.HashMap")
136                && Capabilities.classExists("bsh.classpath.ClassManagerImpl")
137            )
138                try {
139                    // Try to load the module
140                    // don't refer to it directly here or we're dependent upon it
141                    Class clas = Class.forName( "bsh.classpath.ClassManagerImpl" );
142                    manager = (BshClassManager)clas.newInstance();
143                } catch ( Exception e ) {
144                    throw new InterpreterError("Error loading classmanager: "+e);
145                }
146            else
147                manager = new BshClassManager();
148    
149            if ( interpreter == null )
150                interpreter = new Interpreter();
151            manager.declaringInterpreter = interpreter;
152            return manager;
153        }
154    
155        public boolean classExists( String name ) {
156            return ( classForName( name ) != null );
157        }
158    
159        /**
160            Load the specified class by name, taking into account added classpath
161            and reloaded classes, etc.
162            Note: Again, this is just a trivial implementation.
163            See bsh.classpath.ClassManagerImpl for the fully functional class
164            management package.
165            @return the class or null
166        */
167        public Class classForName( String name )
168        {
169            if ( isClassBeingDefined( name ) )
170                throw new InterpreterError(
171                    "Attempting to load class in the process of being defined: "
172                    +name );
173    
174            Class clas = null;
175            try {
176                clas = plainClassForName( name );
177            } catch ( ClassNotFoundException e ) { /*ignore*/ }
178    
179            // try scripted class
180            if ( clas == null )
181                clas = loadSourceClass( name );
182    
183            return clas;
184        }
185    
186        // Move me to classpath/ClassManagerImpl???
187        protected Class loadSourceClass( String name )
188        {
189            String fileName = "/"+name.replace('.','/')+".java";
190            InputStream in = getResourceAsStream( fileName );
191            if ( in == null )
192                return null;
193    
194            try {
195                logger.info("Loading class from source file: "+fileName);
196                declaringInterpreter.eval( new InputStreamReader(in) );
197            } catch ( EvalError e ) {
198                // ignore
199                logger.warning(e.toString());
200            }
201            try {
202                return plainClassForName( name );
203            } catch ( ClassNotFoundException e ) {
204                logger.warning("Class not found in source file: "+name );
205                return null;
206            }
207        }
208    
209        /**
210            Perform a plain Class.forName() or call the externally provided
211            classloader.
212            If a BshClassManager implementation is loaded the call will be
213            delegated to it, to allow for additional hooks.
214            <p/>
215    
216            This simply wraps that bottom level class lookup call and provides a
217            central point for monitoring and handling certain Java version
218            dependent bugs, etc.
219    
220            @see #classForName( String )
221            @return the class
222        */
223        public Class plainClassForName( String name )
224            throws ClassNotFoundException
225        {
226            Class c = null;
227    
228            try {
229                if ( externalClassLoader != null )
230                    c = externalClassLoader.loadClass( name );
231                else
232                    c = Class.forName( name );
233    
234                cacheClassInfo( name, c );
235    
236            /*
237                Original note: Jdk under Win is throwing these to
238                warn about lower case / upper case possible mismatch.
239                e.g. bsh.console bsh.Console
240    
241                Update: Prior to 1.3 we were squeltching NoClassDefFoundErrors
242                which was very annoying.  I cannot reproduce the original problem
243                and this was never a valid solution.  If there are legacy VMs that
244                have problems we can include a more specific test for them here.
245            */
246            } catch ( NoClassDefFoundError e ) {
247                throw noClassDefFound( name, e );
248            }
249    
250            return c;
251        }
252    
253        /**
254            Get a resource URL using the BeanShell classpath
255            @param path should be an absolute path
256        */
257        public URL getResource( String path )
258        {
259            URL url = null;
260            if ( externalClassLoader != null )
261            {
262                // classloader wants no leading slash
263                url = externalClassLoader.getResource( path.substring(1) );
264            }
265            if ( url == null )
266                url = Interpreter.class.getResource( path );
267    
268            return url;
269        }
270        /**
271            Get a resource stream using the BeanShell classpath
272            @param path should be an absolute path
273        */
274        public InputStream getResourceAsStream( String path )
275        {
276            InputStream in = null;
277            if ( externalClassLoader != null )
278            {
279                // classloader wants no leading slash
280                in = externalClassLoader.getResourceAsStream( path.substring(1) );
281            }
282            if ( in == null )
283                in = Interpreter.class.getResourceAsStream( path );
284    
285            return in;
286        }
287    
288        /**
289            Cache info about whether name is a class or not.
290            @param value
291                if value is non-null, cache the class
292                if value is null, set the flag that it is *not* a class to
293                speed later resolution
294        */
295        public void cacheClassInfo( String name, Class value ) {
296            if ( value != null )
297                absoluteClassCache.put( name, value );
298            else
299                absoluteNonClasses.put( name, NOVALUE );
300        }
301    
302        /**
303            Cache a resolved (possibly overloaded) method based on the
304            argument types used to invoke it, subject to classloader change.
305            Static and Object methods are cached separately to support fast lookup
306            in the general case where either will do.
307        */
308        public void cacheResolvedMethod(
309            Class clas, Class [] types, Method method )
310        {
311            if ( Interpreter.DEBUG )
312                Interpreter.debug(
313                    "cacheResolvedMethod putting: " + clas +" "+ method );
314    
315            SignatureKey sk = new SignatureKey( clas, method.getName(), types );
316            if ( Modifier.isStatic( method.getModifiers() ) )
317                resolvedStaticMethods.put( sk, method );
318            else
319                resolvedObjectMethods.put( sk, method );
320        }
321    
322        /**
323            Return a previously cached resolved method.
324            @param onlyStatic specifies that only a static method may be returned.
325            @return the Method or null
326        */
327        protected Method getResolvedMethod(
328            Class clas, String methodName, Class [] types, boolean onlyStatic  )
329        {
330            SignatureKey sk = new SignatureKey( clas, methodName, types );
331    
332            // Try static and then object, if allowed
333            // Note that the Java compiler should not allow both.
334            Method method = (Method)resolvedStaticMethods.get( sk );
335            if ( method == null && !onlyStatic)
336                method = (Method)resolvedObjectMethods.get( sk );
337    
338            if ( Interpreter.DEBUG )
339            {
340                if ( method == null )
341                    Interpreter.debug(
342                        "getResolvedMethod cache MISS: " + clas +" - "+methodName );
343                else
344                    Interpreter.debug(
345                        "getResolvedMethod cache HIT: " + clas +" - " +method );
346            }
347            return method;
348        }
349    
350        /**
351            Clear the caches in BshClassManager
352            @see public void #reset() for external usage
353        */
354        protected void clearCaches()
355        {
356            absoluteNonClasses = new Hashtable();
357            absoluteClassCache = new Hashtable();
358            resolvedObjectMethods = new Hashtable();
359            resolvedStaticMethods = new Hashtable();
360        }
361    
362        /**
363            Set an external class loader.  BeanShell will use this at the same
364            point it would otherwise use the plain Class.forName().
365            i.e. if no explicit classpath management is done from the script
366            (addClassPath(), setClassPath(), reloadClasses()) then BeanShell will
367            only use the supplied classloader.  If additional classpath management
368            is done then BeanShell will perform that in addition to the supplied
369            external classloader.
370            However BeanShell is not currently able to reload
371            classes supplied through the external classloader.
372        */
373        public void setClassLoader( ClassLoader externalCL )
374        {
375            externalClassLoader = externalCL;
376            classLoaderChanged();
377        }
378    
379        public void addClassPath( URL path )
380            throws IOException {
381        }
382    
383        /**
384            Clear all loaders and start over.  No class loading.
385        */
386        public void reset() {
387            clearCaches();
388        }
389    
390        /**
391            Set a new base classpath and create a new base classloader.
392            This means all types change.
393        */
394        public void setClassPath( URL [] cp )
395            throws UtilEvalError
396        {
397            throw cmUnavailable();
398        }
399    
400        /**
401            Overlay the entire path with a new class loader.
402            Set the base path to the user path + base path.
403    
404            No point in including the boot class path (can't reload thos).
405        */
406        public void reloadAllClasses() throws UtilEvalError {
407            throw cmUnavailable();
408        }
409    
410        /**
411            Reloading classes means creating a new classloader and using it
412            whenever we are asked for classes in the appropriate space.
413            For this we use a DiscreteFilesClassLoader
414        */
415        public void reloadClasses( String [] classNames )
416            throws UtilEvalError
417        {
418            throw cmUnavailable();
419        }
420    
421        /**
422            Reload all classes in the specified package: e.g. "com.sun.tools"
423    
424            The special package name "<unpackaged>" can be used to refer
425            to unpackaged classes.
426        */
427        public void reloadPackage( String pack )
428            throws UtilEvalError
429        {
430            throw cmUnavailable();
431        }
432    
433        /**
434            This has been removed from the interface to shield the core from the
435            rest of the classpath package. If you need the classpath you will have
436            to cast the classmanager to its impl.
437    
438            public BshClassPath getClassPath() throws ClassPathException;
439        */
440    
441        /**
442            Support for "import *;"
443            Hide details in here as opposed to NameSpace.
444        */
445        protected void doSuperImport()
446            throws UtilEvalError
447        {
448            throw cmUnavailable();
449        }
450    
451        /**
452            A "super import" ("import *") operation has been performed.
453        */
454        protected boolean hasSuperImport()
455        {
456            return false;
457        }
458    
459        /**
460            Return the name or null if none is found,
461            Throw an ClassPathException containing detail if name is ambigous.
462        */
463        protected String getClassNameByUnqName( String name )
464            throws UtilEvalError
465        {
466            throw cmUnavailable();
467        }
468    
469        public void addListener( Listener l ) { }
470    
471        public void removeListener( Listener l ) { }
472    
473        public void dump( PrintWriter pw ) {
474            pw.println("BshClassManager: no class manager.");
475        }
476    
477        /**
478            Flag the class name as being in the process of being defined.
479            The class manager will not attempt to load it.
480        */
481        /*
482            Note: this implementation is temporary. We currently keep a flat
483            namespace of the base name of classes.  i.e. BeanShell cannot be in the
484            process of defining two classes in different packages with the same
485            base name.  To remove this limitation requires that we work through
486            namespace imports in an analogous (or using the same path) as regular
487            class import resolution.  This workaround should handle most cases
488            so we'll try it for now.
489        */
490        protected void definingClass( String className ) {
491            String baseName = Name.suffix(className,1);
492            int i = baseName.indexOf("$");
493            if ( i != -1 )
494                baseName = baseName.substring(i+1);
495            String cur = (String)definingClassesBaseNames.get( baseName );
496            if ( cur != null )
497                throw new InterpreterError("Defining class problem: "+className
498                    +": BeanShell cannot yet simultaneously define two or more "
499                    +"dependant classes of the same name.  Attempt to define: "
500                    + className +" while defining: "+cur
501                );
502            definingClasses.put( className, NOVALUE );
503            definingClassesBaseNames.put( baseName, className );
504        }
505    
506        protected boolean isClassBeingDefined( String className ) {
507            return definingClasses.get( className ) != null;
508        }
509    
510        /**
511            This method is a temporary workaround used with definingClass.
512            It is to be removed at some point.
513        */
514        protected String getClassBeingDefined( String className ) {
515            String baseName = Name.suffix(className,1);
516            return (String)definingClassesBaseNames.get( baseName );
517        }
518    
519        /**
520            Indicate that the specified class name has been defined and may be
521            loaded normally.
522        */
523        protected void doneDefiningClass( String className ) {
524            String baseName = Name.suffix(className,1);
525            definingClasses.remove( className );
526            definingClassesBaseNames.remove( baseName );
527        }
528    
529        /*
530            The real implementation in the classpath.ClassManagerImpl handles
531            reloading of the generated classes.
532        */
533        public Class defineClass( String name, byte [] code )
534        {
535            throw new InterpreterError("Can't create class ("+name
536                +") without class manager package.");
537        /*
538            Old implementation injected classes into the parent classloader.
539            This was incorrect behavior for several reasons.  The biggest problem
540            is that classes could therefore only be defined once across all
541            executions of the script...
542    
543            ClassLoader cl = this.getClass().getClassLoader();
544            Class clas;
545            try {
546                clas = (Class)Reflect.invokeObjectMethod(
547                    cl, "defineClass",
548                    new Object [] {
549                        name, code,
550                        new Primitive( (int)0 )/offset/,
551                        new Primitive( code.length )/len/
552                    },
553                    (Interpreter)null, (CallStack)null, (SimpleNode)null
554                );
555            } catch ( Exception e ) {
556                e.printStackTrace();
557                throw new InterpreterError("Unable to define class: "+ e );
558            }
559            absoluteNonClasses.remove( name ); // may have been axed previously
560            return clas;
561        */
562        }
563    
564        protected void classLoaderChanged() { }
565    
566        /**
567            Annotate the NoClassDefFoundError with some info about the class
568            we were trying to load.
569        */
570        protected static Error noClassDefFound( String className, Error e ) {
571            return new NoClassDefFoundError(
572                "A class required by class: "+className +" could not be loaded:\n"
573                +e.toString() );
574        }
575    
576        protected static UtilEvalError cmUnavailable() {
577            return new Capabilities.Unavailable(
578                "ClassLoading features unavailable.");
579        }
580    
581        public static interface Listener
582        {
583            public void classLoaderChanged();
584        }
585    
586        /**
587            SignatureKey serves as a hash of a method signature on a class
588            for fast lookup of overloaded and general resolved Java methods.
589            <p>
590        */
591        /*
592            Note: is using SignatureKey in this way dangerous?  In the pathological
593            case a user could eat up memory caching every possible combination of
594            argument types to an untyped method.  Maybe we could be smarter about
595            it by ignoring the types of untyped parameter positions?  The method
596            resolver could return a set of "hints" for the signature key caching?
597    
598            There is also the overhead of creating one of these for every method
599            dispatched.  What is the alternative?
600        */
601        static class SignatureKey
602        {
603            Class clas;
604            Class [] types;
605            String methodName;
606            int hashCode = 0;
607    
608            SignatureKey( Class clas, String methodName, Class [] types ) {
609                this.clas = clas;
610                this.methodName = methodName;
611                this.types = types;
612            }
613    
614            public int hashCode()
615            {
616                if ( hashCode == 0 )
617                {
618                    hashCode = clas.hashCode() * methodName.hashCode();
619                    if ( types == null ) // no args method
620                        return hashCode;
621                    for( int i =0; i < types.length; i++ ) {
622                        int hc = types[i] == null ? 21 : types[i].hashCode();
623                        hashCode = hashCode*(i+1) + hc;
624                    }
625                }
626                return hashCode;
627            }
628    
629            public boolean equals( Object o ) {
630                SignatureKey target = (SignatureKey)o;
631                if ( types == null )
632                    return target.types == null;
633                if ( clas != target.clas )
634                    return false;
635                if ( !methodName.equals( target.methodName ) )
636                    return false;
637                if ( types.length != target.types.length )
638                    return false;
639                for( int i =0; i< types.length; i++ )
640                {
641                    if ( types[i]==null )
642                    {
643                        if ( !(target.types[i]==null) )
644                            return false;
645                    } else
646                        if ( !types[i].equals( target.types[i] ) )
647                            return false;
648                }
649    
650                return true;
651            }
652        }
653    }