KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > bsf > BSFManager


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2002 The Apache Software Foundation. All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if
20  * any, must include the following acknowlegement:
21  * "This product includes software developed by the
22  * Apache Software Foundation (http://www.apache.org/)."
23  * Alternately, this acknowlegement may appear in the software itself,
24  * if and wherever such third-party acknowlegements normally appear.
25  *
26  * 4. The names "Apache BSF", "Apache", and "Apache Software Foundation"
27  * must not be used to endorse or promote products derived from
28  * this software without prior written permission. For written
29  * permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache"
32  * nor may "Apache" appear in their names without prior written
33  * permission of the Apache Group.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many individuals
50  * on behalf of the Apache Software Foundation and was originally created by
51  * Sanjiva Weerawarana and others at International Business Machines
52  * Corporation. For more information on the Apache Software Foundation,
53  * please see <http://www.apache.org/>.
54  */

55
56 package org.apache.bsf;
57
58 import java.lang.reflect.*;
59 import java.util.*;
60 import java.io.*;
61 import java.beans.*;
62 import java.security.*;
63
64 import org.apache.bsf.util.*;
65 import org.apache.bsf.debug.*;
66 import org.apache.bsf.debug.util.DebugLog;
67
68 import javax.naming.*;
69
70 /**
71  * This class is the entry point to the bean scripting framework. An
72  * application wishing to integrate scripting to a Java app would
73  * place an instance of a BSFManager in their code and use its services
74  * to register the beans they want to make available for scripting,
75  * load scripting engines, and run scripts.
76  * <p>
77  * BSFManager serves as the registry of available scripting engines
78  * as well. Loading and unloading of scripting engines is
79  * supported as well. Each BSFManager loads one engine per language.
80  * Several BSFManagers can be created per JVM.
81  * <p>
82  * Each BSFManager and engine participate in the debugger framework.
83  * Per JVM, a debug manager is created and manages the different
84  * instances of BSFManagers, which in turn manage the engines.
85  * The debug manager allows remote debugger to register themselves
86  * for a particular language. The debugger will be notified of the
87  * creation and termination of engines for that language of interest.
88  * Each debugger can then ask the engines for its language-specific
89  * debugging interface. Usually, this interface allows the debugger
90  * to register its language-specific callbacks for debugging events.
91  *
92  * @see org.apache.bsf.debug packages for more details.
93  *
94  * @author Sanjiva Weerawarana
95  * @author Matthew J. Duftler
96  * @author Sam Ruby
97  * @author Olivier Gruber (added debugging support)
98  */

99 public class BSFManager {
100     // table of registered scripting engines
101
protected static Hashtable registeredEngines = new Hashtable();
102
103     // mapping of file extensions to languages
104
protected static Hashtable extn2Lang = new Hashtable();
105
106     // table of scripting engine instances created by this manager.
107
// only one instance of a given language engine is created by a single
108
// manager instance.
109
protected Hashtable loadedEngines = new Hashtable();
110
111     // table of registered beans for use by scripting engines.
112
protected ObjectRegistry objectRegistry = new ObjectRegistry();
113
114     // prop change support containing loaded engines to inform when any
115
// of my interesting properties change
116
protected PropertyChangeSupport pcs;
117
118     // the class loader to use if a class loader is needed. Default is
119
// he who loaded me (which may be null in which case its Class.forName).
120
protected ClassLoader JavaDoc classLoader = getClass().getClassLoader();
121
122     // temporary directory to use to dump temporary files into. Note that
123
// if class files are dropped here then unless this dir is in the
124
// classpath or unless the classloader knows to look here, the classes
125
// will not be found.
126
protected String JavaDoc tempDir = ".";
127
128     // classpath used by those that need a classpath
129
protected String JavaDoc classPath;
130
131     // stores BSFDeclaredBeans representing objects
132
// introduced by a client of BSFManager
133
protected Vector declaredBeans = new Vector();
134
135     // Debug manager
136
static BSFDebugManagerImpl gDebugManager;
137
138     //////////////////////////////////////////////////////////////////////
139
//
140
// pre-register engines that BSF supports off the shelf
141
//
142
//////////////////////////////////////////////////////////////////////
143

144     static {
145         try {
146             ResourceBundle rb =
147                 ResourceBundle.getBundle("org.apache.bsf.Languages");
148             Enumeration keys = rb.getKeys();
149             
150             while (keys.hasMoreElements()) {
151                 String JavaDoc key = (String JavaDoc) keys.nextElement();
152                 String JavaDoc value = rb.getString(key);
153                 
154                 StringTokenizer tokens = new StringTokenizer(value, ",");
155                 String JavaDoc className = (String JavaDoc) tokens.nextToken();
156                 
157                 // get the extensions for this language
158
String JavaDoc exts = (String JavaDoc) tokens.nextToken();
159                 StringTokenizer st = new StringTokenizer(exts, "|");
160                 String JavaDoc[] extensions = new String JavaDoc[st.countTokens()];
161                 for (int i = 0; st.hasMoreTokens(); i++) {
162                     extensions[i] = ((String JavaDoc) st.nextToken()).trim();
163                 }
164                 
165                 registerScriptingEngine(key, className, extensions);
166             }
167         }
168         catch (NoSuchElementException nsee) {
169             nsee.printStackTrace();
170             System.err.println("Syntax error in Languages resource bundle");
171         }
172         catch (MissingResourceException mre) {
173             mre.printStackTrace();
174             System.err.println("Initialization error: " + mre.toString());
175         }
176
177         if (Boolean.getBoolean("org.apache.bsf.serverLaunch"))
178             initBSFDebugManager();
179     }
180
181     public BSFManager() {
182         pcs = new PropertyChangeSupport(this);
183         if (gDebugManager != null) gDebugManager.registerManager(this);
184     }
185
186     /**
187      * Apply the given anonymous function of the given language to the given
188      * parameters and return the resulting value.
189      *
190      * @param lang language identifier
191      * @param source (context info) the source of this expression
192      (e.g., filename)
193      * @param lineNo (context info) the line number in source for expr
194      * @param columnNo (context info) the column number in source for expr
195      * @param funcBody the multi-line, value returning script to evaluate
196      * @param paramNames the names of the parameters above assumes
197      * @param arguments values of the above parameters
198      *
199      * @exception BSFException if anything goes wrong while running the script
200      */

201     public Object JavaDoc apply(String JavaDoc lang,
202                         String JavaDoc source,
203                         int lineNo,
204                         int columnNo,
205                         Object JavaDoc funcBody,
206                         Vector paramNames,
207                         Vector arguments)
208         throws BSFException {
209         final BSFEngine e = loadScriptingEngine(lang);
210         final String JavaDoc sourcef = source;
211         final int lineNof = lineNo, columnNof = columnNo;
212         final Object JavaDoc funcBodyf = funcBody;
213         final Vector paramNamesf = paramNames;
214         final Vector argumentsf = arguments;
215         Object JavaDoc result = null;
216
217         try {
218             final Object JavaDoc resultf =
219                 AccessController.doPrivileged(new PrivilegedExceptionAction() {
220                         public Object JavaDoc run() throws Exception JavaDoc {
221                             return e.apply(sourcef, lineNof, columnNof,
222                                            funcBodyf, paramNamesf, argumentsf);
223                         }
224                     });
225             result = resultf;
226         }
227         catch (PrivilegedActionException prive) {
228             throw (BSFException) prive.getException();
229         }
230
231         return result;
232     }
233
234     /**
235      * Compile the application of the given anonymous function of the given
236      * language to the given parameters into the given <tt>CodeBuffer</tt>.
237      *
238      * @param lang language identifier
239      * @param source (context info) the source of this expression
240      (e.g., filename)
241      * @param lineNo (context info) the line number in source for expr
242      * @param columnNo (context info) the column number in source for expr
243      * @param funcBody the multi-line, value returning script to evaluate
244      * @param paramNames the names of the parameters above assumes
245      * @param arguments values of the above parameters
246      * @param cb code buffer to compile into
247      *
248      * @exception BSFException if anything goes wrong while running the script
249      */

250     public void compileApply(String JavaDoc lang,
251                              String JavaDoc source,
252                              int lineNo,
253                              int columnNo,
254                              Object JavaDoc funcBody,
255                              Vector paramNames,
256                              Vector arguments,
257                              CodeBuffer cb)
258         throws BSFException {
259         final BSFEngine e = loadScriptingEngine(lang);
260         final String JavaDoc sourcef = source;
261         final int lineNof = lineNo, columnNof = columnNo;
262         final Object JavaDoc funcBodyf = funcBody;
263         final Vector paramNamesf = paramNames;
264         final Vector argumentsf = arguments;
265         final CodeBuffer cbf = cb;
266         
267         try {
268             AccessController.doPrivileged(new PrivilegedExceptionAction() {
269                     public Object JavaDoc run() throws Exception JavaDoc {
270                         e.compileApply(sourcef, lineNof, columnNof,
271                                        funcBodyf, paramNamesf,
272                                        argumentsf, cbf);
273                         return null;
274                     }
275                 });
276         }
277         catch (PrivilegedActionException prive) {
278             throw (BSFException) prive.getException();
279         }
280     }
281
282     /**
283      * Compile the given expression of the given language into the given
284      * <tt>CodeBuffer</tt>.
285      *
286      * @param lang language identifier
287      * @param source (context info) the source of this expression
288      (e.g., filename)
289      * @param lineNo (context info) the line number in source for expr
290      * @param columnNo (context info) the column number in source for expr
291      * @param expr the expression to compile
292      * @param cb code buffer to compile into
293      *
294      * @exception BSFException if any error while compiling the expression
295      */

296     public void compileExpr(String JavaDoc lang,
297                             String JavaDoc source,
298                             int lineNo,
299                             int columnNo,
300                             Object JavaDoc expr,
301                             CodeBuffer cb)
302         throws BSFException {
303         final BSFEngine e = loadScriptingEngine(lang);
304         final String JavaDoc sourcef = source;
305         final int lineNof = lineNo, columnNof = columnNo;
306         final Object JavaDoc exprf = expr;
307         final CodeBuffer cbf = cb;
308
309         try {
310             AccessController.doPrivileged(new PrivilegedExceptionAction() {
311                     public Object JavaDoc run() throws Exception JavaDoc {
312                         e.compileExpr(sourcef, lineNof, columnNof, exprf, cbf);
313                         return null;
314                     }
315                 });
316         }
317         catch (PrivilegedActionException prive) {
318             throw (BSFException) prive.getException();
319         }
320     }
321
322     /**
323      * Compile the given script of the given language into the given
324      * <tt>CodeBuffer</tt>.
325      *
326      * @param lang language identifier
327      * @param source (context info) the source of this script
328      (e.g., filename)
329      * @param lineNo (context info) the line number in source for script
330      * @param columnNo (context info) the column number in source for script
331      * @param script the script to compile
332      * @param cb code buffer to compile into
333      *
334      * @exception BSFException if any error while compiling the script
335      */

336     public void compileScript(String JavaDoc lang,
337                               String JavaDoc source,
338                               int lineNo,
339                               int columnNo,
340                               Object JavaDoc script,
341                               CodeBuffer cb)
342         throws BSFException {
343         final BSFEngine e = loadScriptingEngine(lang);
344         final String JavaDoc sourcef = source;
345         final int lineNof = lineNo, columnNof = columnNo;
346         final Object JavaDoc scriptf = script;
347         final CodeBuffer cbf = cb;
348
349         try {
350             AccessController.doPrivileged(new PrivilegedExceptionAction() {
351                     public Object JavaDoc run() throws Exception JavaDoc {
352                         e.compileScript(sourcef, lineNof, columnNof,
353                                         scriptf, cbf);
354                         return null;
355                     }
356                 });
357         }
358         catch (PrivilegedActionException prive) {
359             throw (BSFException) prive.getException();
360         }
361     }
362
363     /**
364      * Declare a bean. The difference between declaring and registering
365      * is that engines are spsed to make declared beans "pre-available"
366      * in the scripts as far as possible. That is, if a script author
367      * needs a registered bean, he needs to look it up in some way. However
368      * if he needs a declared bean, the language has the responsibility to
369      * make those beans avaialable "automatically."
370      * <p>
371      * When a bean is declared it is automatically registered as well
372      * so that any declared bean can be gotton to by looking it up as well.
373      * <p>
374      * If any of the languages that are already running in this manager
375      * says they don't like this (by throwing an exception) then this
376      * method will simply quit with that exception. That is, any engines
377      * that come after than in the engine enumeration will not even be
378      * told about this new bean.
379      * <p>
380      * So, in general its best to declare beans before the manager has
381      * been asked to load any engines because then the user can be informed
382      * when an engine rejects it. Also, its much more likely that an engine
383      * can declare a bean at start time than it can at any time.
384      *
385      * @param beanName name to declare bean as
386      * @param bean the bean that's being declared
387      * @param type the type to represent the bean as
388      *
389      * @exception BSFException if any of the languages that are already
390      * running decides to throw an exception when asked to
391      * declare this bean.
392      */

393     public void declareBean(String JavaDoc beanName, Object JavaDoc bean, Class JavaDoc type)
394         throws BSFException {
395         registerBean(beanName, bean);
396
397         BSFDeclaredBean tempBean = new BSFDeclaredBean(beanName, bean, type);
398         declaredBeans.addElement(tempBean);
399
400         Enumeration enginesEnum = loadedEngines.elements();
401         BSFEngine engine;
402         while (enginesEnum.hasMoreElements()) {
403             engine = (BSFEngine) enginesEnum.nextElement();
404             engine.declareBean(tempBean);
405         }
406     }
407
408     /**
409      * Evaluate the given expression of the given language and return the
410      * resulting value.
411      *
412      * @param lang language identifier
413      * @param source (context info) the source of this expression
414      (e.g., filename)
415      * @param lineNo (context info) the line number in source for expr
416      * @param columnNo (context info) the column number in source for expr
417      * @param expr the expression to evaluate
418      *
419      * @exception BSFException if anything goes wrong while running the script
420      */

421     public Object JavaDoc eval(String JavaDoc lang,
422                        String JavaDoc source,
423                        int lineNo,
424                        int columnNo,
425                        Object JavaDoc expr)
426         throws BSFException {
427         final BSFEngine e = loadScriptingEngine(lang);
428         final String JavaDoc sourcef = source;
429         final int lineNof = lineNo, columnNof = columnNo;
430         final Object JavaDoc exprf = expr;
431         Object JavaDoc result = null;
432         
433         try {
434             final Object JavaDoc resultf =
435                 AccessController.doPrivileged(new PrivilegedExceptionAction() {
436                         public Object JavaDoc run() throws Exception JavaDoc {
437                             return e.eval(sourcef, lineNof, columnNof, exprf);
438                         }
439                     });
440             result = resultf;
441         }
442         catch (PrivilegedActionException prive) {
443             throw (BSFException) prive.getException();
444         }
445
446         return result;
447     }
448
449     //////////////////////////////////////////////////////////////////////
450
//
451
// Convenience functions for exec'ing and eval'ing scripts directly
452
// without loading and dealing with engines etc..
453
//
454
//////////////////////////////////////////////////////////////////////
455

456     /**
457      * Execute the given script of the given language.
458      *
459      * @param lang language identifier
460      * @param source (context info) the source of this expression
461      (e.g., filename)
462      * @param lineNo (context info) the line number in source for expr
463      * @param columnNo (context info) the column number in source for expr
464      * @param script the script to execute
465      *
466      * @exception BSFException if anything goes wrong while running the script
467      */

468     public void exec(String JavaDoc lang,
469                      String JavaDoc source,
470                      int lineNo,
471                      int columnNo,
472                      Object JavaDoc script)
473         throws BSFException {
474         final BSFEngine e = loadScriptingEngine(lang);
475         final String JavaDoc sourcef = source;
476         final int lineNof = lineNo, columnNof = columnNo;
477         final Object JavaDoc scriptf = script;
478
479         try {
480             AccessController.doPrivileged(new PrivilegedExceptionAction() {
481                     public Object JavaDoc run() throws Exception JavaDoc {
482                         e.exec(sourcef, lineNof, columnNof, scriptf);
483                         return null;
484                     }
485                 });
486         }
487         catch (PrivilegedActionException prive) {
488             throw (BSFException) prive.getException();
489         }
490     }
491
492     /**
493      * Get classLoader
494      */

495     public ClassLoader JavaDoc getClassLoader() {
496         return classLoader;
497     }
498
499     /**
500      * Get classPath
501      */

502     public String JavaDoc getClassPath() {
503         if (classPath == null) {
504             try {
505                 classPath = System.getProperty("java.class.path");
506             }
507             catch (Throwable JavaDoc t) {
508                 // prolly a security exception .. so no can do
509
}
510         }
511         return classPath;
512     }
513
514     /**
515      * Get debug manager
516      */

517     public static BSFDebugManager getDebugManager() {
518         return gDebugManager;
519     }
520
521     /**
522      * Determine the language of a script file by looking at the file
523      * extension.
524      *
525      * @param filename the name of the file
526      *
527      * @return the scripting language the file is in if the file extension
528      * is known to me (must have been registered via
529      * registerScriptingEngine).
530      *
531      * @exception BSFException if file's extension is unknown.
532      */

533     public static String JavaDoc getLangFromFilename(String JavaDoc fileName)
534         throws BSFException {
535         int dotIndex = fileName.lastIndexOf(".");
536
537         if (dotIndex != -1) {
538             String JavaDoc extn = fileName.substring(dotIndex + 1);
539             String JavaDoc langval = (String JavaDoc) extn2Lang.get(extn), lang = null;
540             int index = 0, loops = 0;
541
542             if (langval != null) {
543                 while ((index = langval.indexOf(":", 0)) != -1) {
544                     // Great. Multiple language engines registered
545
// for this extension.
546
// Try to find first one that is in our classpath.
547
lang = langval.substring(0, index);
548                     langval = langval.substring(index + 1);
549                     loops++;
550
551                     // Test to see if in classpath
552
try {
553                         String JavaDoc engineName =
554                             (String JavaDoc) registeredEngines.get(lang);
555                         Class.forName(engineName);
556                     }
557                     catch (ClassNotFoundException JavaDoc cnfe) {
558                         // Bummer.
559
lang = langval;
560                         continue;
561                     }
562
563                     // Got past that? Good.
564
break;
565                 }
566                 if (loops == 0) lang = langval;
567             }
568             
569             if (lang != null && lang != "") {
570                 return lang;
571             }
572         }
573         throw new BSFException(BSFException.REASON_OTHER_ERROR,
574                                "file extension missing or unknown: "
575                                + "unable to determine language for '"
576                                + fileName
577                                + "'");
578     }
579
580     /**
581      * Return the current object registry of the manager.
582      *
583      * @return the current registry.
584      */

585     public ObjectRegistry getObjectRegistry() {
586         return objectRegistry;
587     }
588
589     /**
590      * Get tempDir
591      */

592     public String JavaDoc getTempDir() {
593         return tempDir;
594     }
595
596     /**
597      * Determine whether a language is registered.
598      *
599      * @param lang string identifying a language
600      *
601      * @return true iff it is
602      */

603     public static boolean isLanguageRegistered(String JavaDoc lang) {
604         return (registeredEngines.get(lang) != null);
605     }
606
607     //////////////////////////////////////////////////////////////////////
608
//
609
// Bean scripting framework services
610
//
611
//////////////////////////////////////////////////////////////////////
612

613     /**
614      * Load a scripting engine based on the lang string identifying it.
615      *
616      * @param lang string identifying language
617      * @exception BSFException if the language is unknown (i.e., if it
618      * has not been registered) with a reason of
619      * REASON_UNKNOWN_LANGUAGE. If the language is known but
620      * if the interface can't be created for some reason, then
621      * the reason is set to REASON_OTHER_ERROR and the actual
622      * exception is passed on as well.
623      */

624     public BSFEngine loadScriptingEngine(String JavaDoc lang) throws BSFException {
625         // if its already loaded return that
626
BSFEngine eng = (BSFEngine) loadedEngines.get(lang);
627         if (eng != null) {
628             return eng;
629         }
630
631         // is it a registered language?
632
String JavaDoc engineClassName = (String JavaDoc) registeredEngines.get(lang);
633         if (engineClassName == null) {
634             throw new BSFException(BSFException.REASON_UNKNOWN_LANGUAGE,
635                                    "unsupported language: " + lang);
636         }
637
638         // create the engine and initialize it. if anything goes wrong
639
// except.
640
try {
641             Class JavaDoc engineClass =
642                 (classLoader == null)
643                 ? Class.forName(engineClassName)
644                 : classLoader.loadClass(engineClassName);
645             final BSFEngine engf = (BSFEngine) engineClass.newInstance();
646             final BSFManager thisf = this;
647             final String JavaDoc langf = lang;
648             final Vector dbf = declaredBeans;
649             AccessController.doPrivileged(new PrivilegedExceptionAction() {
650                     public Object JavaDoc run() throws Exception JavaDoc {
651                         engf.initialize(thisf, langf, dbf);
652                         return null;
653                     }
654                 });
655             eng = engf;
656             loadedEngines.put(lang, eng);
657             pcs.addPropertyChangeListener(eng);
658             return eng;
659         }
660         catch (PrivilegedActionException prive) {
661                 throw (BSFException) prive.getException();
662         }
663         catch (Throwable JavaDoc t) {
664             throw new BSFException(BSFException.REASON_OTHER_ERROR,
665                                    "unable to load language: " + lang,
666                                    t);
667         }
668     }
669
670     /**
671      * return a handle to a bean registered in the bean registry by the
672      * application or a scripting engine. Returns null if bean is not found.
673      *
674      * @param beanName name of bean to look up
675      *
676      * @return the bean if its found or null
677      */

678     public Object JavaDoc lookupBean(String JavaDoc beanName) {
679         try {
680             return objectRegistry.lookup(beanName);
681         }
682         catch (IllegalArgumentException JavaDoc e) {
683             return null;
684         }
685     }
686
687     /**
688      * This is the init for the debugging framework.
689      * The framework relies on a BSFDebugManager,
690      * a unique object per JVM. The DebugManager acts
691      * as a remote server for debuggers to register.
692      * Once a debugger is registered for a given language, such as
693      * javascript, the DebugManager will forward creation/deletion
694      * events to the debugger about BSFManager and BSFEngine
695      * instances.
696      * Debugger can then ask the engine for its language-specific
697      * debug interface and use it for registering its language-specific
698      * callback interface.
699      * From there on, the debugger is connected to the engine.
700      * When the BSFEngine terminates, the debugger will be notified.
701      *
702      */

703     public static void initBSFDebugManager() {
704         if(gDebugManager != null)
705             DebugLog.stdoutPrintln("BSF Debug Manager already running...",
706                                    DebugLog.BSF_LOG_L1);
707         else {
708             DebugLog.stdoutPrintln("BSF in Debug Mode...",
709                                    DebugLog.BSF_LOG_L1);
710             try {
711                 // Instantiate our BSF Debug Manager...
712
// One per JVM.
713
AccessController.doPrivileged(new PrivilegedExceptionAction() {
714                         public Object JavaDoc run() throws Exception JavaDoc {
715                             System.setProperty("org.apache.bsf.isServer",
716                                                "true");
717                             return null;
718                         }
719                     });
720                 
721                 gDebugManager = new BSFDebugManagerImpl();
722             }
723             catch (PrivilegedActionException prive) {
724                 Exception JavaDoc e = prive.getException();
725                 System.err.println("Cannot set up debug manager: "
726                                    + e.getMessage());
727                 e.printStackTrace();
728                 System.err.println("Execution continues without debugging.");
729             }
730             catch (Exception JavaDoc e) {
731                 System.err.println("BSF Factory cannot bound BSF Manager: "
732                                    + e.getMessage());
733                 e.printStackTrace();
734                 System.err.println("Ignoring... Execution continues...");
735             }
736         }
737     }
738
739     /**
740      * Registering a bean allows a scripting engine or the application to
741      * access that bean by name and to manipulate it.
742      *
743      * @param beanName name to register under
744      * @param bean the bean to register
745      */

746     public void registerBean(String JavaDoc beanName, Object JavaDoc bean) {
747         objectRegistry.register(beanName, bean);
748     }
749
750     /**
751      * Register a scripting engine in the static registry of the
752      * BSFManager.
753      *
754      * @param lang string identifying language
755      * @param engineClassName fully qualified name of the class interfacing
756      * the language to BSF.
757      * @param extensions array of file extensions that should be mapped to
758      * this language type. may be null.
759      */

760     public static void registerScriptingEngine(String JavaDoc lang,
761                                                String JavaDoc engineClassName,
762                                                String JavaDoc[] extensions) {
763         registeredEngines.put(lang, engineClassName);
764         if (extensions != null) {
765             for (int i = 0; i < extensions.length; i++) {
766                 String JavaDoc langstr = (String JavaDoc) extn2Lang.get(extensions[i]);
767                 langstr = (langstr == null) ? lang : lang + ":" + langstr;
768                 extn2Lang.put(extensions[i], langstr);
769             }
770         }
771     }
772
773     /**
774      * Set the class loader for those that need to use it. Default is he
775      * who loaded me or null (i.e., its Class.forName).
776      *
777      * @param classLoader the class loader to use.
778      */

779     public void setClassLoader(ClassLoader JavaDoc classLoader) {
780         pcs.firePropertyChange("classLoader", this.classLoader, classLoader);
781         this.classLoader = classLoader;
782     }
783
784     /**
785      * Set the classpath for those that need to use it. Default is the value
786      * of the java.class.path property.
787      *
788      * @param classPath the classpath to use
789      */

790     public void setClassPath(String JavaDoc classPath) {
791         pcs.firePropertyChange("classPath", this.classPath, classPath);
792         this.classPath = classPath;
793     }
794
795     /**
796      * Set the object registry used by this manager. By default a new
797      * one is created when the manager is new'ed and this overwrites
798      * that one.
799      *
800      * @param objectRegistry the registry to use
801      */

802     public void setObjectRegistry(ObjectRegistry objectRegistry) {
803         this.objectRegistry = objectRegistry;
804     }
805
806     /**
807      * Temporary directory to put stuff into (for those who need to). Note
808      * that unless this directory is in the classpath or unless the
809      * classloader knows to look in here, any classes here will not
810      * be found! BSFManager provides a service method to load a class
811      * which uses either the classLoader provided by the class loader
812      * property or, if that fails, a class loader which knows to load from
813      * the tempdir to try to load the class. Default value of tempDir
814      * is "." (current working dir).
815      *
816      * @param tempDir the temporary directory
817      */

818     public void setTempDir(String JavaDoc tempDir) {
819         pcs.firePropertyChange("tempDir", this.tempDir, tempDir);
820         this.tempDir = tempDir;
821     }
822
823     /**
824      * Gracefully terminate all engines
825      */

826     public void terminate() {
827         Enumeration enginesEnum = loadedEngines.elements();
828         BSFEngine engine;
829         while (enginesEnum.hasMoreElements()) {
830             engine = (BSFEngine) enginesEnum.nextElement();
831             engine.terminate();
832         }
833
834         loadedEngines = new Hashtable();
835
836         if (gDebugManager != null)
837             gDebugManager.terminateManagerNotify(this);
838     }
839
840     /**
841      * Undeclare a previously declared bean. This removes the bean from
842      * the list of declared beans in the manager as well as asks every
843      * running engine to undeclared the bean. As with above, if any
844      * of the engines except when asked to undeclare, this method does
845      * not catch that exception. Quietly returns if the bean is unknown.
846      *
847      * @param beanName name of bean to undeclare
848      *
849      * @exception BSFException if any of the languages that are already
850      * running decides to throw an exception when asked to
851      * undeclare this bean.
852      */

853     public void undeclareBean(String JavaDoc beanName) throws BSFException {
854         unregisterBean(beanName);
855
856         BSFDeclaredBean tempBean = null;
857         for (int i = 0; i < declaredBeans.size(); i++) {
858             tempBean = (BSFDeclaredBean) declaredBeans.elementAt(i);
859             if (tempBean.name.equals(beanName)) {
860                 break;
861             }
862         }
863
864         if (tempBean != null) {
865             declaredBeans.removeElement(tempBean);
866
867             Enumeration enginesEnum = loadedEngines.elements();
868             while (enginesEnum.hasMoreElements()) {
869                 BSFEngine engine = (BSFEngine) enginesEnum.nextElement();
870                 engine.undeclareBean(tempBean);
871             }
872         }
873     }
874
875     /**
876      * Unregister a previously registered bean. Silent if name is not found.
877      *
878      * @param beanName name of bean to unregister
879      */

880     public void unregisterBean(String JavaDoc beanName) {
881         objectRegistry.unregister(beanName);
882     }
883 }
884
Popular Tags