PageRenderTime 41ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/jEdit/tags/jedit-4-3-pre5/bsh/BshClassManager.java

#
Java | 634 lines | 307 code | 58 blank | 269 comment | 52 complexity | 9f58ee23870741f0ce071b2ff08ef701 MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, Apache-2.0, LGPL-2.0, LGPL-3.0, GPL-2.0, CC-BY-SA-3.0, LGPL-2.1, GPL-3.0, MPL-2.0-no-copyleft-exception, IPL-1.0
  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. package bsh;
  34. import java.net.*;
  35. import java.util.*;
  36. import java.io.IOException;
  37. import java.io.*;
  38. import java.lang.reflect.Method;
  39. import java.lang.reflect.Modifier;
  40. /**
  41. BshClassManager manages all classloading in BeanShell.
  42. It also supports a dynamically loaded extension (bsh.classpath package)
  43. which allows classpath extension and class file reloading.
  44. Currently the extension relies on 1.2 for BshClassLoader and weak
  45. references.
  46. See http://www.beanshell.org/manual/classloading.html for details
  47. on the bsh classloader architecture.
  48. <p>
  49. Bsh has a multi-tiered class loading architecture. No class loader is
  50. used unless/until the classpath is modified or a class is reloaded.
  51. <p>
  52. */
  53. /*
  54. Implementation notes:
  55. Note: we may need some synchronization in here
  56. Note on version dependency: This base class is JDK 1.1 compatible,
  57. however we are forced to use weak references in the full featured
  58. implementation (the optional bsh.classpath package) to accomodate all of
  59. the fleeting namespace listeners as they fall out of scope. (NameSpaces
  60. must be informed if the class space changes so that they can un-cache
  61. names).
  62. <p>
  63. Perhaps a simpler idea would be to have entities that reference cached
  64. types always perform a light weight check with a counter / reference
  65. value and use that to detect changes in the namespace. This puts the
  66. burden on the consumer to check at appropriate times, but could eliminate
  67. the need for the listener system in many places and the necessity of weak
  68. references in this package.
  69. <p>
  70. */
  71. public class BshClassManager
  72. {
  73. /** Identifier for no value item. Use a hashtable as a Set. */
  74. private static Object NOVALUE = new Object();
  75. /**
  76. The interpreter which created the class manager
  77. This is used to load scripted classes from source files.
  78. */
  79. private Interpreter declaringInterpreter;
  80. /**
  81. An external classloader supplied by the setClassLoader() command.
  82. */
  83. private ClassLoader externalClassLoader;
  84. /**
  85. Global cache for things we know are classes.
  86. Note: these should probably be re-implemented with Soft references.
  87. (as opposed to strong or Weak)
  88. */
  89. protected transient Hashtable absoluteClassCache = new Hashtable();
  90. /**
  91. Global cache for things we know are *not* classes.
  92. Note: these should probably be re-implemented with Soft references.
  93. (as opposed to strong or Weak)
  94. */
  95. protected transient Hashtable absoluteNonClasses = new Hashtable();
  96. /**
  97. Caches for resolved object and static methods.
  98. We keep these maps separate to support fast lookup in the general case
  99. where the method may be either.
  100. */
  101. protected transient Hashtable resolvedObjectMethods = new Hashtable();
  102. protected transient Hashtable resolvedStaticMethods = new Hashtable();
  103. protected transient Hashtable definingClasses = new Hashtable();
  104. protected transient Hashtable definingClassesBaseNames = new Hashtable();
  105. /**
  106. Create a new instance of the class manager.
  107. Class manager instnaces are now associated with the interpreter.
  108. @see bsh.Interpreter.getClassManager()
  109. @see bsh.Interpreter.setClassLoader( ClassLoader )
  110. */
  111. public static BshClassManager createClassManager( Interpreter interpreter )
  112. {
  113. BshClassManager manager;
  114. // Do we have the necessary jdk1.2 packages and optional package?
  115. if ( Capabilities.classExists("java.lang.ref.WeakReference")
  116. && Capabilities.classExists("java.util.HashMap")
  117. && Capabilities.classExists("bsh.classpath.ClassManagerImpl")
  118. )
  119. try {
  120. // Try to load the module
  121. // don't refer to it directly here or we're dependent upon it
  122. Class clas = Class.forName( "bsh.classpath.ClassManagerImpl" );
  123. manager = (BshClassManager)clas.newInstance();
  124. } catch ( Exception e ) {
  125. throw new InterpreterError("Error loading classmanager: "+e);
  126. }
  127. else
  128. manager = new BshClassManager();
  129. if ( interpreter == null )
  130. interpreter = new Interpreter();
  131. manager.declaringInterpreter = interpreter;
  132. return manager;
  133. }
  134. public boolean classExists( String name ) {
  135. return ( classForName( name ) != null );
  136. }
  137. /**
  138. Load the specified class by name, taking into account added classpath
  139. and reloaded classes, etc.
  140. @return the class or null
  141. */
  142. public Class classForName( String name )
  143. {
  144. if ( isClassBeingDefined( name ) )
  145. throw new InterpreterError(
  146. "Attempting to load class in the process of being defined: "
  147. +name );
  148. Class clas = null;
  149. try {
  150. clas = plainClassForName( name );
  151. } catch ( ClassNotFoundException e ) { /*ignore*/ }
  152. // try scripted class
  153. if ( clas == null )
  154. clas = loadSourceClass( name );
  155. return clas;
  156. }
  157. // Move me to classpath/ClassManagerImpl???
  158. protected Class loadSourceClass( String name )
  159. {
  160. String fileName = "/"+name.replace('.','/')+".java";
  161. InputStream in = getResourceAsStream( fileName );
  162. if ( in == null )
  163. return null;
  164. try {
  165. System.out.println("Loading class from source file: "+fileName);
  166. declaringInterpreter.eval( new InputStreamReader(in) );
  167. } catch ( EvalError e ) {
  168. // ignore
  169. System.err.println( e );
  170. }
  171. try {
  172. return plainClassForName( name );
  173. } catch ( ClassNotFoundException e ) {
  174. System.err.println("Class not found in source file: "+name );
  175. return null;
  176. }
  177. }
  178. /**
  179. Perform a plain Class.forName() or call the externally provided
  180. classloader.
  181. If a BshClassManager implementation is loaded the call will be
  182. delegated to it, to allow for additional hooks.
  183. <p/>
  184. This simply wraps that bottom level class lookup call and provides a
  185. central point for monitoring and handling certain Java version
  186. dependent bugs, etc.
  187. @see #classForName( String )
  188. @return the class
  189. */
  190. public Class plainClassForName( String name )
  191. throws ClassNotFoundException
  192. {
  193. Class c = null;
  194. try {
  195. if ( externalClassLoader != null )
  196. c = externalClassLoader.loadClass( name );
  197. else
  198. c = Class.forName( name );
  199. cacheClassInfo( name, c );
  200. /*
  201. Original note: Jdk under Win is throwing these to
  202. warn about lower case / upper case possible mismatch.
  203. e.g. bsh.console bsh.Console
  204. Update: Prior to 1.3 we were squeltching NoClassDefFoundErrors
  205. which was very annoying. I cannot reproduce the original problem
  206. and this was never a valid solution. If there are legacy VMs that
  207. have problems we can include a more specific test for them here.
  208. */
  209. } catch ( NoClassDefFoundError e ) {
  210. throw noClassDefFound( name, e );
  211. }
  212. return c;
  213. }
  214. /**
  215. Get a resource URL using the BeanShell classpath
  216. @param path should be an absolute path
  217. */
  218. public URL getResource( String path )
  219. {
  220. if ( externalClassLoader != null )
  221. {
  222. // classloader wants no leading slash
  223. return externalClassLoader.getResource( path.substring(1) );
  224. } else
  225. return Interpreter.class.getResource( path );
  226. }
  227. /**
  228. Get a resource stream using the BeanShell classpath
  229. @param path should be an absolute path
  230. */
  231. public InputStream getResourceAsStream( String path )
  232. {
  233. if ( externalClassLoader != null )
  234. {
  235. // classloader wants no leading slash
  236. return externalClassLoader.getResourceAsStream( path.substring(1) );
  237. } else
  238. return Interpreter.class.getResourceAsStream( path );
  239. }
  240. /**
  241. Cache info about whether name is a class or not.
  242. @param value
  243. if value is non-null, cache the class
  244. if value is null, set the flag that it is *not* a class to
  245. speed later resolution
  246. */
  247. public void cacheClassInfo( String name, Class value ) {
  248. if ( value != null )
  249. absoluteClassCache.put( name, value );
  250. else
  251. absoluteNonClasses.put( name, NOVALUE );
  252. }
  253. /**
  254. Cache a resolved (possibly overloaded) method based on the
  255. argument types used to invoke it, subject to classloader change.
  256. Static and Object methods are cached separately to support fast lookup
  257. in the general case where either will do.
  258. */
  259. public void cacheResolvedMethod(
  260. Class clas, Class [] types, Method method )
  261. {
  262. if ( Interpreter.DEBUG )
  263. Interpreter.debug(
  264. "cacheResolvedMethod putting: " + clas +" "+ method );
  265. SignatureKey sk = new SignatureKey( clas, method.getName(), types );
  266. if ( Modifier.isStatic( method.getModifiers() ) )
  267. resolvedStaticMethods.put( sk, method );
  268. else
  269. resolvedObjectMethods.put( sk, method );
  270. }
  271. /**
  272. Return a previously cached resolved method.
  273. @param onlyStatic specifies that only a static method may be returned.
  274. @return the Method or null
  275. */
  276. protected Method getResolvedMethod(
  277. Class clas, String methodName, Class [] types, boolean onlyStatic )
  278. {
  279. SignatureKey sk = new SignatureKey( clas, methodName, types );
  280. // Try static and then object, if allowed
  281. // Note that the Java compiler should not allow both.
  282. Method method = (Method)resolvedStaticMethods.get( sk );
  283. if ( method == null && !onlyStatic)
  284. method = (Method)resolvedObjectMethods.get( sk );
  285. if ( Interpreter.DEBUG )
  286. {
  287. if ( method == null )
  288. Interpreter.debug(
  289. "getResolvedMethod cache MISS: " + clas +" - "+methodName );
  290. else
  291. Interpreter.debug(
  292. "getResolvedMethod cache HIT: " + clas +" - " +method );
  293. }
  294. return method;
  295. }
  296. /**
  297. Clear the caches in BshClassManager
  298. @see public void #reset() for external usage
  299. */
  300. protected void clearCaches()
  301. {
  302. absoluteNonClasses = new Hashtable();
  303. absoluteClassCache = new Hashtable();
  304. resolvedObjectMethods = new Hashtable();
  305. resolvedStaticMethods = new Hashtable();
  306. }
  307. /**
  308. Set an external class loader. BeanShell will use this at the same
  309. point it would otherwise use the plain Class.forName().
  310. i.e. if no explicit classpath management is done from the script
  311. (addClassPath(), setClassPath(), reloadClasses()) then BeanShell will
  312. only use the supplied classloader. If additional classpath management
  313. is done then BeanShell will perform that in addition to the supplied
  314. external classloader.
  315. However BeanShell is not currently able to reload
  316. classes supplied through the external classloader.
  317. */
  318. public void setClassLoader( ClassLoader externalCL )
  319. {
  320. externalClassLoader = externalCL;
  321. classLoaderChanged();
  322. }
  323. public void addClassPath( URL path )
  324. throws IOException {
  325. }
  326. /**
  327. Clear all loaders and start over. No class loading.
  328. */
  329. public void reset() {
  330. clearCaches();
  331. }
  332. /**
  333. Set a new base classpath and create a new base classloader.
  334. This means all types change.
  335. */
  336. public void setClassPath( URL [] cp )
  337. throws UtilEvalError
  338. {
  339. throw cmUnavailable();
  340. }
  341. /**
  342. Overlay the entire path with a new class loader.
  343. Set the base path to the user path + base path.
  344. No point in including the boot class path (can't reload thos).
  345. */
  346. public void reloadAllClasses() throws UtilEvalError {
  347. throw cmUnavailable();
  348. }
  349. /**
  350. Reloading classes means creating a new classloader and using it
  351. whenever we are asked for classes in the appropriate space.
  352. For this we use a DiscreteFilesClassLoader
  353. */
  354. public void reloadClasses( String [] classNames )
  355. throws UtilEvalError
  356. {
  357. throw cmUnavailable();
  358. }
  359. /**
  360. Reload all classes in the specified package: e.g. "com.sun.tools"
  361. The special package name "<unpackaged>" can be used to refer
  362. to unpackaged classes.
  363. */
  364. public void reloadPackage( String pack )
  365. throws UtilEvalError
  366. {
  367. throw cmUnavailable();
  368. }
  369. /**
  370. This has been removed from the interface to shield the core from the
  371. rest of the classpath package. If you need the classpath you will have
  372. to cast the classmanager to its impl.
  373. public BshClassPath getClassPath() throws ClassPathException;
  374. */
  375. /**
  376. Support for "import *;"
  377. Hide details in here as opposed to NameSpace.
  378. */
  379. protected void doSuperImport()
  380. throws UtilEvalError
  381. {
  382. throw cmUnavailable();
  383. }
  384. /**
  385. A "super import" ("import *") operation has been performed.
  386. */
  387. protected boolean hasSuperImport()
  388. {
  389. return false;
  390. }
  391. /**
  392. Return the name or null if none is found,
  393. Throw an ClassPathException containing detail if name is ambigous.
  394. */
  395. protected String getClassNameByUnqName( String name )
  396. throws UtilEvalError
  397. {
  398. throw cmUnavailable();
  399. }
  400. public void addListener( Listener l ) { }
  401. public void removeListener( Listener l ) { }
  402. public void dump( PrintWriter pw ) {
  403. pw.println("BshClassManager: no class manager.");
  404. }
  405. /**
  406. Flag the class name as being in the process of being defined.
  407. The class manager will not attempt to load it.
  408. */
  409. /*
  410. Note: this implementation is temporary. We currently keep a flat
  411. namespace of the base name of classes. i.e. BeanShell cannot be in the
  412. process of defining two classes in different packages with the same
  413. base name. To remove this limitation requires that we work through
  414. namespace imports in an analogous (or using the same path) as regular
  415. class import resolution. This workaround should handle most cases
  416. so we'll try it for now.
  417. */
  418. protected void definingClass( String className ) {
  419. String baseName = Name.suffix(className,1);
  420. int i = baseName.indexOf("$");
  421. if ( i != -1 )
  422. baseName = baseName.substring(i+1);
  423. String cur = (String)definingClassesBaseNames.get( baseName );
  424. if ( cur != null )
  425. throw new InterpreterError("Defining class problem: "+className
  426. +": BeanShell cannot yet simultaneously define two or more "
  427. +"dependant classes of the same name. Attempt to define: "
  428. + className +" while defining: "+cur
  429. );
  430. definingClasses.put( className, NOVALUE );
  431. definingClassesBaseNames.put( baseName, className );
  432. }
  433. protected boolean isClassBeingDefined( String className ) {
  434. return definingClasses.get( className ) != null;
  435. }
  436. /**
  437. This method is a temporary workaround used with definingClass.
  438. It is to be removed at some point.
  439. */
  440. protected String getClassBeingDefined( String className ) {
  441. String baseName = Name.suffix(className,1);
  442. return (String)definingClassesBaseNames.get( baseName );
  443. }
  444. /**
  445. Indicate that the specified class name has been defined and may be
  446. loaded normally.
  447. */
  448. protected void doneDefiningClass( String className ) {
  449. String baseName = Name.suffix(className,1);
  450. definingClasses.remove( className );
  451. definingClassesBaseNames.remove( baseName );
  452. }
  453. /*
  454. Issues to resolve here...
  455. 1) In which classloader should we define the class?
  456. if there is a BshClassLoader should we define it there?
  457. 2) should we use reflection to set it in a non-bsh classloader
  458. if there is one or should we always create a bsh classloader
  459. (and expose its defineClass)?
  460. */
  461. public Class defineClass( String name, byte [] code )
  462. {
  463. ClassLoader cl = this.getClass().getClassLoader();
  464. Class clas;
  465. try {
  466. clas = (Class)Reflect.invokeObjectMethod(
  467. cl, "defineClass",
  468. new Object [] {
  469. name, code,
  470. new Primitive( (int)0 )/*offset*/,
  471. new Primitive( code.length )/*len*/
  472. },
  473. (Interpreter)null, (CallStack)null, (SimpleNode)null
  474. );
  475. } catch ( Exception e ) {
  476. e.printStackTrace();
  477. throw new InterpreterError("Unable to define class: "+ e );
  478. }
  479. absoluteNonClasses.remove( name ); // may have been axed previously
  480. return clas;
  481. }
  482. protected void classLoaderChanged() { }
  483. /**
  484. Annotate the NoClassDefFoundError with some info about the class
  485. we were trying to load.
  486. */
  487. protected static Error noClassDefFound( String className, Error e ) {
  488. return new NoClassDefFoundError(
  489. "A class required by class: "+className +" could not be loaded:\n"
  490. +e.toString() );
  491. }
  492. protected static UtilEvalError cmUnavailable() {
  493. return new Capabilities.Unavailable(
  494. "ClassLoading features unavailable.");
  495. }
  496. public static interface Listener
  497. {
  498. public void classLoaderChanged();
  499. }
  500. /**
  501. SignatureKey serves as a hash of a method signature on a class
  502. for fast lookup of overloaded and general resolved Java methods.
  503. <p>
  504. */
  505. /*
  506. Note: is using SignatureKey in this way dangerous? In the pathological
  507. case a user could eat up memory caching every possible combination of
  508. argument types to an untyped method. Maybe we could be smarter about
  509. it by ignoring the types of untyped parameter positions? The method
  510. resolver could return a set of "hints" for the signature key caching?
  511. There is also the overhead of creating one of these for every method
  512. dispatched. What is the alternative?
  513. */
  514. static class SignatureKey
  515. {
  516. Class clas;
  517. Class [] types;
  518. String methodName;
  519. int hashCode = 0;
  520. SignatureKey( Class clas, String methodName, Class [] types ) {
  521. this.clas = clas;
  522. this.methodName = methodName;
  523. this.types = types;
  524. }
  525. public int hashCode()
  526. {
  527. if ( hashCode == 0 )
  528. {
  529. hashCode = clas.hashCode() * methodName.hashCode();
  530. if ( types == null ) // no args method
  531. return hashCode;
  532. for( int i =0; i < types.length; i++ ) {
  533. int hc = types[i] == null ? 21 : types[i].hashCode();
  534. hashCode = hashCode*(i+1) + hc;
  535. }
  536. }
  537. return hashCode;
  538. }
  539. public boolean equals( Object o ) {
  540. SignatureKey target = (SignatureKey)o;
  541. if ( types == null )
  542. return target.types == null;
  543. if ( clas != target.clas )
  544. return false;
  545. if ( !methodName.equals( target.methodName ) )
  546. return false;
  547. if ( types.length != target.types.length )
  548. return false;
  549. for( int i =0; i< types.length; i++ )
  550. {
  551. if ( types[i]==null )
  552. {
  553. if ( !(target.types[i]==null) )
  554. return false;
  555. } else
  556. if ( !types[i].equals( target.types[i] ) )
  557. return false;
  558. }
  559. return true;
  560. }
  561. }
  562. }