bsfmanager.java

来自「Bean Scripting Framework (BSF)为在java应用中使」· Java 代码 · 共 911 行 · 第 1/3 页

JAVA
911
字号
/* * Copyright 2004,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.bsf;import java.beans.PropertyChangeSupport;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.security.AccessController;import java.security.PrivilegedActionException;import java.security.PrivilegedExceptionAction;import java.util.Enumeration;import java.util.Hashtable;import java.util.Iterator;import java.util.MissingResourceException;import java.util.NoSuchElementException;import java.util.Properties;import java.util.StringTokenizer;import java.util.Vector;import org.apache.bsf.util.CodeBuffer;import org.apache.bsf.util.ObjectRegistry;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;/** * This class is the entry point to the bean scripting framework. An * application wishing to integrate scripting to a Java app would * place an instance of a BSFManager in their code and use its services * to register the beans they want to make available for scripting, * load scripting engines, and run scripts. * <p> * BSFManager serves as the registry of available scripting engines * as well. Loading and unloading of scripting engines is * supported as well. Each BSFManager loads one engine per language. * Several BSFManagers can be created per JVM. * * @author   Sanjiva Weerawarana * @author   Matthew J. Duftler * @author   Sam Ruby * @author   Olivier Gruber (added original debugging support) * @author   Don Schwarz (added support for registering languages dynamically) */public class BSFManager {    // version string is in the form "abc.yyyymmdd" where    // "abc" represents a dewey decimal number (three levels, each between 0 and 9),    // and "yyyy" a four digit year, "mm" a two digit month, "dd" a two digit day.    //    // Example: "240.20060925" stands for: BSF version "2.4.0" as of "2006-09-25"    protected static String version="240.20061006";    // table of registered scripting engines    protected static Hashtable registeredEngines = new Hashtable();    // mapping of file extensions to languages    protected static Hashtable extn2Lang = new Hashtable();    // table of scripting engine instances created by this manager.    // only one instance of a given language engine is created by a single    // manager instance.    protected Hashtable loadedEngines = new Hashtable();    // table of registered beans for use by scripting engines.    protected ObjectRegistry objectRegistry = new ObjectRegistry();    // prop change support containing loaded engines to inform when any    // of my interesting properties change    protected PropertyChangeSupport pcs;    // the class loader to use if a class loader is needed. Default is    // he who loaded me (which may be null in which case its Class.forName).    // protected ClassLoader classLoader = getClass().getClassLoader();    protected ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // rgf, 2006-01-05    // temporary directory to use to dump temporary files into. Note that    // if class files are dropped here then unless this dir is in the    // classpath or unless the classloader knows to look here, the classes    // will not be found.    protected String tempDir = ".";    // classpath used by those that need a classpath    protected String classPath;    // stores BSFDeclaredBeans representing objects    // introduced by a client of BSFManager    protected Vector declaredBeans = new Vector();    private Log logger = LogFactory.getLog(this.getClass().getName());    //////////////////////////////////////////////////////////////////////    //    // pre-register engines that BSF supports off the shelf    //    //////////////////////////////////////////////////////////////////////    static {        try {            Enumeration e = BSFManager.class.getClassLoader().getResources("org/apache/bsf/Languages.properties");            while (e.hasMoreElements()) {                URL url = (URL)e.nextElement();                InputStream is = url.openStream();                Properties p = new Properties();                p.load(is);                for (Enumeration keys = p.propertyNames(); keys.hasMoreElements();) {                    String key = (String) keys.nextElement();                    String value = p.getProperty(key);                    String className = value.substring(0, value.indexOf(","));                    // get the extensions for this language                    String exts = value.substring(value.indexOf(",")+1, value.length());                    StringTokenizer st = new StringTokenizer(exts, "|");                    String[] extensions = new String[st.countTokens()];                    for (int i = 0; st.hasMoreTokens(); i++) {                        extensions[i] = ((String) st.nextToken()).trim();                    }                    registerScriptingEngine(key, className, extensions);                }            }        } catch (IOException ex) {            ex.printStackTrace();            System.err.println("Error reading Languages file " + ex);        } catch (NoSuchElementException nsee) {            nsee.printStackTrace();            System.err.println("Syntax error in Languages resource bundle");        } catch (MissingResourceException mre) {            mre.printStackTrace();            System.err.println("Initialization error: " + mre.toString());        }    }    public BSFManager() {        pcs = new PropertyChangeSupport(this);    }   /** Returns the version string of BSF.     *     * @return version string in the form &quot;abc.yyyymmdd&quot; where       &quot;abc&quot; represents a dewey decimal number (three levels, each between 0 and 9), and       &quot;yyyy&quot; a four digit year, &quot;mm&quot; a two digit month,       &quot;dd&quot; a two digit day.    *       <br>Example: &quot;<code>240.20061006</code>&quot;       stands for: BSF version <code>2.4.0</code> as of <code>2006-10-06</code>.    *    *     * @since 2006-01-17     */    public static String getVersion() {        return version;    }    /**     * Apply the given anonymous function of the given language to the given     * parameters and return the resulting value.     *     * @param lang language identifier     * @param source (context info) the source of this expression     (e.g., filename)     * @param lineNo (context info) the line number in source for expr     * @param columnNo (context info) the column number in source for expr     * @param funcBody the multi-line, value returning script to evaluate     * @param paramNames the names of the parameters above assumes     * @param arguments values of the above parameters     *     * @exception BSFException if anything goes wrong while running the script     */    public Object apply(String lang,                        String source,                        int lineNo,                        int columnNo,                        Object funcBody,                        Vector paramNames,                        Vector arguments)        throws BSFException {    	logger.debug("BSFManager:apply");    	final BSFEngine e = loadScriptingEngine(lang);        final String sourcef = source;        final int lineNof = lineNo, columnNof = columnNo;        final Object funcBodyf = funcBody;        final Vector paramNamesf = paramNames;        final Vector argumentsf = arguments;        Object result = null;        try {            final Object resultf =                AccessController.doPrivileged(new PrivilegedExceptionAction() {                        public Object run() throws Exception {                            return e.apply(sourcef, lineNof, columnNof,                                           funcBodyf, paramNamesf, argumentsf);                        }                    });            result = resultf;        } catch (PrivilegedActionException prive) {        	logger.error("Exception: ", prive);            throw (BSFException) prive.getException();        }        return result;    }    /**     * Compile the application of the given anonymous function of the given     * language to the given parameters into the given <tt>CodeBuffer</tt>.     *     * @param lang language identifier     * @param source (context info) the source of this expression     (e.g., filename)     * @param lineNo (context info) the line number in source for expr     * @param columnNo (context info) the column number in source for expr     * @param funcBody the multi-line, value returning script to evaluate     * @param paramNames the names of the parameters above assumes     * @param arguments values of the above parameters     * @param cb       code buffer to compile into     *     * @exception BSFException if anything goes wrong while running the script     */    public void compileApply(String lang,                             String source,                             int lineNo,                             int columnNo,                             Object funcBody,                             Vector paramNames,                             Vector arguments,                             CodeBuffer cb)        throws BSFException {    	logger.debug("BSFManager:compileApply");        final BSFEngine e = loadScriptingEngine(lang);        final String sourcef = source;        final int lineNof = lineNo, columnNof = columnNo;        final Object funcBodyf = funcBody;        final Vector paramNamesf = paramNames;        final Vector argumentsf = arguments;        final CodeBuffer cbf = cb;        try {            AccessController.doPrivileged(new PrivilegedExceptionAction() {                    public Object run() throws Exception {                        e.compileApply(sourcef, lineNof, columnNof,                                       funcBodyf, paramNamesf,                                       argumentsf, cbf);                        return null;                    }                });        } catch (PrivilegedActionException prive) {        	logger.error("Exception :", prive);            throw (BSFException) prive.getException();        }    }    /**     * Compile the given expression of the given language into the given     * <tt>CodeBuffer</tt>.     *     * @param lang     language identifier     * @param source   (context info) the source of this expression     (e.g., filename)     * @param lineNo   (context info) the line number in source for expr     * @param columnNo (context info) the column number in source for expr     * @param expr     the expression to compile     * @param cb       code buffer to compile into     *     * @exception BSFException if any error while compiling the expression     */    public void compileExpr(String lang,                            String source,                            int lineNo,                            int columnNo,                            Object expr,                            CodeBuffer cb)        throws BSFException {    	logger.debug("BSFManager:compileExpr");    	final BSFEngine e = loadScriptingEngine(lang);        final String sourcef = source;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?