PageRenderTime 46ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

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

#
Java | 340 lines | 131 code | 30 blank | 179 comment | 29 complexity | dded4a069dbe12495eedc4fcd0f12d29 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.io.IOException;
  35. /**
  36. 'This' is the type of bsh scripted objects.
  37. A 'This' object is a bsh scripted object context. It holds a namespace
  38. reference and implements event listeners and various other interfaces.
  39. This holds a reference to the declaring interpreter for callbacks from
  40. outside of bsh.
  41. */
  42. public class This implements java.io.Serializable, Runnable
  43. {
  44. /**
  45. The namespace that this This reference wraps.
  46. */
  47. NameSpace namespace;
  48. /**
  49. This is the interpreter running when the This ref was created.
  50. It's used as a default interpreter for callback through the This
  51. where there is no current interpreter instance
  52. e.g. interface proxy or event call backs from outside of bsh.
  53. */
  54. transient Interpreter declaringInterpreter;
  55. /**
  56. getThis() is a factory for bsh.This type references. The capabilities
  57. of ".this" references in bsh are version dependent up until jdk1.3.
  58. The version dependence was to support different default interface
  59. implementations. i.e. different sets of listener interfaces which
  60. scripted objects were capable of implementing. In jdk1.3 the
  61. reflection proxy mechanism was introduced which allowed us to
  62. implement arbitrary interfaces. This is fantastic.
  63. A This object is a thin layer over a namespace, comprising a bsh object
  64. context. We create it here only if needed for the namespace.
  65. Note: this method could be considered slow because of the way it
  66. dynamically factories objects. However I've also done tests where
  67. I hard-code the factory to return JThis and see no change in the
  68. rough test suite time. This references are also cached in NameSpace.
  69. */
  70. static This getThis(
  71. NameSpace namespace, Interpreter declaringInterpreter )
  72. {
  73. try {
  74. Class c;
  75. if ( Capabilities.canGenerateInterfaces() )
  76. c = Class.forName( "bsh.XThis" );
  77. else if ( Capabilities.haveSwing() )
  78. c = Class.forName( "bsh.JThis" );
  79. else
  80. return new This( namespace, declaringInterpreter );
  81. return (This)Reflect.constructObject( c,
  82. new Object [] { namespace, declaringInterpreter } );
  83. } catch ( Exception e ) {
  84. throw new InterpreterError("internal error 1 in This: "+e);
  85. }
  86. }
  87. /**
  88. Get a version of this scripted object implementing the specified
  89. interface.
  90. */
  91. /*
  92. If this type of This implements it directly return this,
  93. else try complain that we don't have the proxy mechanism.
  94. */
  95. public Object getInterface( Class clas )
  96. throws UtilEvalError
  97. {
  98. if ( clas.isInstance( this ) )
  99. return this;
  100. else
  101. throw new UtilEvalError( "Dynamic proxy mechanism not available. "
  102. + "Cannot construct interface type: "+clas );
  103. }
  104. /**
  105. Get a version of this scripted object implementing the specified
  106. interfaces.
  107. */
  108. public Object getInterface( Class [] ca )
  109. throws UtilEvalError
  110. {
  111. for(int i=0; i<ca.length; i++)
  112. if ( !(ca[i].isInstance( this )) )
  113. throw new UtilEvalError(
  114. "Dynamic proxy mechanism not available. "
  115. + "Cannot construct interface type: "+ca[i] );
  116. return this;
  117. }
  118. /*
  119. I wish protected access were limited to children and not also
  120. package scope... I want this to be a singleton implemented by various
  121. children.
  122. */
  123. protected This( NameSpace namespace, Interpreter declaringInterpreter ) {
  124. this.namespace = namespace;
  125. this.declaringInterpreter = declaringInterpreter;
  126. //initCallStack( namespace );
  127. }
  128. public NameSpace getNameSpace() {
  129. return namespace;
  130. }
  131. public String toString() {
  132. return "'this' reference to Bsh object: " + namespace;
  133. }
  134. public void run() {
  135. try {
  136. invokeMethod( "run", new Object[0] );
  137. } catch( EvalError e ) {
  138. declaringInterpreter.error(
  139. "Exception in runnable:" + e );
  140. }
  141. }
  142. /**
  143. Invoke specified method as from outside java code, using the
  144. declaring interpreter and current namespace.
  145. The call stack will indicate that the method is being invoked from
  146. outside of bsh in native java code.
  147. Note: you must still wrap/unwrap args/return values using
  148. Primitive/Primitive.unwrap() for use outside of BeanShell.
  149. @see bsh.Primitive
  150. */
  151. public Object invokeMethod( String name, Object [] args )
  152. throws EvalError
  153. {
  154. // null callstack, one will be created for us
  155. return invokeMethod(
  156. name, args, null/*declaringInterpreter*/, null, null,
  157. false/*declaredOnly*/ );
  158. }
  159. /**
  160. Invoke a method in this namespace with the specified args,
  161. interpreter reference, callstack, and caller info.
  162. <p>
  163. Note: If you use this method outside of the bsh package and wish to
  164. use variables with primitive values you will have to wrap them using
  165. bsh.Primitive. Consider using This getInterface() to make a true Java
  166. interface for invoking your scripted methods.
  167. <p>
  168. This method also implements the default object protocol of toString(),
  169. hashCode() and equals() and the invoke() meta-method handling as a
  170. last resort.
  171. <p>
  172. Note: The invoke() meta-method will not catch the Object protocol
  173. methods (toString(), hashCode()...). If you want to override them you
  174. have to script them directly.
  175. <p>
  176. @see bsh.This.invokeMethod(
  177. String methodName, Object [] args, Interpreter interpreter,
  178. CallStack callstack, SimpleNode callerInfo )
  179. @param if callStack is null a new CallStack will be created and
  180. initialized with this namespace.
  181. @param declaredOnly if true then only methods declared directly in the
  182. namespace will be visible - no inherited or imported methods will
  183. be visible.
  184. @see bsh.Primitive
  185. */
  186. /*
  187. invokeMethod() here is generally used by outside code to callback
  188. into the bsh interpreter. e.g. when we are acting as an interface
  189. for a scripted listener, etc. In this case there is no real call stack
  190. so we make a default one starting with the special JAVACODE namespace
  191. and our namespace as the next.
  192. */
  193. public Object invokeMethod(
  194. String methodName, Object [] args,
  195. Interpreter interpreter, CallStack callstack, SimpleNode callerInfo,
  196. boolean declaredOnly )
  197. throws EvalError
  198. {
  199. /*
  200. Wrap nulls.
  201. This is a bit of a cludge to address a deficiency in the class
  202. generator whereby it does not wrap nulls on method delegate. See
  203. Class Generator.java. If we fix that then we can remove this.
  204. (just have to generate the code there.)
  205. */
  206. if ( args != null )
  207. {
  208. Object [] oa = new Object [args.length];
  209. for(int i=0; i<args.length; i++)
  210. oa[i] = ( args[i] == null ? Primitive.NULL : args[i] );
  211. args = oa;
  212. }
  213. if ( interpreter == null )
  214. interpreter = declaringInterpreter;
  215. if ( callstack == null )
  216. callstack = new CallStack( namespace );
  217. if ( callerInfo == null )
  218. callerInfo = SimpleNode.JAVACODE;
  219. // Find the bsh method
  220. Class [] types = Types.getTypes( args );
  221. BshMethod bshMethod = null;
  222. try {
  223. bshMethod = namespace.getMethod( methodName, types, declaredOnly );
  224. } catch ( UtilEvalError e ) {
  225. // leave null
  226. }
  227. if ( bshMethod != null )
  228. return bshMethod.invoke( args, interpreter, callstack, callerInfo );
  229. /*
  230. No scripted method of that name.
  231. Implement the required part of the Object protocol:
  232. public int hashCode();
  233. public boolean equals(java.lang.Object);
  234. public java.lang.String toString();
  235. if these were not handled by scripted methods we must provide
  236. a default impl.
  237. */
  238. // a default toString() that shows the interfaces we implement
  239. if ( methodName.equals("toString" ) )
  240. return toString();
  241. // a default hashCode()
  242. if ( methodName.equals("hashCode" ) )
  243. return new Integer(this.hashCode());
  244. // a default equals() testing for equality with the This reference
  245. if ( methodName.equals("equals" ) ) {
  246. Object obj = args[0];
  247. return new Boolean( this == obj );
  248. }
  249. // Look for a default invoke() handler method in the namespace
  250. // Note: this code duplicates that in NameSpace getCommand()
  251. // is that ok?
  252. try {
  253. bshMethod = namespace.getMethod(
  254. "invoke", new Class [] { null, null } );
  255. } catch ( UtilEvalError e ) { /*leave null*/ }
  256. // Call script "invoke( String methodName, Object [] args );
  257. if ( bshMethod != null )
  258. return bshMethod.invoke( new Object [] { methodName, args },
  259. interpreter, callstack, callerInfo );
  260. throw new EvalError("Method " +
  261. StringUtil.methodString( methodName, types ) +
  262. " not found in bsh scripted object: "+ namespace.getName(),
  263. callerInfo, callstack );
  264. }
  265. /**
  266. Bind a This reference to a parent's namespace with the specified
  267. declaring interpreter. Also re-init the callstack. It's necessary
  268. to bind a This reference before it can be used after deserialization.
  269. This is used by the bsh load() command.
  270. <p>
  271. This is a static utility method because it's used by a bsh command
  272. bind() and the interpreter doesn't currently allow access to direct
  273. methods of This objects (small hack)
  274. */
  275. public static void bind(
  276. This ths, NameSpace namespace, Interpreter declaringInterpreter )
  277. {
  278. ths.namespace.setParent( namespace );
  279. ths.declaringInterpreter = declaringInterpreter;
  280. }
  281. /**
  282. Allow invocations of these method names on This type objects.
  283. Don't give bsh.This a chance to override their behavior.
  284. <p>
  285. If the method is passed here the invocation will actually happen on
  286. the bsh.This object via the regular reflective method invocation
  287. mechanism. If not, then the method is evaluated by bsh.This itself
  288. as a scripted method call.
  289. */
  290. static boolean isExposedThisMethod( String name )
  291. {
  292. return
  293. name.equals("getClass")
  294. || name.equals("invokeMethod")
  295. || name.equals("getInterface")
  296. // These are necessary to let us test synchronization from scripts
  297. || name.equals("wait")
  298. || name.equals("notify")
  299. || name.equals("notifyAll");
  300. }
  301. }