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
035 package bsh;
036
037 import java.util.*;
038
039 import java.io.InputStream;
040 import java.io.BufferedReader;
041 import java.io.InputStreamReader;
042 import java.io.IOException;
043
044 import java.lang.reflect.Method;
045 import java.lang.reflect.Field;
046
047 /**
048 A namespace in which methods, variables, and imports (class names) live.
049 This is package public because it is used in the implementation of some
050 bsh commands. However for normal use you should be using methods on
051 bsh.Interpreter to interact with your scripts.
052 <p>
053
054 A bsh.This object is a thin layer over a NameSpace that associates it with
055 an Interpreter instance. Together they comprise a Bsh scripted object
056 context.
057 <p>
058
059 Note: I'd really like to use collections here, but we have to keep this
060 compatible with JDK1.1
061 */
062 /*
063 Thanks to Slava Pestov (of jEdit fame) for import caching enhancements.
064 Note: This class has gotten too big. It should be broken down a bit.
065 */
066 public class NameSpace
067 implements java.io.Serializable, BshClassManager.Listener,
068 NameSource
069 {
070 public static final NameSpace JAVACODE =
071 new NameSpace((BshClassManager)null, "Called from compiled Java code.");
072 static {
073 JAVACODE.isMethod = true;
074 }
075
076 // Begin instance data
077 // Note: if we add something here we should reset it in the clear() method.
078
079 /**
080 The name of this namespace. If the namespace is a method body
081 namespace then this is the name of the method. If it's a class or
082 class instance then it's the name of the class.
083 */
084 private String nsName;
085 private NameSpace parent;
086 private Hashtable variables;
087 private Hashtable methods;
088
089 protected Hashtable importedClasses;
090 private Vector importedPackages;
091 private Vector importedCommands;
092 private Vector importedObjects;
093 private Vector importedStatic;
094 private String packageName;
095
096 transient private BshClassManager classManager;
097
098 // See notes in getThis()
099 private This thisReference;
100
101 /** Name resolver objects */
102 private Hashtable names;
103
104 /** The node associated with the creation of this namespace.
105 This is used support getInvocationLine() and getInvocationText(). */
106 SimpleNode callerInfoNode;
107
108 /**
109 Note that the namespace is a method body namespace. This is used for
110 printing stack traces in exceptions.
111 */
112 boolean isMethod;
113 /**
114 Note that the namespace is a class body or class instance namespace.
115 This is used for controlling static/object import precedence, etc.
116 */
117 /*
118 Note: We will ll move this behavior out to a subclass of
119 NameSpace, but we'll start here.
120 */
121 boolean isClass;
122 Class classStatic;
123 Object classInstance;
124
125 void setClassStatic( Class clas ) {
126 this.classStatic = clas;
127 importStatic( clas );
128 }
129 void setClassInstance( Object instance ) {
130 this.classInstance = instance;
131 importObject( instance );
132 }
133 Object getClassInstance()
134 throws UtilEvalError
135 {
136 if ( classInstance != null )
137 return classInstance;
138
139 if ( classStatic != null
140 //|| ( getParent()!=null && getParent().classStatic != null )
141 )
142 throw new UtilEvalError(
143 "Can't refer to class instance from static context.");
144 else
145 throw new InterpreterError(
146 "Can't resolve class instance 'this' in: "+this);
147 }
148
149
150 /**
151 Local class cache for classes resolved through this namespace using
152 getClass() (taking into account imports). Only unqualified class names
153 are cached here (those which might be imported). Qualified names are
154 always absolute and are cached by BshClassManager.
155 */
156 transient private Hashtable classCache;
157
158 // End instance data
159
160 // Begin constructors
161
162 /**
163 @parent the parent namespace of this namespace. Child namespaces
164 inherit all variables and methods of their parent and can (of course)
165 override / shadow them.
166 */
167 public NameSpace( NameSpace parent, String name )
168 {
169 // Note: in this case parent must have a class manager.
170 this( parent, null, name );
171 }
172
173 public NameSpace( BshClassManager classManager, String name )
174 {
175 this( null, classManager, name );
176 }
177
178 public NameSpace(
179 NameSpace parent, BshClassManager classManager, String name )
180 {
181 // We might want to do this here rather than explicitly in Interpreter
182 // for global (see also prune())
183 //if ( classManager == null && (parent == null ) )
184 // create our own class manager?
185
186 setName(name);
187 setParent(parent);
188 setClassManager( classManager );
189
190 // Register for notification of classloader change
191 if ( classManager != null )
192 classManager.addListener(this);
193 }
194
195 // End constructors
196
197 public void setName( String name ) {
198 this.nsName = name;
199 }
200
201 /**
202 The name of this namespace. If the namespace is a method body
203 namespace then this is the name of the method. If it's a class or
204 class instance then it's the name of the class.
205 */
206 public String getName() {
207 return this.nsName;
208 }
209
210 /**
211 Set the node associated with the creation of this namespace.
212 This is used in debugging and to support the getInvocationLine()
213 and getInvocationText() methods.
214 */
215 void setNode( SimpleNode node ) {
216 callerInfoNode = node;
217 }
218
219 /**
220 */
221 SimpleNode getNode()
222 {
223 if ( callerInfoNode != null )
224 return callerInfoNode;
225 if ( parent != null )
226 return parent.getNode();
227 else
228 return null;
229 }
230
231 /**
232 Resolve name to an object through this namespace.
233 */
234 public Object get( String name, Interpreter interpreter )
235 throws UtilEvalError
236 {
237 CallStack callstack = new CallStack( this );
238 return getNameResolver( name ).toObject( callstack, interpreter );
239 }
240
241 /**
242 Set the variable through this namespace.
243 This method obeys the LOCALSCOPING property to determine how variables
244 are set.
245 <p>
246 Note: this method is primarily intended for use internally. If you use
247 this method outside of the bsh package and wish to set variables with
248 primitive values you will have to wrap them using bsh.Primitive.
249 @see bsh.Primitive
250 <p>
251 Setting a new variable (which didn't exist before) or removing
252 a variable causes a namespace change.
253
254 @param strictJava specifies whether strict java rules are applied.
255 */
256 public void setVariable( String name, Object value, boolean strictJava )
257 throws UtilEvalError
258 {
259 // if localscoping switch follow strictJava, else recurse
260 boolean recurse = Interpreter.LOCALSCOPING ? strictJava : true;
261 setVariable( name, value, strictJava, recurse );
262 }
263
264 /**
265 Set a variable explicitly in the local scope.
266 */
267 void setLocalVariable(
268 String name, Object value, boolean strictJava )
269 throws UtilEvalError
270 {
271 setVariable( name, value, strictJava, false/*recurse*/ );
272 }
273
274 /**
275 Set the value of a the variable 'name' through this namespace.
276 The variable may be an existing or non-existing variable.
277 It may live in this namespace or in a parent namespace if recurse is
278 true.
279 <p>
280 Note: This method is not public and does *not* know about LOCALSCOPING.
281 Its caller methods must set recurse intelligently in all situations
282 (perhaps based on LOCALSCOPING).
283
284 <p>
285 Note: this method is primarily intended for use internally. If you use
286 this method outside of the bsh package and wish to set variables with
287 primitive values you will have to wrap them using bsh.Primitive.
288 @see bsh.Primitive
289 <p>
290 Setting a new variable (which didn't exist before) or removing
291 a variable causes a namespace change.
292
293 @param strictJava specifies whether strict java rules are applied.
294 @param recurse determines whether we will search for the variable in
295 our parent's scope before assigning locally.
296 */
297 void setVariable(
298 String name, Object value, boolean strictJava, boolean recurse )
299 throws UtilEvalError
300 {
301 if ( variables == null )
302 variables = new Hashtable();
303
304 // primitives should have been wrapped
305 if ( value == null )
306 throw new InterpreterError("null variable value");
307
308 // Locate the variable definition if it exists.
309 Variable existing = getVariableImpl( name, recurse );
310
311 // Found an existing variable here (or above if recurse allowed)
312 if ( existing != null )
313 {
314 try {
315 existing.setValue( value, Variable.ASSIGNMENT );
316 } catch ( UtilEvalError e ) {
317 throw new UtilEvalError(
318 "Variable assignment: " + name + ": " + e.getMessage());
319 }
320 } else
321 // No previous variable definition found here (or above if recurse)
322 {
323 if ( strictJava )
324 throw new UtilEvalError(
325 "(Strict Java mode) Assignment to undeclared variable: "
326 +name );
327
328 // If recurse, set global untyped var, else set it here.
329 //NameSpace varScope = recurse ? getGlobal() : this;
330 // This modification makes default allocation local
331 NameSpace varScope = this;
332
333 varScope.variables.put(
334 name, new Variable( name, value, null/*modifiers*/ ) );
335
336 // nameSpaceChanged() on new variable addition
337 nameSpaceChanged();
338 }
339 }
340
341 /**
342 Remove the variable from the namespace.
343 */
344 public void unsetVariable( String name )
345 {
346 if ( variables != null )
347 {
348 variables.remove( name );
349 nameSpaceChanged();
350 }
351 }
352
353 /**
354 Get the names of variables defined in this namespace.
355 (This does not show variables in parent namespaces).
356 */
357 public String [] getVariableNames() {
358 if ( variables == null )
359 return new String [0];
360 else
361 return enumerationToStringArray( variables.keys() );
362 }
363
364 /**
365 Get the names of methods declared in this namespace.
366 (This does not include methods in parent namespaces).
367 */
368 public String [] getMethodNames()
369 {
370 if ( methods == null )
371 return new String [0];
372 else
373 return enumerationToStringArray( methods.keys() );
374 }
375
376 /**
377 Get the methods defined in this namespace.
378 (This does not show methods in parent namespaces).
379 Note: This will probably be renamed getDeclaredMethods()
380 */
381 public BshMethod [] getMethods()
382 {
383 if ( methods == null )
384 return new BshMethod [0];
385 else
386 return flattenMethodCollection( methods.elements() );
387 }
388
389 private String [] enumerationToStringArray( Enumeration e ) {
390 Vector v = new Vector();
391 while ( e.hasMoreElements() )
392 v.addElement( e.nextElement() );
393 String [] sa = new String [ v.size() ];
394 v.copyInto( sa );
395 return sa;
396 }
397
398 /**
399 Flatten the vectors of overloaded methods to a single array.
400 @see #getMethods()
401 */
402 private BshMethod [] flattenMethodCollection( Enumeration e ) {
403 Vector v = new Vector();
404 while ( e.hasMoreElements() ) {
405 Object o = e.nextElement();
406 if ( o instanceof BshMethod )
407 v.addElement( o );
408 else {
409 Vector ov = (Vector)o;
410 for(int i=0; i<ov.size(); i++)
411 v.addElement( ov.elementAt( i ) );
412 }
413 }
414 BshMethod [] bma = new BshMethod [ v.size() ];
415 v.copyInto( bma );
416 return bma;
417 }
418
419 /**
420 Get the parent namespace.
421 Note: this isn't quite the same as getSuper().
422 getSuper() returns 'this' if we are at the root namespace.
423 */
424 public NameSpace getParent() {
425 return parent;
426 }
427
428 /**
429 Get the parent namespace' This reference or this namespace' This
430 reference if we are the top.
431 */
432 public This getSuper( Interpreter declaringInterpreter )
433 {
434 if ( parent != null )
435 return parent.getThis( declaringInterpreter );
436 else
437 return getThis( declaringInterpreter );
438 }
439
440 /**
441 Get the top level namespace or this namespace if we are the top.
442 Note: this method should probably return type bsh.This to be consistent
443 with getThis();
444 */
445 public This getGlobal( Interpreter declaringInterpreter )
446 {
447 if ( parent != null )
448 return parent.getGlobal( declaringInterpreter );
449 else
450 return getThis( declaringInterpreter );
451 }
452
453
454 /**
455 A This object is a thin layer over a namespace, comprising a bsh object
456 context. It handles things like the interface types the bsh object
457 supports and aspects of method invocation on it.
458 <p>
459
460 The declaringInterpreter is here to support callbacks from Java through
461 generated proxies. The scripted object "remembers" who created it for
462 things like printing messages and other per-interpreter phenomenon
463 when called externally from Java.
464 */
465 /*
466 Note: we need a singleton here so that things like 'this == this' work
467 (and probably a good idea for speed).
468
469 Caching a single instance here seems technically incorrect,
470 considering the declaringInterpreter could be different under some
471 circumstances. (Case: a child interpreter running a source() / eval()
472 command ). However the effect is just that the main interpreter that
473 executes your script should be the one involved in call-backs from Java.
474
475 I do not know if there are corner cases where a child interpreter would
476 be the first to use a This reference in a namespace or if that would
477 even cause any problems if it did... We could do some experiments
478 to find out... and if necessary we could cache on a per interpreter
479 basis if we had weak references... We might also look at skipping
480 over child interpreters and going to the parent for the declaring
481 interpreter, so we'd be sure to get the top interpreter.
482 */
483 This getThis( Interpreter declaringInterpreter )
484 {
485 if ( thisReference == null )
486 thisReference = This.getThis( this, declaringInterpreter );
487
488 return thisReference;
489 }
490
491 public BshClassManager getClassManager()
492 {
493 if ( classManager != null )
494 return classManager;
495 if ( parent != null && parent != JAVACODE )
496 return parent.getClassManager();
497
498 System.out.println("experiment: creating class manager");
499 classManager = BshClassManager.createClassManager( null/*interp*/ );
500
501 //Interpreter.debug("No class manager namespace:" +this);
502 return classManager;
503 }
504
505 void setClassManager( BshClassManager classManager ) {
506 this.classManager = classManager;
507 }
508
509 /**
510 Used for serialization
511 */
512 public void prune()
513 {
514 // Cut off from parent, we must have our own class manager.
515 // Can't do this in the run() command (needs to resolve stuff)
516 // Should we do it by default when we create a namespace will no
517 // parent of class manager?
518
519 if ( this.classManager == null )
520 // XXX if we keep the createClassManager in getClassManager then we can axe
521 // this?
522 setClassManager(
523 BshClassManager.createClassManager( null/*interp*/ ) );
524
525 setParent( null );
526 }
527
528 public void setParent( NameSpace parent )
529 {
530 this.parent = parent;
531
532 // If we are disconnected from root we need to handle the def imports
533 if ( parent == null )
534 loadDefaultImports();
535 }
536
537 /**
538 Get the specified variable in this namespace or a parent namespace.
539 <p>
540 Note: this method is primarily intended for use internally. If you use
541 this method outside of the bsh package you will have to use
542 Primitive.unwrap() to get primitive values.
543 @see Primitive#unwrap( Object )
544
545 @return The variable value or Primitive.VOID if it is not defined.
546 */
547 public Object getVariable( String name )
548 throws UtilEvalError
549 {
550 return getVariable( name, true );
551 }
552
553 /**
554 Get the specified variable in this namespace.
555 @param recurse If recurse is true then we recursively search through
556 parent namespaces for the variable.
557 <p>
558 Note: this method is primarily intended for use internally. If you use
559 this method outside of the bsh package you will have to use
560 Primitive.unwrap() to get primitive values.
561 @see Primitive#unwrap( Object )
562
563 @return The variable value or Primitive.VOID if it is not defined.
564 */
565 public Object getVariable( String name, boolean recurse )
566 throws UtilEvalError
567 {
568 Variable var = getVariableImpl( name, recurse );
569 return unwrapVariable( var );
570 }
571
572 /**
573 Locate a variable and return the Variable object with optional
574 recursion through parent name spaces.
575 <p/>
576 If this namespace is static, return only static variables.
577
578 @return the Variable value or null if it is not defined
579 */
580 protected Variable getVariableImpl( String name, boolean recurse )
581 throws UtilEvalError
582 {
583 Variable var = null;
584
585 // Change import precedence if we are a class body/instance
586 // Get imported first.
587 if ( var == null && isClass )
588 var = getImportedVar( name );
589
590 if ( var == null && variables != null )
591 var = (Variable)variables.get(name);
592
593 // Change import precedence if we are a class body/instance
594 if ( var == null && !isClass )
595 var = getImportedVar( name );
596
597 // try parent
598 if ( recurse && (var == null) && (parent != null) )
599 var = parent.getVariableImpl( name, recurse );
600
601 return var;
602 }
603
604 /*
605 Get variables declared in this namespace.
606 */
607 public Variable [] getDeclaredVariables()
608 {
609 if ( variables == null )
610 return new Variable[0];
611 Variable [] vars = new Variable [ variables.size() ];
612 int i=0;
613 for( Enumeration e = variables.elements(); e.hasMoreElements(); )
614 vars[i++] = (Variable)e.nextElement();
615 return vars;
616 }
617
618 /**
619 Unwrap a variable to its value.
620 @return return the variable value. A null var is mapped to
621 Primitive.VOID
622 */
623 protected Object unwrapVariable( Variable var )
624 throws UtilEvalError
625 {
626 return (var == null) ? Primitive.VOID : var.getValue();
627 }
628
629 /**
630 @deprecated See #setTypedVariable( String, Class, Object, Modifiers )
631 */
632 public void setTypedVariable(
633 String name, Class type, Object value, boolean isFinal )
634 throws UtilEvalError
635 {
636 Modifiers modifiers = new Modifiers();
637 if ( isFinal )
638 modifiers.addModifier( Modifiers.FIELD, "final" );
639 setTypedVariable( name, type, value, modifiers );
640 }
641
642 /**
643 Declare a variable in the local scope and set its initial value.
644 Value may be null to indicate that we would like the default value
645 for the variable type. (e.g. 0 for integer types, null for object
646 types). An existing typed variable may only be set to the same type.
647 If an untyped variable of the same name exists it will be overridden
648 with the new typed var.
649 The set will perform a Types.getAssignableForm() on the value if
650 necessary.
651
652 <p>
653 Note: this method is primarily intended for use internally. If you use
654 this method outside of the bsh package and wish to set variables with
655 primitive values you will have to wrap them using bsh.Primitive.
656 @see bsh.Primitive
657
658 @param value If value is null, you'll get the default value for the type
659 @param modifiers may be null
660 */
661 public void setTypedVariable(
662 String name, Class type, Object value, Modifiers modifiers )
663 throws UtilEvalError
664 {
665 //checkVariableModifiers( name, modifiers );
666
667 if ( variables == null )
668 variables = new Hashtable();
669
670 // Setting a typed variable is always a local operation.
671 Variable existing = getVariableImpl( name, false/*recurse*/ );
672
673
674 // Null value is just a declaration
675 // Note: we might want to keep any existing value here instead of reset
676 /*
677 // Moved to Variable
678 if ( value == null )
679 value = Primitive.getDefaultValue( type );
680 */
681
682 // does the variable already exist?
683 if ( existing != null )
684 {
685 // Is it typed?
686 if ( existing.getType() != null )
687 {
688 // If it had a different type throw error.
689 // This allows declaring the same var again, but not with
690 // a different (even if assignable) type.
691 if ( existing.getType() != type )
692 {
693 throw new UtilEvalError( "Typed variable: "+name
694 +" was previously declared with type: "
695 + existing.getType() );
696 } else
697 {
698 // else set it and return
699 existing.setValue( value, Variable.DECLARATION );
700 return;
701 }
702 }
703 // Careful here:
704 // else fall through to override and install the new typed version
705 }
706
707 // Add the new typed var
708 variables.put( name, new Variable( name, type, value, modifiers ) );
709 }
710
711 /**
712 Dissallow static vars outside of a class
713 @param name is here just to allow the error message to use it
714 protected void checkVariableModifiers( String name, Modifiers modifiers )
715 throws UtilEvalError
716 {
717 if ( modifiers!=null && modifiers.hasModifier("static") )
718 throw new UtilEvalError(
719 "Can't declare static variable outside of class: "+name );
720 }
721 */
722
723 /**
724 Note: this is primarily for internal use.
725 @see Interpreter#source( String )
726 @see Interpreter#eval( String )
727 */
728 public void setMethod( String name, BshMethod method )
729 throws UtilEvalError
730 {
731 //checkMethodModifiers( method );
732
733 if ( methods == null )
734 methods = new Hashtable();
735
736 Object m = methods.get(name);
737
738 if ( m == null )
739 methods.put(name, method);
740 else
741 if ( m instanceof BshMethod ) {
742 Vector v = new Vector();
743 v.addElement( m );
744 v.addElement( method );
745 methods.put( name, v );
746 } else // Vector
747 ((Vector)m).addElement( method );
748 }
749
750 /**
751 @see #getMethod( String, Class [], boolean )
752 @see #getMethod( String, Class [] )
753 */
754 public BshMethod getMethod( String name, Class [] sig )
755 throws UtilEvalError
756 {
757 return getMethod( name, sig, false/*declaredOnly*/ );
758 }
759
760 /**
761 Get the bsh method matching the specified signature declared in
762 this name space or a parent.
763 <p>
764 Note: this method is primarily intended for use internally. If you use
765 this method outside of the bsh package you will have to be familiar
766 with BeanShell's use of the Primitive wrapper class.
767 @see bsh.Primitive
768 @return the BshMethod or null if not found
769 @param declaredOnly if true then only methods declared directly in this
770 namespace will be found and no inherited or imported methods will
771 be visible.
772 */
773 public BshMethod getMethod(
774 String name, Class [] sig, boolean declaredOnly )
775 throws UtilEvalError
776 {
777 BshMethod method = null;
778
779 // Change import precedence if we are a class body/instance
780 // Get import first.
781 if ( method == null && isClass && !declaredOnly )
782 method = getImportedMethod( name, sig );
783
784 Object m = null;
785 if ( method == null && methods != null )
786 {
787 m = methods.get(name);
788
789 // m contains either BshMethod or Vector of BshMethod
790 if ( m != null )
791 {
792 // unwrap
793 BshMethod [] ma;
794 if ( m instanceof Vector )
795 {
796 Vector vm = (Vector)m;
797 ma = new BshMethod[ vm.size() ];
798 vm.copyInto( ma );
799 } else
800 ma = new BshMethod[] { (BshMethod)m };
801
802 // Apply most specific signature matching
803 Class [][] candidates = new Class[ ma.length ][];
804 for( int i=0; i< ma.length; i++ )
805 candidates[i] = ma[i].getParameterTypes();
806
807 int match =
808 Reflect.findMostSpecificSignature( sig, candidates );
809 if ( match != -1 )
810 method = ma[match];
811 }
812 }
813
814 if ( method == null && !isClass && !declaredOnly )
815 method = getImportedMethod( name, sig );
816
817 // try parent
818 if ( !declaredOnly && (method == null) && (parent != null) )
819 return parent.getMethod( name, sig );
820
821 return method;
822 }
823
824 /**
825 Import a class name.
826 Subsequent imports override earlier ones
827 */
828 public void importClass(String name)
829 {
830 if ( importedClasses == null )
831 importedClasses = new Hashtable();
832
833 importedClasses.put( Name.suffix(name, 1), name );
834 nameSpaceChanged();
835 }
836
837 /**
838 subsequent imports override earlier ones
839 */
840 public void importPackage(String name)
841 {
842 if(importedPackages == null)
843 importedPackages = new Vector();
844
845 // If it exists, remove it and add it at the end (avoid memory leak)
846 if ( importedPackages.contains( name ) )
847 importedPackages.remove( name );
848
849 importedPackages.addElement(name);
850 nameSpaceChanged();
851 }
852
853 /**
854 Import scripted or compiled BeanShell commands in the following package
855 in the classpath. You may use either "/" path or "." package notation.
856 e.g. importCommands("/bsh/commands") or importCommands("bsh.commands")
857 are equivalent. If a relative path style specifier is used then it is
858 made into an absolute path by prepending "/".
859 */
860 public void importCommands( String name )
861 {
862 if ( importedCommands == null )
863 importedCommands = new Vector();
864
865 // dots to slashes
866 name = name.replace('.','/');
867 // absolute
868 if ( !name.startsWith("/") )
869 name = "/"+name;
870 // remove trailing (but preserve case of simple "/")
871 if ( name.length() > 1 && name.endsWith("/") )
872 name = name.substring( 0, name.length()-1 );
873
874 // If it exists, remove it and add it at the end (avoid memory leak)
875 if ( importedCommands.contains( name ) )
876 importedCommands.remove( name );
877
878 importedCommands.addElement(name);
879 nameSpaceChanged();
880 }
881
882 /**
883 A command is a scripted method or compiled command class implementing a
884 specified method signature. Commands are loaded from the classpath
885 and may be imported using the importCommands() method.
886 <p/>
887
888 This method searches the imported commands packages for a script or
889 command object corresponding to the name of the method. If it is a
890 script the script is sourced into this namespace and the BshMethod for
891 the requested signature is returned. If it is a compiled class the
892 class is returned. (Compiled command classes implement static invoke()
893 methods).
894 <p/>
895
896 The imported packages are searched in reverse order, so that later
897 imports take priority.
898 Currently only the first object (script or class) with the appropriate
899 name is checked. If another, overloaded form, is located in another
900 package it will not currently be found. This could be fixed.
901 <p/>
902
903 @return a BshMethod, Class, or null if no such command is found.
904 @param name is the name of the desired command method
905 @param argTypes is the signature of the desired command method.
906 @throws UtilEvalError if loadScriptedCommand throws UtilEvalError
907 i.e. on errors loading a script that was found
908 */
909 public Object getCommand(
910 String name, Class [] argTypes, Interpreter interpreter )
911 throws UtilEvalError
912 {
913 if (Interpreter.DEBUG) Interpreter.debug("getCommand: "+name);
914 BshClassManager bcm = interpreter.getClassManager();
915
916 if ( importedCommands != null )
917 {
918 // loop backwards for precedence
919 for(int i=importedCommands.size()-1; i>=0; i--)
920 {
921 String path = (String)importedCommands.elementAt(i);
922
923 String scriptPath;
924 if ( path.equals("/") )
925 scriptPath = path + name +".bsh";
926 else
927 scriptPath = path +"/"+ name +".bsh";
928
929 Interpreter.debug("searching for script: "+scriptPath );
930
931 InputStream in = bcm.getResourceAsStream( scriptPath );
932
933 if ( in != null )
934 return loadScriptedCommand(
935 in, name, argTypes, scriptPath, interpreter );
936
937 // Chop leading "/" and change "/" to "."
938 String className;
939 if ( path.equals("/") )
940 className = name;
941 else
942 className = path.substring(1).replace('/','.') +"."+name;
943
944 Interpreter.debug("searching for class: "+className);
945 Class clas = bcm.classForName( className );
946 if ( clas != null )
947 return clas;
948 }
949 }
950
951 if ( parent != null )
952 return parent.getCommand( name, argTypes, interpreter );
953 else
954 return null;
955 }
956
957 protected BshMethod getImportedMethod( String name, Class [] sig )
958 throws UtilEvalError
959 {
960 // Try object imports
961 if ( importedObjects != null )
962 for(int i=0; i<importedObjects.size(); i++)
963 {
964 Object object = importedObjects.elementAt(i);
965 Class clas = object.getClass();
966 Method method = Reflect.resolveJavaMethod(
967 getClassManager(), clas, name, sig, false/*onlyStatic*/ );
968 if ( method != null )
969 return new BshMethod( method, object );
970 }
971
972 // Try static imports
973 if ( importedStatic!= null )
974 for(int i=0; i<importedStatic.size(); i++)
975 {
976 Class clas = (Class)importedStatic.elementAt(i);
977 Method method = Reflect.resolveJavaMethod(
978 getClassManager(), clas, name, sig, true/*onlyStatic*/ );
979 if ( method != null )
980 return new BshMethod( method, null/*object*/ );
981 }
982
983 return null;
984 }
985
986 protected Variable getImportedVar( String name )
987 throws UtilEvalError
988 {
989 // Try object imports
990 if ( importedObjects != null )
991 for(int i=0; i<importedObjects.size(); i++)
992 {
993 Object object = importedObjects.elementAt(i);
994 Class clas = object.getClass();
995 Field field = Reflect.resolveJavaField(
996 clas, name, false/*onlyStatic*/ );
997 if ( field != null )
998 return new Variable(
999 name, field.getType(), new LHS( object, field ) );
1000 }
1001
1002 // Try static imports
1003 if ( importedStatic!= null )
1004 for(int i=0; i<importedStatic.size(); i++)
1005 {
1006 Class clas = (Class)importedStatic.elementAt(i);
1007 Field field = Reflect.resolveJavaField(
1008 clas, name, true/*onlyStatic*/ );
1009 if ( field != null )
1010 return new Variable( name, field.getType(), new LHS( field ) );
1011 }
1012
1013 return null;
1014 }
1015
1016 /**
1017 Load a command script from the input stream and find the BshMethod in
1018 the target namespace.
1019 @throws UtilEvalError on error in parsing the script or if the the
1020 method is not found after parsing the script.
1021 */
1022 /*
1023 If we want to support multiple commands in the command path we need to
1024 change this to not throw the exception.
1025 */
1026 private BshMethod loadScriptedCommand(
1027 InputStream in, String name, Class [] argTypes, String resourcePath,
1028 Interpreter interpreter )
1029 throws UtilEvalError
1030 {
1031 try {
1032 interpreter.eval(
1033 new InputStreamReader(in), this, resourcePath );
1034 } catch ( EvalError e ) {
1035 /*
1036 Here we catch any EvalError from the interpreter because we are
1037 using it as a tool to load the command, not as part of the
1038 execution path.
1039 */
1040 Interpreter.debug( e.toString() );
1041 throw new UtilEvalError(
1042 "Error loading script: "+ e.getMessage());
1043 }
1044
1045 // Look for the loaded command
1046 BshMethod meth = getMethod( name, argTypes );
1047 /*
1048 if ( meth == null )
1049 throw new UtilEvalError("Loaded resource: " + resourcePath +
1050 "had an error or did not contain the correct method" );
1051 */
1052
1053 return meth;
1054 }
1055
1056 /**
1057 Helper that caches class.
1058 */
1059 void cacheClass( String name, Class c ) {
1060 if ( classCache == null ) {
1061 classCache = new Hashtable();
1062 //cacheCount++; // debug
1063 }
1064
1065 classCache.put(name, c);
1066 }
1067
1068 /**
1069 Load a class through this namespace taking into account imports.
1070 The class search will proceed through the parent namespaces if
1071 necessary.
1072
1073 @return null if not found.
1074 */
1075 public Class getClass( String name )
1076 throws UtilEvalError
1077 {
1078 Class c = getClassImpl(name);
1079 if ( c != null )
1080 return c;
1081 else
1082 // implement the recursion for getClassImpl()
1083 if ( parent != null )
1084 return parent.getClass( name );
1085 else
1086 return null;
1087 }
1088
1089 /**
1090 Implementation of getClass()
1091
1092 Load a class through this namespace taking into account imports.
1093 <p>
1094
1095 Check the cache first. If an unqualified name look for imported
1096 class or package. Else try to load absolute name.
1097 <p>
1098
1099 This method implements caching of unqualified names (normally imports).
1100 Qualified names are cached by the BshClassManager.
1101 Unqualified absolute class names (e.g. unpackaged Foo) are cached too
1102 so that we don't go searching through the imports for them each time.
1103
1104 @return null if not found.
1105 */
1106 private Class getClassImpl( String name )
1107 throws UtilEvalError
1108 {
1109 Class c = null;
1110
1111 // Check the cache
1112 if (classCache != null) {
1113 c = (Class)classCache.get(name);
1114
1115 if ( c != null )
1116 return c;
1117 }
1118
1119 // Unqualified (simple, non-compound) name
1120 boolean unqualifiedName = !Name.isCompound(name);
1121
1122 // Unqualified name check imported
1123 if ( unqualifiedName )
1124 {
1125 // Try imported class
1126 if ( c == null )
1127 c = getImportedClassImpl( name );
1128
1129 // if found as imported also cache it
1130 if ( c != null ) {
1131 cacheClass( name, c );
1132 return c;
1133 }
1134 }
1135
1136 // Try absolute
1137 c = classForName( name );
1138 if ( c != null ) {
1139 // Cache unqualified names to prevent import check again
1140 if ( unqualifiedName )
1141 cacheClass( name, c );
1142 return c;
1143 }
1144
1145 // Not found
1146 if ( Interpreter.DEBUG )
1147 Interpreter.debug("getClass(): " + name + " not found in "+this);
1148 return null;
1149 }
1150
1151 /**
1152 Try to make the name into an imported class.
1153 This method takes into account only imports (class or package)
1154 found directly in this NameSpace (no parent chain).
1155 */
1156 private Class getImportedClassImpl( String name )
1157 throws UtilEvalError
1158 {
1159 // Try explicitly imported class, e.g. import foo.Bar;
1160 String fullname = null;
1161 if ( importedClasses != null )
1162 fullname = (String)importedClasses.get(name);
1163
1164 // not sure if we should really recurse here for explicitly imported
1165 // class in parent...
1166
1167 if ( fullname != null )
1168 {
1169 /*
1170 Found the full name in imported classes.
1171 */
1172 // Try to make the full imported name
1173 Class clas=classForName(fullname);
1174
1175 // Handle imported inner class case
1176 if ( clas == null )
1177 {
1178 // Imported full name wasn't found as an absolute class
1179 // If it is compound, try to resolve to an inner class.
1180 // (maybe this should happen in the BshClassManager?)
1181
1182 if ( Name.isCompound( fullname ) )
1183 try {
1184 clas = getNameResolver( fullname ).toClass();
1185 } catch ( ClassNotFoundException e ) { /* not a class */ }
1186 else
1187 if ( Interpreter.DEBUG ) Interpreter.debug(
1188 "imported unpackaged name not found:" +fullname);
1189
1190 // If found cache the full name in the BshClassManager
1191 if ( clas != null ) {
1192 // (should we cache info in not a class case too?)
1193 getClassManager().cacheClassInfo( fullname, clas );
1194 return clas;
1195 }
1196 } else
1197 return clas;
1198
1199 // It was explicitly imported, but we don't know what it is.
1200 // should we throw an error here??
1201 return null;
1202 }
1203
1204 /*
1205 Try imported packages, e.g. "import foo.bar.*;"
1206 in reverse order of import...
1207 (give later imports precedence...)
1208 */
1209 if ( importedPackages != null )
1210 for(int i=importedPackages.size()-1; i>=0; i--)
1211 {
1212 String s = ((String)importedPackages.elementAt(i)) + "." + name;
1213 Class c=classForName(s);
1214 if ( c != null )
1215 return c;
1216 }
1217
1218 BshClassManager bcm = getClassManager();
1219 /*
1220 Try super import if available
1221 Note: we do this last to allow explicitly imported classes
1222 and packages to take priority. This method will also throw an
1223 error indicating ambiguity if it exists...
1224 */
1225 if ( bcm.hasSuperImport() )
1226 {
1227 String s = bcm.getClassNameByUnqName( name );
1228 if ( s != null )
1229 return classForName( s );
1230 }
1231
1232 return null;
1233 }
1234
1235 private Class classForName( String name )
1236 {
1237 return getClassManager().classForName( name );
1238 }
1239
1240 /**
1241 Implements NameSource
1242 @return all variable and method names in this and all parent
1243 namespaces
1244 */
1245 public String [] getAllNames()
1246 {
1247 Vector vec = new Vector();
1248 getAllNamesAux( vec );
1249 String [] names = new String [ vec.size() ];
1250 vec.copyInto( names );
1251 return names;
1252 }
1253
1254 /**
1255 Helper for implementing NameSource
1256 */
1257 protected void getAllNamesAux( Vector vec )
1258 {
1259 Enumeration varNames = variables.keys();
1260 while( varNames.hasMoreElements() )
1261 vec.addElement( varNames.nextElement() );
1262
1263 Enumeration methodNames = methods.keys();
1264 while( methodNames.hasMoreElements() )
1265 vec.addElement( methodNames.nextElement() );
1266
1267 if ( parent != null )
1268 parent.getAllNamesAux( vec );
1269 }
1270
1271 Vector nameSourceListeners;
1272 /**
1273 Implements NameSource
1274 Add a listener who is notified upon changes to names in this space.
1275 */
1276 public void addNameSourceListener( NameSource.Listener listener ) {
1277 if ( nameSourceListeners == null )
1278 nameSourceListeners = new Vector();
1279 nameSourceListeners.addElement( listener );
1280 }
1281
1282 /**
1283 Perform "import *;" causing the entire classpath to be mapped.
1284 This can take a while.
1285 */
1286 public void doSuperImport()
1287 throws UtilEvalError
1288 {
1289 getClassManager().doSuperImport();
1290 }
1291
1292
1293 public String toString() {
1294 return "NameSpace: "
1295 + ( nsName==null
1296 ? super.toString()
1297 : nsName + " (" + super.toString() +")" )
1298 + ( isClass ? " (isClass) " : "" )
1299 + ( isMethod ? " (method) " : "" )
1300 + ( classStatic != null ? " (class static) " : "" )
1301 + ( classInstance != null ? " (class instance) " : "" );
1302 }
1303
1304 /*
1305 For serialization.
1306 Don't serialize non-serializable objects.
1307 */
1308 private synchronized void writeObject(java.io.ObjectOutputStream s)
1309 throws IOException
1310 {
1311 // clear name resolvers... don't know if this is necessary.
1312 names = null;
1313
1314 s.defaultWriteObject();
1315 }
1316
1317 /**
1318 Invoke a method in this namespace with the specified args and
1319 interpreter reference. No caller information or call stack is
1320 required. The method will appear as if called externally from Java.
1321 <p>
1322
1323 @see bsh.This.invokeMethod(
1324 String methodName, Object [] args, Interpreter interpreter,
1325 CallStack callstack, SimpleNode callerInfo, boolean )
1326 */
1327 public Object invokeMethod(
1328 String methodName, Object [] args, Interpreter interpreter )
1329 throws EvalError
1330 {
1331 return invokeMethod(
1332 methodName, args, interpreter, null, null );
1333 }
1334
1335 /**
1336 This method simply delegates to This.invokeMethod();
1337 <p>
1338 @see bsh.This.invokeMethod(
1339 String methodName, Object [] args, Interpreter interpreter,
1340 CallStack callstack, SimpleNode callerInfo )
1341 */
1342 public Object invokeMethod(
1343 String methodName, Object [] args, Interpreter interpreter,
1344 CallStack callstack, SimpleNode callerInfo )
1345 throws EvalError
1346 {
1347 return getThis( interpreter ).invokeMethod(
1348 methodName, args, interpreter, callstack, callerInfo,
1349 false/*declaredOnly*/ );
1350 }
1351
1352 /**
1353 Clear all cached classes and names
1354 */
1355 public void classLoaderChanged() {
1356 nameSpaceChanged();
1357 }
1358
1359 /**
1360 Clear all cached classes and names
1361 */
1362 public void nameSpaceChanged() {
1363 classCache = null;
1364 names = null;
1365 }
1366
1367 /**
1368 Import standard packages. Currently:
1369 <pre>
1370 importClass("bsh.EvalError");
1371 importClass("bsh.Interpreter");
1372 importPackage("javax.swing.event");
1373 importPackage("javax.swing");
1374 importPackage("java.awt.event");
1375 importPackage("java.awt");
1376 importPackage("java.net");
1377 importPackage("java.util");
1378 importPackage("java.io");
1379 importPackage("java.lang");
1380 importCommands("/bsh/commands");
1381 </pre>
1382 */
1383 public void loadDefaultImports()
1384 {
1385 /**
1386 Note: the resolver looks through these in reverse order, per
1387 precedence rules... so for max efficiency put the most common
1388 ones later.
1389 */
1390 importClass("bsh.EvalError");
1391 importClass("bsh.Interpreter");
1392 importPackage("javax.swing.event");
1393 importPackage("javax.swing");
1394 importPackage("java.awt.event");
1395 importPackage("java.awt");
1396 importPackage("java.net");
1397 importPackage("java.util");
1398 importPackage("java.io");
1399 importPackage("java.lang");
1400 importCommands("/bsh/commands");
1401 }
1402
1403 /**
1404 This is the factory for Name objects which resolve names within
1405 this namespace (e.g. toObject(), toClass(), toLHS()).
1406 <p>
1407
1408 This was intended to support name resolver caching, allowing
1409 Name objects to cache info about the resolution of names for
1410 performance reasons. However this not proven useful yet.
1411 <p>
1412
1413 We'll leave the caching as it will at least minimize Name object
1414 creation.
1415 <p>
1416
1417 (This method would be called getName() if it weren't already used for
1418 the simple name of the NameSpace)
1419 <p>
1420
1421 This method was public for a time, which was a mistake.
1422 Use get() instead.
1423 */
1424 Name getNameResolver( String ambigname )
1425 {
1426 if ( names == null )
1427 names = new Hashtable();
1428
1429 Name name = (Name)names.get( ambigname );
1430
1431 if ( name == null ) {
1432 name = new Name( this, ambigname );
1433 names.put( ambigname, name );
1434 }
1435
1436 return name;
1437 }
1438
1439 public int getInvocationLine() {
1440 SimpleNode node = getNode();
1441 if ( node != null )
1442 return node.getLineNumber();
1443 else
1444 return -1;
1445 }
1446 public String getInvocationText() {
1447 SimpleNode node = getNode();
1448 if ( node != null )
1449 return node.getText();
1450 else
1451 return "<invoked from Java code>";
1452 }
1453
1454 /**
1455 This is a helper method for working inside of bsh scripts and commands.
1456 In that context it is impossible to see a ClassIdentifier object
1457 for what it is. Attempting to access a method on a ClassIdentifier
1458 will look like a static method invocation.
1459
1460 This method is in NameSpace for convenience (you don't have to import
1461 bsh.ClassIdentifier to use it );
1462 */
1463 public static Class identifierToClass( ClassIdentifier ci )
1464 {
1465 return ci.getTargetClass();
1466 }
1467
1468
1469 /**
1470 Clear all variables, methods, and imports from this namespace.
1471 If this namespace is the root, it will be reset to the default
1472 imports.
1473 @see #loadDefaultImports()
1474 */
1475 public void clear()
1476 {
1477 variables = null;
1478 methods = null;
1479 importedClasses = null;
1480 importedPackages = null;
1481 importedCommands = null;
1482 importedObjects = null;
1483 if ( parent == null )
1484 loadDefaultImports();
1485 classCache = null;
1486 names = null;
1487 }
1488
1489 /**
1490 Import a compiled Java object's methods and variables into this
1491 namespace. When no scripted method / command or variable is found
1492 locally in this namespace method / fields of the object will be
1493 checked. Objects are checked in the order of import with later imports
1494 taking precedence.
1495 <p/>
1496 */
1497 /*
1498 Note: this impor pattern is becoming common... could factor it out into
1499 an importedObject Vector class.
1500 */
1501 public void importObject( Object obj )
1502 {
1503 if ( importedObjects == null )
1504 importedObjects = new Vector();
1505
1506 // If it exists, remove it and add it at the end (avoid memory leak)
1507 if ( importedObjects.contains( obj ) )
1508 importedObjects.remove( obj );
1509
1510 importedObjects.addElement( obj );
1511 nameSpaceChanged();
1512
1513 }
1514
1515 /**
1516 */
1517 public void importStatic( Class clas )
1518 {
1519 if ( importedStatic == null )
1520 importedStatic = new Vector();
1521
1522 // If it exists, remove it and add it at the end (avoid memory leak)
1523 if ( importedStatic.contains( clas ) )
1524 importedStatic.remove( clas );
1525
1526 importedStatic.addElement( clas );
1527 nameSpaceChanged();
1528 }
1529
1530 /**
1531 Set the package name for classes defined in this namespace.
1532 Subsequent sets override the package.
1533 */
1534 void setPackage( String packageName )
1535 {
1536 this.packageName = packageName;
1537 }
1538
1539 String getPackage()
1540 {
1541 if ( packageName != null )
1542 return packageName;
1543
1544 if ( parent != null )
1545 return parent.getPackage();
1546
1547 return null;
1548 }
1549 }
1550