You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2022/08/30 14:11:26 UTC
[commons-bsf] branch master updated: We don't use author tags
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-bsf.git
The following commit(s) were added to refs/heads/master by this push:
new 8a9c95b We don't use author tags
8a9c95b is described below
commit 8a9c95bdc1b69f97a666fb4c59005afc561888bf
Author: Gary Gregory <gg...@rocketsoftware.com>
AuthorDate: Tue Aug 30 10:11:20 2022 -0400
We don't use author tags
---
src/main/java/org/apache/bsf/BSFDeclaredBean.java | 73 +-
src/main/java/org/apache/bsf/BSFEngine.java | 501 +++--
src/main/java/org/apache/bsf/BSFException.java | 138 +-
src/main/java/org/apache/bsf/BSFManager.java | 2033 ++++++++++----------
src/main/java/org/apache/bsf/BSF_Log.java | 1021 +++++-----
src/main/java/org/apache/bsf/BSF_LogFactory.java | 88 +-
src/main/java/org/apache/bsf/Main.java | 374 ++--
.../org/apache/bsf/engines/jacl/JaclEngine.java | 280 ++-
.../org/apache/bsf/engines/java/JavaEngine.java | 714 ++++---
.../bsf/engines/javaclass/JavaClassEngine.java | 146 +-
.../bsf/engines/javascript/JavaScriptEngine.java | 473 +++--
.../apache/bsf/engines/jython/JythonEngine.java | 563 +++---
.../apache/bsf/engines/netrexx/NetRexxEngine.java | 1000 +++++-----
.../org/apache/bsf/engines/xslt/XSLTEngine.java | 401 ++--
.../java/org/apache/bsf/util/BSFClassLoader.java | 150 +-
.../java/org/apache/bsf/util/BSFEngineImpl.java | 404 ++--
.../org/apache/bsf/util/BSFEventProcessor.java | 234 ++-
.../util/BSFEventProcessorReturningEventInfos.java | 377 ++--
.../java/org/apache/bsf/util/BSFFunctions.java | 108 +-
src/main/java/org/apache/bsf/util/Bean.java | 76 +-
src/main/java/org/apache/bsf/util/CodeBuffer.java | 960 +++++----
src/main/java/org/apache/bsf/util/EngineUtils.java | 876 +++++----
src/main/java/org/apache/bsf/util/IOUtils.java | 101 +-
.../java/org/apache/bsf/util/IndentWriter.java | 170 +-
src/main/java/org/apache/bsf/util/JavaUtils.java | 114 +-
src/main/java/org/apache/bsf/util/MethodUtils.java | 1081 ++++++-----
src/main/java/org/apache/bsf/util/ObjInfo.java | 176 +-
.../java/org/apache/bsf/util/ObjectRegistry.java | 125 +-
.../java/org/apache/bsf/util/ReflectionUtils.java | 1085 ++++++-----
.../org/apache/bsf/util/ScriptSymbolTable.java | 90 +-
src/main/java/org/apache/bsf/util/StringUtils.java | 852 ++++----
src/main/java/org/apache/bsf/util/cf/CFDriver.java | 399 ++--
.../java/org/apache/bsf/util/cf/CodeFormatter.java | 753 ++++----
.../org/apache/bsf/util/event/EventAdapter.java | 70 +-
.../apache/bsf/util/event/EventAdapterImpl.java | 70 +-
.../bsf/util/event/EventAdapterRegistry.java | 276 ++-
.../org/apache/bsf/util/event/EventProcessor.java | 70 +-
.../util/event/generator/AdapterClassLoader.java | 406 ++--
.../bsf/util/event/generator/ByteUtility.java | 661 ++++---
.../apache/bsf/util/event/generator/Bytecode.java | 209 +-
.../org/apache/bsf/util/type/TypeConvertor.java | 63 +-
.../bsf/util/type/TypeConvertorRegistry.java | 408 ++--
.../java/org/apache/bsf/BSFEngineTestTmpl.java | 137 +-
src/test/java/org/apache/bsf/BSFTest.java | 357 ++--
src/test/java/org/apache/bsf/engines/JaclTest.java | 369 ++--
.../org/apache/bsf/engines/JavascriptTest.java | 403 ++--
.../java/org/apache/bsf/engines/JythonTest.java | 403 ++--
.../java/org/apache/bsf/engines/NetrexxTest.java | 325 ++--
.../java/org/apache/bsf/util/EngineUtilsTest.java | 240 ++-
src/test/java/org/apache/bsf/util/IOUtilsTest.java | 146 +-
.../java/org/apache/bsf/util/StringUtilsTest.java | 526 +++--
src/test/java/org/apache/bsf/util/TestBean.java | 112 +-
52 files changed, 10527 insertions(+), 10660 deletions(-)
diff --git a/src/main/java/org/apache/bsf/BSFDeclaredBean.java b/src/main/java/org/apache/bsf/BSFDeclaredBean.java
index 67b1b00..ea56dc3 100644
--- a/src/main/java/org/apache/bsf/BSFDeclaredBean.java
+++ b/src/main/java/org/apache/bsf/BSFDeclaredBean.java
@@ -1,38 +1,35 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-/**
- * BSFDeclaredBeans are used internally by BSF to encapsulate information being
- * passed between a BSFManager and its various BSFEngines. Note that the
- * constructor is not public because this is not a public class.
- *
- * @author Matthew J. Duftler
- * @author Sanjiva Weerawarana
- */
-public class BSFDeclaredBean {
- public String name;
- public Object bean;
- public Class type;
-
- BSFDeclaredBean(final String name, final Object bean, final Class type) {
- this.name = name;
- this.bean = bean;
- this.type = type;
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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;
+
+/**
+ * BSFDeclaredBeans are used internally by BSF to encapsulate information being
+ * passed between a BSFManager and its various BSFEngines. Note that the
+ * constructor is not public because this is not a public class.
+ */
+public class BSFDeclaredBean {
+ public String name;
+ public Object bean;
+ public Class type;
+
+ BSFDeclaredBean(final String name, final Object bean, final Class type) {
+ this.name = name;
+ this.bean = bean;
+ this.type = type;
+ }
+}
diff --git a/src/main/java/org/apache/bsf/BSFEngine.java b/src/main/java/org/apache/bsf/BSFEngine.java
index a145468..30e4c70 100644
--- a/src/main/java/org/apache/bsf/BSFEngine.java
+++ b/src/main/java/org/apache/bsf/BSFEngine.java
@@ -1,252 +1,249 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.PropertyChangeListener;
-import java.util.Vector;
-
-import org.apache.bsf.util.CodeBuffer;
-
-/**
- * This is the view of a scripting engine assumed by the Bean Scripting
- * Framework. This interface is used when an application decides to
- * run some script under application control. (This is the reverse of
- * the more common situation, which is that of the scripting language
- * calling into the application.)
- * <p>
- * When a scripting engine is first fired up, the initialize()
- * method is called right after construction.
- * <p>
- * A scripting engine must provide two access points for applications
- * to call into them: via function calls and via expression evaluation.
- * It must also support loading scripts.
- * <p>
- * A scripting engine is a property change listener and will be notified
- * when any of the relevant properties of the manager change. (See
- * BSFManager to see which of its properties are bound.)
- *
- * @author Sanjiva Weerawarana
- * @author Matthew J. Duftler
- */
-public interface BSFEngine extends PropertyChangeListener {
-
- /**
- * This is used by an application to invoke an anonymous function. An
- * anonymous function is a multi-line script which when evaluated will
- * produce a value. These are separated from expressions and scripts
- * because the prior are spsed to be good 'ol expressions and scripts
- * are not value returning. We allow anonymous functions to have parameters
- * as well for completeness.
- *
- * @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 doin' it.
- */
- Object apply(
- String source,
- int lineNo,
- int columnNo,
- Object funcBody,
- Vector paramNames,
- Vector arguments)
- throws BSFException;
- /**
- * This is used by an application to call into the scripting engine
- * to make a function/method call. The "object" argument is the object
- * whose method is to be called, if that applies. For non-OO languages,
- * this is typically ignored and should be given as null. For pretend-OO
- * languages such as VB, this would be the (String) name of the object.
- * The arguments are given in the args array.
- *
- * @param object object on which to make the call
- * @param name name of the method / procedure to call
- * @param args the arguments to be given to the procedure
- *
- * @exception BSFException if anything goes wrong while eval'ing a
- * BSFException is thrown. The reason indicates the problem.
- */
- Object call(Object object, String name, Object[] args)
- throws BSFException;
- /**
- * This is used by an application to compile an anonymous function. See
- * comments in apply for more hdetails.
- *
- * @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 the CodeBuffer to compile into
- *
- * @exception BSFException if anything goes wrong while doin' it.
- */
- void compileApply(
- String source,
- int lineNo,
- int columnNo,
- Object funcBody,
- Vector paramNames,
- Vector arguments,
- CodeBuffer cb)
- throws BSFException;
- /**
- * This is used by an application to compile a value-returning expression.
- * The expr may be string or some other type, depending on the language.
- * The generated code is dumped into the {@code CodeBuffer}.
- *
- * @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 the CodeBuffer to compile into
- *
- * @exception BSFException if anything goes wrong while compiling a
- * BSFException is thrown. The reason indicates the problem.
- */
- void compileExpr(
- String source,
- int lineNo,
- int columnNo,
- Object expr,
- CodeBuffer cb)
- throws BSFException;
- /**
- * This is used by an application to compile some script. The
- * script may be string or some other type, depending on the
- * language. The generated code is dumped into the {@code CodeBuffer}.
- *
- * @param source (context info) the source of this script
- * (e.g., filename)
- * @param lineNo (context info) the line number in source for script
- * @param columnNo (context info) the column number in source for script
- * @param script the script to compile
- * @param cb the CodeBuffer to compile into
- *
- * @exception BSFException if anything goes wrong while compiling a
- * BSFException is thrown. The reason indicates the problem.
- */
- void compileScript(
- String source,
- int lineNo,
- int columnNo,
- Object script,
- CodeBuffer cb)
- throws BSFException;
- /**
- * Declare a bean after the engine has been started. Declared beans
- * are beans that are named and which the engine must make available
- * to the scripts it runs in the most first class way possible.
- *
- * @param bean the bean to declare
- *
- * @exception BSFException if the engine cannot do this operation
- */
- void declareBean(BSFDeclaredBean bean) throws BSFException;
- /**
- * This is used by an application to evaluate an expression. The
- * expression may be string or some other type, depending on the
- * language. (For example, for BML it'll be an org.w3c.dom.Element
- * object.)
- *
- * @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 evaluate
- *
- * @exception BSFException if anything goes wrong while eval'ing a
- * BSFException is thrown. The reason indicates the problem.
- */
- Object eval(String source, int lineNo, int columnNo, Object expr)
- throws BSFException;
- /**
- * This is used by an application to execute some script. The
- * expression may be string or some other type, depending on the
- * language. Returns nothing but if something goes wrong it excepts
- * (of course).
- *
- * @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 script the script to execute
- *
- * @exception BSFException if anything goes wrong while exec'ing a
- * BSFException is thrown. The reason indicates the problem.
- */
- void exec(String source, int lineNo, int columnNo, Object script)
- throws BSFException;
- /**
- * This is used by an application to execute some script, as though
- * one were interacting with the language in an interactive session.
- * The expression may be string or some other type, depending on the
- * language. Returns nothing but if something goes wrong it excepts (of
- * course).
- *
- * @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 script the script to execute
- *
- * @exception BSFException if anything goes wrong while exec'ing a
- * BSFException is thrown. The reason indicates the problem.
- */
- void iexec(String source, int lineNo, int columnNo, Object script)
- throws BSFException;
-
- /**
- * This method is used to initialize the engine right after construction.
- * This method will be called before any calls to eval or call. At this
- * time the engine should capture the current values of interesting
- * properties from the manager. In the future, any changes to those
- * will be mirrored to me by the manager via a property change event.
- *
- * @param mgr The BSFManager that's hosting this engine.
- * @param lang Language string which this engine is handling.
- * @param declaredBeans Vector of BSFDeclaredObject containing beans
- * that should be declared into the language runtime at init
- * time as best as possible.
- *
- * @exception BSFException if anything goes wrong while init'ing a
- * BSFException is thrown. The reason indicates the problem.
- */
- void initialize(BSFManager mgr, String lang, Vector declaredBeans)
- throws BSFException;
- /**
- * Graceful termination
- */
- void terminate();
- /**
- * Undeclare a previously declared bean.
- *
- * @param bean the bean to undeclare
- *
- * @exception BSFException if the engine cannot do this operation
- */
- void undeclareBean(BSFDeclaredBean bean) throws BSFException;
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.PropertyChangeListener;
+import java.util.Vector;
+
+import org.apache.bsf.util.CodeBuffer;
+
+/**
+ * This is the view of a scripting engine assumed by the Bean Scripting
+ * Framework. This interface is used when an application decides to
+ * run some script under application control. (This is the reverse of
+ * the more common situation, which is that of the scripting language
+ * calling into the application.)
+ * <p>
+ * When a scripting engine is first fired up, the initialize()
+ * method is called right after construction.
+ * <p>
+ * A scripting engine must provide two access points for applications
+ * to call into them: via function calls and via expression evaluation.
+ * It must also support loading scripts.
+ * <p>
+ * A scripting engine is a property change listener and will be notified
+ * when any of the relevant properties of the manager change. (See
+ * BSFManager to see which of its properties are bound.)
+ */
+public interface BSFEngine extends PropertyChangeListener {
+
+ /**
+ * This is used by an application to invoke an anonymous function. An
+ * anonymous function is a multi-line script which when evaluated will
+ * produce a value. These are separated from expressions and scripts
+ * because the prior are spsed to be good 'ol expressions and scripts
+ * are not value returning. We allow anonymous functions to have parameters
+ * as well for completeness.
+ *
+ * @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 doin' it.
+ */
+ Object apply(
+ String source,
+ int lineNo,
+ int columnNo,
+ Object funcBody,
+ Vector paramNames,
+ Vector arguments)
+ throws BSFException;
+ /**
+ * This is used by an application to call into the scripting engine
+ * to make a function/method call. The "object" argument is the object
+ * whose method is to be called, if that applies. For non-OO languages,
+ * this is typically ignored and should be given as null. For pretend-OO
+ * languages such as VB, this would be the (String) name of the object.
+ * The arguments are given in the args array.
+ *
+ * @param object object on which to make the call
+ * @param name name of the method / procedure to call
+ * @param args the arguments to be given to the procedure
+ *
+ * @exception BSFException if anything goes wrong while eval'ing a
+ * BSFException is thrown. The reason indicates the problem.
+ */
+ Object call(Object object, String name, Object[] args)
+ throws BSFException;
+ /**
+ * This is used by an application to compile an anonymous function. See
+ * comments in apply for more hdetails.
+ *
+ * @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 the CodeBuffer to compile into
+ *
+ * @exception BSFException if anything goes wrong while doin' it.
+ */
+ void compileApply(
+ String source,
+ int lineNo,
+ int columnNo,
+ Object funcBody,
+ Vector paramNames,
+ Vector arguments,
+ CodeBuffer cb)
+ throws BSFException;
+ /**
+ * This is used by an application to compile a value-returning expression.
+ * The expr may be string or some other type, depending on the language.
+ * The generated code is dumped into the {@code CodeBuffer}.
+ *
+ * @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 the CodeBuffer to compile into
+ *
+ * @exception BSFException if anything goes wrong while compiling a
+ * BSFException is thrown. The reason indicates the problem.
+ */
+ void compileExpr(
+ String source,
+ int lineNo,
+ int columnNo,
+ Object expr,
+ CodeBuffer cb)
+ throws BSFException;
+ /**
+ * This is used by an application to compile some script. The
+ * script may be string or some other type, depending on the
+ * language. The generated code is dumped into the {@code CodeBuffer}.
+ *
+ * @param source (context info) the source of this script
+ * (e.g., filename)
+ * @param lineNo (context info) the line number in source for script
+ * @param columnNo (context info) the column number in source for script
+ * @param script the script to compile
+ * @param cb the CodeBuffer to compile into
+ *
+ * @exception BSFException if anything goes wrong while compiling a
+ * BSFException is thrown. The reason indicates the problem.
+ */
+ void compileScript(
+ String source,
+ int lineNo,
+ int columnNo,
+ Object script,
+ CodeBuffer cb)
+ throws BSFException;
+ /**
+ * Declare a bean after the engine has been started. Declared beans
+ * are beans that are named and which the engine must make available
+ * to the scripts it runs in the most first class way possible.
+ *
+ * @param bean the bean to declare
+ *
+ * @exception BSFException if the engine cannot do this operation
+ */
+ void declareBean(BSFDeclaredBean bean) throws BSFException;
+ /**
+ * This is used by an application to evaluate an expression. The
+ * expression may be string or some other type, depending on the
+ * language. (For example, for BML it'll be an org.w3c.dom.Element
+ * object.)
+ *
+ * @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 evaluate
+ *
+ * @exception BSFException if anything goes wrong while eval'ing a
+ * BSFException is thrown. The reason indicates the problem.
+ */
+ Object eval(String source, int lineNo, int columnNo, Object expr)
+ throws BSFException;
+ /**
+ * This is used by an application to execute some script. The
+ * expression may be string or some other type, depending on the
+ * language. Returns nothing but if something goes wrong it excepts
+ * (of course).
+ *
+ * @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 script the script to execute
+ *
+ * @exception BSFException if anything goes wrong while exec'ing a
+ * BSFException is thrown. The reason indicates the problem.
+ */
+ void exec(String source, int lineNo, int columnNo, Object script)
+ throws BSFException;
+ /**
+ * This is used by an application to execute some script, as though
+ * one were interacting with the language in an interactive session.
+ * The expression may be string or some other type, depending on the
+ * language. Returns nothing but if something goes wrong it excepts (of
+ * course).
+ *
+ * @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 script the script to execute
+ *
+ * @exception BSFException if anything goes wrong while exec'ing a
+ * BSFException is thrown. The reason indicates the problem.
+ */
+ void iexec(String source, int lineNo, int columnNo, Object script)
+ throws BSFException;
+
+ /**
+ * This method is used to initialize the engine right after construction.
+ * This method will be called before any calls to eval or call. At this
+ * time the engine should capture the current values of interesting
+ * properties from the manager. In the future, any changes to those
+ * will be mirrored to me by the manager via a property change event.
+ *
+ * @param mgr The BSFManager that's hosting this engine.
+ * @param lang Language string which this engine is handling.
+ * @param declaredBeans Vector of BSFDeclaredObject containing beans
+ * that should be declared into the language runtime at init
+ * time as best as possible.
+ *
+ * @exception BSFException if anything goes wrong while init'ing a
+ * BSFException is thrown. The reason indicates the problem.
+ */
+ void initialize(BSFManager mgr, String lang, Vector declaredBeans)
+ throws BSFException;
+ /**
+ * Graceful termination
+ */
+ void terminate();
+ /**
+ * Undeclare a previously declared bean.
+ *
+ * @param bean the bean to undeclare
+ *
+ * @exception BSFException if the engine cannot do this operation
+ */
+ void undeclareBean(BSFDeclaredBean bean) throws BSFException;
+}
diff --git a/src/main/java/org/apache/bsf/BSFException.java b/src/main/java/org/apache/bsf/BSFException.java
index f8361a4..5354deb 100644
--- a/src/main/java/org/apache/bsf/BSFException.java
+++ b/src/main/java/org/apache/bsf/BSFException.java
@@ -1,70 +1,68 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-/**
- * If something goes wrong while doing some scripting stuff, one of these
- * is thrown. The integer code indicates what's wrong and the message
- * may give more details. The reason one exception with multiple meanings
- * (via the code) [instead of multiple exception types] is used is due to
- * the interest to keep the run-time size small.
- *
- * @author Sanjiva Weerawarana
- */
-public class BSFException extends Exception {
- public static final int REASON_INVALID_ARGUMENT = 0;
- public static final int REASON_IO_ERROR = 10;
- public static final int REASON_UNKNOWN_LANGUAGE = 20;
- public static final int REASON_EXECUTION_ERROR = 100;
- public static final int REASON_UNSUPPORTED_FEATURE = 499;
- public static final int REASON_OTHER_ERROR = 500;
-
- int reason;
- Throwable targetThrowable;
-
- public BSFException (final int reason, final String msg) {
- super (msg);
- this.reason = reason;
- }
- public BSFException (final int reason, final String msg, final Throwable t) {
- this (reason, msg);
- targetThrowable = t;
- }
- public BSFException (final String msg) {
- this (REASON_OTHER_ERROR, msg);
- }
- public int getReason () {
- return reason;
- }
- public Throwable getTargetException () {
- return targetThrowable;
- }
- public void printStackTrace () {
- if (targetThrowable != null) {
- final String msg = getMessage ();
-
- if (msg != null && !msg.equals (targetThrowable.getMessage ())) {
- System.err.print (msg + ": ");
- }
-
- targetThrowable.printStackTrace ();
- } else {
- super.printStackTrace ();
- }
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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;
+
+/**
+ * If something goes wrong while doing some scripting stuff, one of these
+ * is thrown. The integer code indicates what's wrong and the message
+ * may give more details. The reason one exception with multiple meanings
+ * (via the code) [instead of multiple exception types] is used is due to
+ * the interest to keep the run-time size small.
+ */
+public class BSFException extends Exception {
+ public static final int REASON_INVALID_ARGUMENT = 0;
+ public static final int REASON_IO_ERROR = 10;
+ public static final int REASON_UNKNOWN_LANGUAGE = 20;
+ public static final int REASON_EXECUTION_ERROR = 100;
+ public static final int REASON_UNSUPPORTED_FEATURE = 499;
+ public static final int REASON_OTHER_ERROR = 500;
+
+ int reason;
+ Throwable targetThrowable;
+
+ public BSFException (final int reason, final String msg) {
+ super (msg);
+ this.reason = reason;
+ }
+ public BSFException (final int reason, final String msg, final Throwable t) {
+ this (reason, msg);
+ targetThrowable = t;
+ }
+ public BSFException (final String msg) {
+ this (REASON_OTHER_ERROR, msg);
+ }
+ public int getReason () {
+ return reason;
+ }
+ public Throwable getTargetException () {
+ return targetThrowable;
+ }
+ public void printStackTrace () {
+ if (targetThrowable != null) {
+ final String msg = getMessage ();
+
+ if (msg != null && !msg.equals (targetThrowable.getMessage ())) {
+ System.err.print (msg + ": ");
+ }
+
+ targetThrowable.printStackTrace ();
+ } else {
+ super.printStackTrace ();
+ }
+ }
+}
diff --git a/src/main/java/org/apache/bsf/BSFManager.java b/src/main/java/org/apache/bsf/BSFManager.java
index 7584cc9..cdb6e94 100644
--- a/src/main/java/org/apache/bsf/BSFManager.java
+++ b/src/main/java/org/apache/bsf/BSFManager.java
@@ -1,1020 +1,1013 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
- // org.apache.commons.logging is delegated to "org.apache.bsf.BSF_Log[Factory]"
-// 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)
- * @author Rony G. Flatscher (added BSF_Log[Factory] to allow BSF to run without org.apache.commons.logging present)
- */
-
-// changed 2007-01-28: ---rgf, fixed Class.forName() to use the context class loader instead; oversaw this the last time
-/* changed 2007-09-17: ---rgf, some Java hosts do not set the Thread's context class loader and
- load BSF with a customized ClassLoader!
- Resolution:
- - use Thread context ClassLoader, if resource or class to
- load not found, then
- - use the BSFManager's defining ClassLoader instead, if it is
- different to the context ClassLoader
-
- 2012-01-29, ---rgf, - context class loader may not be set, account for it (2009-09-10)
- - static constructor: fixed logic error in fallback code for getResources() (2011-01-08)
- 2014-12-30, ---rgf, - remove memory leak when terminating engines, cf. issue [BSF-41]
-*/
-
-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: "250.20120129" stands for: BSF version "2.5.0" as of "2012-01-29"
- protected static String version="250.20141230";
-
- // table of registered scripting engines
- protected static Hashtable registeredEngines = new Hashtable();
-
- // mapping of file extensions to languages
- protected static Hashtable extn2Lang = new Hashtable();
-
- // get the defined CL (ClassLoader which got used to define this class object) // rgf, 20070917
- protected static ClassLoader definedClassLoader;
-/*
- protected static ClassLoader appClassLoader; // application/system class loader
- protected static ClassLoader extClassLoader; // extension (option) class loader
-*/
-
- /** Returns the defined ClassLoader (the ClassLoader that got used to define the
- * org.apache.bsf.BSFManager class object).
- * @return the defined ClassLoader instance
- */
- public static ClassLoader getDefinedClassLoader() // rgf, 20070917
- {
- return definedClassLoader;
- }
-
-
- // 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;
-
-/* rgf (20070917): wrong assumption; context ClassLoader needs to be explicitly
- requested before usage as BSF could be deployed with different
- context ClassLoaders on different threads!
-*/
-
- // 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();
- // rgf, 20070917, reset to original// 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());
- private BSF_Log logger = null;
-
- //////////////////////////////////////////////////////////////////////
- //
- // pre-register engines that BSF supports off the shelf
- //
- //////////////////////////////////////////////////////////////////////
-
- static {
- final String strInfo="org.apache.bsf.BSFManager.dumpEnvironment() [from static{}]";
- try {
- definedClassLoader=BSFManager.class.getClassLoader(); // get defining ClassLoader
-
- final String resourceName="org/apache/bsf/Languages.properties";
-
- Enumeration e = null;
- // use the Thread's context class loader to locate the resources
- final ClassLoader tccl=Thread.currentThread().getContextClassLoader(); // try to get the context class loader
- if (tccl!=null) // no context class loader available!
- {
- e=tccl.getResources(resourceName);
- }
- else // fallback
- {
- e=definedClassLoader.getResources(resourceName);
- Thread.currentThread().setContextClassLoader(definedClassLoader); // set Thread context class loader
- }
-
- while (e.hasMoreElements()) {
- final URL url = (URL)e.nextElement();
- final InputStream is = url.openStream();
-
- final Properties p = new Properties();
- p.load(is);
-
- for (final Enumeration keys = p.propertyNames(); keys.hasMoreElements();) {
-
- final String key = (String) keys.nextElement();
- final String value = p.getProperty(key);
- final String className = value.substring(0, value.indexOf(","));
-
-
- // get the extensions for this language
- final String exts = value.substring(value.indexOf(",")+1);
- final StringTokenizer st = new StringTokenizer(exts, "|");
- final String[] extensions = new String[st.countTokens()];
-
- for (int i = 0; st.hasMoreTokens(); i++) {
- extensions[i] = st.nextToken().trim();
- }
-
- registerScriptingEngine(key, className, extensions);
- }
- }
- } catch (final IOException ex) {
- final BSF_Log logger = BSF_LogFactory.getLog(BSFManager.class.getName());
- logger.debug("[BSFManager] static {...}");
- logger.error("[BSFManager] Error reading Languages file, exception :",ex);
-
- // TODO: leave in case only a no-op-logger is available or remove next two statements?
- ex.printStackTrace();
- System.err.println("Error reading Languages file " + ex);
- } catch (final NoSuchElementException nsee) {
- final BSF_Log logger = BSF_LogFactory.getLog(BSFManager.class.getName());
- logger.debug("[BSFManager] static {...}");
- logger.error("[BSFManager] Syntax error in Languages resource bundle, exception :",nsee);
-
- // TODO: leave in case only a no-op-logger is available or remove next two statements?
- nsee.printStackTrace();
- System.err.println("Syntax error in Languages resource bundle");
- } catch (final MissingResourceException mre) {
- final BSF_Log logger = BSF_LogFactory.getLog(BSFManager.class.getName());
- logger.debug("[BSFManager] static {...}");
- logger.error("[BSFManager] Initialization error, exception :",mre);
-
- // TODO: leave in case only a no-op-logger is available or remove next two statements?
- mre.printStackTrace();
- System.err.println("Initialization error: " + mre.toString());
- }
- }
-
- public BSFManager() {
- pcs = new PropertyChangeSupport(this);
- // handle logger
- logger = BSF_LogFactory.getLog(this.getClass().getName());
- }
-
-
- /** Returns the version string of BSF.
- *
- * @return version string 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.
- *
- <br>Example: "<code>250.20120129</code>"
- stands for: BSF version <code>2.5.0</code> as of <code>2012-01-29</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(final String lang,
- final String source,
- final int lineNo,
- final int columnNo,
- final Object funcBody,
- final Vector paramNames,
- final 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 (final PrivilegedActionException prive) {
-
- logger.error("[BSFManager] 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 {@code CodeBuffer}.
- *
- * @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(final String lang,
- final String source,
- final int lineNo,
- final int columnNo,
- final Object funcBody,
- final Vector paramNames,
- final Vector arguments,
- final 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 (final PrivilegedActionException prive) {
-
- logger.error("[BSFManager] Exception :", prive);
- throw (BSFException) prive.getException();
- }
- }
-
- /**
- * Compile the given expression of the given language into the given
- * {@code CodeBuffer}.
- *
- * @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(final String lang,
- final String source,
- final int lineNo,
- final int columnNo,
- final Object expr,
- final CodeBuffer cb)
- throws BSFException {
- logger.debug("BSFManager:compileExpr");
-
- final BSFEngine e = loadScriptingEngine(lang);
- final String sourcef = source;
- final int lineNof = lineNo, columnNof = columnNo;
- final Object exprf = expr;
- final CodeBuffer cbf = cb;
-
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction() {
- public Object run() throws Exception {
- e.compileExpr(sourcef, lineNof, columnNof, exprf, cbf);
- return null;
- }
- });
- } catch (final PrivilegedActionException prive) {
-
- logger.error("[BSFManager] Exception :", prive);
- throw (BSFException) prive.getException();
- }
- }
-
- /**
- * Compile the given script of the given language into the given
- * {@code CodeBuffer}.
- *
- * @param lang language identifier
- * @param source (context info) the source of this script
- (e.g., filename)
- * @param lineNo (context info) the line number in source for script
- * @param columnNo (context info) the column number in source for script
- * @param script the script to compile
- * @param cb code buffer to compile into
- *
- * @exception BSFException if any error while compiling the script
- */
- public void compileScript(final String lang,
- final String source,
- final int lineNo,
- final int columnNo,
- final Object script,
- final CodeBuffer cb)
- throws BSFException {
- logger.debug("BSFManager:compileScript");
-
- final BSFEngine e = loadScriptingEngine(lang);
- final String sourcef = source;
- final int lineNof = lineNo, columnNof = columnNo;
- final Object scriptf = script;
- final CodeBuffer cbf = cb;
-
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction() {
- public Object run() throws Exception {
- e.compileScript(sourcef, lineNof, columnNof,
- scriptf, cbf);
- return null;
- }
- });
- } catch (final PrivilegedActionException prive) {
-
- logger.error("[BSFManager] Exception :", prive);
- throw (BSFException) prive.getException();
- }
- }
-
- /**
- * Declare a bean. The difference between declaring and registering
- * is that engines are spsed to make declared beans "pre-available"
- * in the scripts as far as possible. That is, if a script author
- * needs a registered bean, he needs to look it up in some way. However
- * if he needs a declared bean, the language has the responsibility to
- * make those beans avaialable "automatically."
- * <p>
- * When a bean is declared it is automatically registered as well
- * so that any declared bean can be gotton to by looking it up as well.
- * <p>
- * If any of the languages that are already running in this manager
- * says they don't like this (by throwing an exception) then this
- * method will simply quit with that exception. That is, any engines
- * that come after than in the engine enumeration will not even be
- * told about this new bean.
- * <p>
- * So, in general its best to declare beans before the manager has
- * been asked to load any engines because then the user can be informed
- * when an engine rejects it. Also, its much more likely that an engine
- * can declare a bean at start time than it can at any time.
- *
- * @param beanName name to declare bean as
- * @param bean the bean that's being declared
- * @param type the type to represent the bean as
- *
- * @exception BSFException if any of the languages that are already
- * running decides to throw an exception when asked to
- * declare this bean.
- */
- public void declareBean(final String beanName, final Object bean, final Class type)
- throws BSFException {
- logger.debug("BSFManager:declareBean");
-
- registerBean(beanName, bean);
-
- final BSFDeclaredBean tempBean = new BSFDeclaredBean(beanName, bean, type);
- declaredBeans.addElement(tempBean);
-
- final Enumeration enginesEnum = loadedEngines.elements();
- BSFEngine engine;
- while (enginesEnum.hasMoreElements()) {
- engine = (BSFEngine) enginesEnum.nextElement();
- engine.declareBean(tempBean);
- }
- }
-
- /**
- * Evaluate the given expression of the given language 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 expr the expression to evaluate
- *
- * @exception BSFException if anything goes wrong while running the script
- */
- public Object eval(final String lang,
- final String source,
- final int lineNo,
- final int columnNo,
- final Object expr)
- throws BSFException {
- logger.debug("BSFManager:eval");
-
- final BSFEngine e = loadScriptingEngine(lang);
- final String sourcef = source;
- final int lineNof = lineNo, columnNof = columnNo;
- final Object exprf = expr;
- Object result = null;
-
- try {
- final Object resultf =
- AccessController.doPrivileged(new PrivilegedExceptionAction() {
- public Object run() throws Exception {
- return e.eval(sourcef, lineNof, columnNof, exprf);
- }
- });
- result = resultf;
- } catch (final PrivilegedActionException prive) {
-
- logger.error("[BSFManager] Exception: ", prive);
- throw (BSFException) prive.getException();
- }
-
- return result;
- }
-
- //////////////////////////////////////////////////////////////////////
- //
- // Convenience functions for exec'ing and eval'ing scripts directly
- // without loading and dealing with engines etc..
- //
- //////////////////////////////////////////////////////////////////////
-
- /**
- * Execute the given script of the given language.
- *
- * @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 script the script to execute
- *
- * @exception BSFException if anything goes wrong while running the script
- */
- public void exec(final String lang,
- final String source,
- final int lineNo,
- final int columnNo,
- final Object script)
- throws BSFException {
- logger.debug("BSFManager:exec");
-
- final BSFEngine e = loadScriptingEngine(lang);
- final String sourcef = source;
- final int lineNof = lineNo, columnNof = columnNo;
- final Object scriptf = script;
-
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction() {
- public Object run() throws Exception {
- e.exec(sourcef, lineNof, columnNof, scriptf);
- return null;
- }
- });
- } catch (final PrivilegedActionException prive) {
-
- logger.error("[BSFManager] Exception :", prive);
- throw (BSFException) prive.getException();
- }
- }
-
- /**
- * Execute the given script of the given language, attempting to
- * emulate an interactive session w/ the language.
- *
- * @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 script the script to execute
- *
- * @exception BSFException if anything goes wrong while running the script
- */
- public void iexec(final String lang,
- final String source,
- final int lineNo,
- final int columnNo,
- final Object script)
- throws BSFException {
- logger.debug("BSFManager:iexec");
-
- final BSFEngine e = loadScriptingEngine(lang);
- final String sourcef = source;
- final int lineNof = lineNo, columnNof = columnNo;
- final Object scriptf = script;
-
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction() {
- public Object run() throws Exception {
- e.iexec(sourcef, lineNof, columnNof, scriptf);
- return null;
- }
- });
- } catch (final PrivilegedActionException prive) {
-
- logger.error("[BSFManager] Exception :", prive);
- throw (BSFException) prive.getException();
- }
- }
-
- /**
- * Get classLoader
- */
- public ClassLoader getClassLoader() {
- logger.debug("BSFManager:getClassLoader");
- return classLoader;
- }
-
- /**
- * Get classPath
- */
- public String getClassPath() {
- logger.debug("BSFManager:getClassPath");
- if (classPath == null) {
- try {
- classPath = System.getProperty("java.class.path");
- } catch (final Throwable t) {
-
- logger.debug("[BSFManager] Exception :", t);
- // prolly a security exception .. so no can do
- }
- }
- return classPath;
- }
-
- /**
- * Determine the language of a script file by looking at the file
- * extension.
- *
- * @param fileName the name of the file
- *
- * @return the scripting language the file is in if the file extension
- * is known to me (must have been registered via
- * registerScriptingEngine).
- *
- * @exception BSFException if file's extension is unknown.
- */
- public static String getLangFromFilename(final String fileName)
- throws BSFException {
- final int dotIndex = fileName.lastIndexOf(".");
-
- if (dotIndex != -1) {
- final String extn = fileName.substring(dotIndex + 1);
- String langval = (String) extn2Lang.get(extn);
- String lang = null;
- int index, loops = 0;
-
- if (langval != null) {
- final ClassLoader tccl=Thread.currentThread().getContextClassLoader(); // rgf, 2009-09-10
-
- while ((index = langval.indexOf(":", 0)) != -1) {
- // Great. Multiple language engines registered
- // for this extension.
- // Try to find first one that is in our classpath.
- lang = langval.substring(0, index);
- langval = langval.substring(index + 1);
- loops++;
-
- // Test to see if in classpath
- String engineName=null;
- try {
- engineName =
- (String) registeredEngines.get(lang);
-
- boolean bTryDefinedClassLoader=false;
- if (tccl!=null) // context CL available, try it first
- {
- try
- {
- tccl.loadClass (engineName);
- }
- catch (final ClassNotFoundException cnfe)
- {
- bTryDefinedClassLoader=true;
- }
- }
-
- if (bTryDefinedClassLoader || tccl==null) // not found, try defined CL next
- {
- definedClassLoader.loadClass(engineName);
- }
- }
- catch (final ClassNotFoundException cnfe2) {
- // Bummer.
- lang = langval;
- continue;
- }
-
- // Got past that? Good.
- break;
- }
- if (loops == 0) { lang = langval; }
- }
-
- if (lang != null && lang != "") {
- return lang;
- }
- }
- throw new BSFException(BSFException.REASON_OTHER_ERROR,
- "[BSFManager.getLangFromFilename] file extension missing or unknown: "
- + "unable to determine language for '"
- + fileName
- + "'");
- }
-
- /**
- * Return the current object registry of the manager.
- *
- * @return the current registry.
- */
- public ObjectRegistry getObjectRegistry() {
- return objectRegistry;
- }
-
- /**
- * Get tempDir
- */
- public String getTempDir() {
- return tempDir;
- }
-
- /**
- * Determine whether a language is registered.
- *
- * @param lang string identifying a language
- *
- * @return true iff it is
- */
- public static boolean isLanguageRegistered(final String lang) {
- return (registeredEngines.get(lang) != null);
- }
-
- //////////////////////////////////////////////////////////////////////
- //
- // Bean scripting framework services
- //
- //////////////////////////////////////////////////////////////////////
-
- /**
- * Load a scripting engine based on the lang string identifying it.
- *
- * @param lang string identifying language
- * @exception BSFException if the language is unknown (i.e., if it
- * has not been registered) with a reason of
- * REASON_UNKNOWN_LANGUAGE. If the language is known but
- * if the interface can't be created for some reason, then
- * the reason is set to REASON_OTHER_ERROR and the actual
- * exception is passed on as well.
- */
- public BSFEngine loadScriptingEngine(final String lang) throws BSFException {
- logger.debug("BSFManager:loadScriptingEngine");
-
- // if its already loaded return that
- BSFEngine eng = (BSFEngine) loadedEngines.get(lang);
- if (eng != null) {
- return eng;
- }
-
- // is it a registered language?
- final String engineClassName = (String) registeredEngines.get(lang);
- if (engineClassName == null) {
- logger.error("[BSFManager] unsupported language: " + lang);
- throw new BSFException(BSFException.REASON_UNKNOWN_LANGUAGE,
- "[BSFManager.loadScriptingEngine()] unsupported language: " + lang);
- }
-
- // create the engine and initialize it. if anything goes wrong
- // except.
- try {
-
- Class engineClass=null;
-
- final ClassLoader tccl=Thread.currentThread().getContextClassLoader();
- if (tccl!=null) {
- try {
- engineClass = tccl.loadClass (engineClassName);
- }
- catch (final ClassNotFoundException cnfe)
- {}
- }
-
- if (engineClass==null) // not found, try the defined classLoader
- {
- engineClass = definedClassLoader.loadClass (engineClassName);
- }
-
- final BSFEngine engf = (BSFEngine) engineClass.newInstance();
- final BSFManager thisf = this;
- final String langf = lang;
- final Vector dbf = declaredBeans;
- AccessController.doPrivileged(new PrivilegedExceptionAction() {
- public Object run() throws Exception {
- engf.initialize(thisf, langf, dbf);
- return null;
- }
- });
- eng = engf;
- loadedEngines.put(lang, eng);
- pcs.addPropertyChangeListener(eng);
- return eng;
- } catch (final PrivilegedActionException prive) {
-
- logger.error("[BSFManager] Exception :", prive);
- throw (BSFException) prive.getException();
- } catch (final Throwable t) {
-
- logger.error("[BSFManager] Exception :", t);
- throw new BSFException(BSFException.REASON_OTHER_ERROR,
- "[BSFManager.loadScriptingEngine()] unable to load language: " + lang,
- t);
- }
- }
-
- /**
- * return a handle to a bean registered in the bean registry by the
- * application or a scripting engine. Returns null if bean is not found.
- *
- * @param beanName name of bean to look up
- *
- * @return the bean if its found or null
- */
- public Object lookupBean(final String beanName) {
- logger.debug("BSFManager:lookupBean");
-
- try {
- return ((BSFDeclaredBean)objectRegistry.lookup(beanName)).bean;
- } catch (final IllegalArgumentException e) {
-
- logger.debug("[BSFManager] Exception :", e);
- return null;
- }
- }
-
- /**
- * Registering a bean allows a scripting engine or the application to
- * access that bean by name and to manipulate it.
- *
- * @param beanName name to register under
- * @param bean the bean to register
- */
- public void registerBean(final String beanName, final Object bean) {
- logger.debug("BSFManager:registerBean");
-
- BSFDeclaredBean tempBean;
-
- if(bean == null) {
- tempBean = new BSFDeclaredBean(beanName, null, null);
- } else {
-
- tempBean = new BSFDeclaredBean(beanName, bean, bean.getClass());
- }
- objectRegistry.register(beanName, tempBean);
- }
-
- /**
- * Register a scripting engine in the static registry of the
- * BSFManager.
- *
- * @param lang string identifying language
- * @param engineClassName fully qualified name of the class interfacing
- * the language to BSF.
- * @param extensions array of file extensions that should be mapped to
- * this language type. may be null.
- */
- public static void registerScriptingEngine(final String lang,
- final String engineClassName,
- final String[] extensions) {
- registeredEngines.put(lang, engineClassName);
- if (extensions != null) {
- for (int i = 0; i < extensions.length; i++) {
- String langstr = (String) extn2Lang.get(extensions[i]);
- langstr = (langstr == null) ? lang : lang + ":" + langstr;
- extn2Lang.put(extensions[i], langstr);
- }
- }
- }
-
-
- /**
- * Set the class loader for those that need to use it. Default is he
- * who loaded me or null (i.e., its Class.forName).
- *
- * @param classLoader the class loader to use.
- */
- public void setClassLoader(final ClassLoader classLoader) {
- logger.debug("BSFManager:setClassLoader");
-
- pcs.firePropertyChange("classLoader", this.classLoader, classLoader);
- this.classLoader = classLoader;
- }
-
- /**
- * Set the classpath for those that need to use it. Default is the value
- * of the java.class.path property.
- *
- * @param classPath the classpath to use
- */
- public void setClassPath(final String classPath) {
- logger.debug("BSFManager:setClassPath");
-
- pcs.firePropertyChange("classPath", this.classPath, classPath);
- this.classPath = classPath;
- }
-
- /**
- * Set the object registry used by this manager. By default a new
- * one is created when the manager is new'ed and this overwrites
- * that one.
- *
- * @param objectRegistry the registry to use
- */
- public void setObjectRegistry(final ObjectRegistry objectRegistry) {
- logger.debug("BSFManager:setObjectRegistry");
-
- this.objectRegistry = objectRegistry;
- }
-
- /**
- * Temporary directory to put stuff into (for those who need to). Note
- * that unless this directory is in the classpath or unless the
- * classloader knows to look in here, any classes here will not
- * be found! BSFManager provides a service method to load a class
- * which uses either the classLoader provided by the class loader
- * property or, if that fails, a class loader which knows to load from
- * the tempdir to try to load the class. Default value of tempDir
- * is "." (current working dir).
- *
- * @param tempDir the temporary directory
- */
- public void setTempDir(final String tempDir) {
- logger.debug("BSFManager:setTempDir");
-
- pcs.firePropertyChange("tempDir", this.tempDir, tempDir);
- this.tempDir = tempDir;
- }
-
- /**
- * Gracefully terminate all engines
- */
- public void terminate() {
- logger.debug("BSFManager:terminate");
-
- final Enumeration enginesEnum = loadedEngines.elements();
- BSFEngine engine;
- while (enginesEnum.hasMoreElements()) {
- engine = (BSFEngine) enginesEnum.nextElement();
- pcs.removePropertyChangeListener(engine); // rgf, 2014-12-30: removing memory leak
- engine.terminate();
- }
-
- loadedEngines = new Hashtable();
- }
-
- /**
- * Undeclare a previously declared bean. This removes the bean from
- * the list of declared beans in the manager as well as asks every
- * running engine to undeclared the bean. As with above, if any
- * of the engines except when asked to undeclare, this method does
- * not catch that exception. Quietly returns if the bean is unknown.
- *
- * @param beanName name of bean to undeclare
- *
- * @exception BSFException if any of the languages that are already
- * running decides to throw an exception when asked to
- * undeclare this bean.
- */
- public void undeclareBean(final String beanName) throws BSFException {
- logger.debug("BSFManager:undeclareBean");
-
- unregisterBean(beanName);
-
- BSFDeclaredBean tempBean = null;
- boolean found = false;
- for (final Iterator i = declaredBeans.iterator(); i.hasNext();) {
- tempBean = (BSFDeclaredBean) i.next();
- if (tempBean.name.equals(beanName)) {
- found = true;
- break;
- }
- }
-
- if (found) {
- declaredBeans.removeElement(tempBean);
-
- final Enumeration enginesEnum = loadedEngines.elements();
- while (enginesEnum.hasMoreElements()) {
- final BSFEngine engine = (BSFEngine) enginesEnum.nextElement();
- engine.undeclareBean(tempBean);
- }
- }
- }
-
- /**
- * Unregister a previously registered bean. Silent if name is not found.
- *
- * @param beanName name of bean to unregister
- */
- public void unregisterBean(final String beanName) {
- logger.debug("BSFManager:unregisterBean");
-
- objectRegistry.unregister(beanName);
- }
-
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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;
+
+ // org.apache.commons.logging is delegated to "org.apache.bsf.BSF_Log[Factory]"
+// 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.
+ */
+
+// changed 2007-01-28: ---rgf, fixed Class.forName() to use the context class loader instead; oversaw this the last time
+/* changed 2007-09-17: ---rgf, some Java hosts do not set the Thread's context class loader and
+ load BSF with a customized ClassLoader!
+ Resolution:
+ - use Thread context ClassLoader, if resource or class to
+ load not found, then
+ - use the BSFManager's defining ClassLoader instead, if it is
+ different to the context ClassLoader
+
+ 2012-01-29, ---rgf, - context class loader may not be set, account for it (2009-09-10)
+ - static constructor: fixed logic error in fallback code for getResources() (2011-01-08)
+ 2014-12-30, ---rgf, - remove memory leak when terminating engines, cf. issue [BSF-41]
+*/
+
+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: "250.20120129" stands for: BSF version "2.5.0" as of "2012-01-29"
+ protected static String version="250.20141230";
+
+ // table of registered scripting engines
+ protected static Hashtable registeredEngines = new Hashtable();
+
+ // mapping of file extensions to languages
+ protected static Hashtable extn2Lang = new Hashtable();
+
+ // get the defined CL (ClassLoader which got used to define this class object) // rgf, 20070917
+ protected static ClassLoader definedClassLoader;
+/*
+ protected static ClassLoader appClassLoader; // application/system class loader
+ protected static ClassLoader extClassLoader; // extension (option) class loader
+*/
+
+ /** Returns the defined ClassLoader (the ClassLoader that got used to define the
+ * org.apache.bsf.BSFManager class object).
+ * @return the defined ClassLoader instance
+ */
+ public static ClassLoader getDefinedClassLoader() // rgf, 20070917
+ {
+ return definedClassLoader;
+ }
+
+
+ // 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;
+
+/* rgf (20070917): wrong assumption; context ClassLoader needs to be explicitly
+ requested before usage as BSF could be deployed with different
+ context ClassLoaders on different threads!
+*/
+
+ // 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();
+ // rgf, 20070917, reset to original// 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());
+ private BSF_Log logger = null;
+
+ //////////////////////////////////////////////////////////////////////
+ //
+ // pre-register engines that BSF supports off the shelf
+ //
+ //////////////////////////////////////////////////////////////////////
+
+ static {
+ final String strInfo="org.apache.bsf.BSFManager.dumpEnvironment() [from static{}]";
+ try {
+ definedClassLoader=BSFManager.class.getClassLoader(); // get defining ClassLoader
+
+ final String resourceName="org/apache/bsf/Languages.properties";
+
+ Enumeration e = null;
+ // use the Thread's context class loader to locate the resources
+ final ClassLoader tccl=Thread.currentThread().getContextClassLoader(); // try to get the context class loader
+ if (tccl!=null) // no context class loader available!
+ {
+ e=tccl.getResources(resourceName);
+ }
+ else // fallback
+ {
+ e=definedClassLoader.getResources(resourceName);
+ Thread.currentThread().setContextClassLoader(definedClassLoader); // set Thread context class loader
+ }
+
+ while (e.hasMoreElements()) {
+ final URL url = (URL)e.nextElement();
+ final InputStream is = url.openStream();
+
+ final Properties p = new Properties();
+ p.load(is);
+
+ for (final Enumeration keys = p.propertyNames(); keys.hasMoreElements();) {
+
+ final String key = (String) keys.nextElement();
+ final String value = p.getProperty(key);
+ final String className = value.substring(0, value.indexOf(","));
+
+
+ // get the extensions for this language
+ final String exts = value.substring(value.indexOf(",")+1);
+ final StringTokenizer st = new StringTokenizer(exts, "|");
+ final String[] extensions = new String[st.countTokens()];
+
+ for (int i = 0; st.hasMoreTokens(); i++) {
+ extensions[i] = st.nextToken().trim();
+ }
+
+ registerScriptingEngine(key, className, extensions);
+ }
+ }
+ } catch (final IOException ex) {
+ final BSF_Log logger = BSF_LogFactory.getLog(BSFManager.class.getName());
+ logger.debug("[BSFManager] static {...}");
+ logger.error("[BSFManager] Error reading Languages file, exception :",ex);
+
+ // TODO: leave in case only a no-op-logger is available or remove next two statements?
+ ex.printStackTrace();
+ System.err.println("Error reading Languages file " + ex);
+ } catch (final NoSuchElementException nsee) {
+ final BSF_Log logger = BSF_LogFactory.getLog(BSFManager.class.getName());
+ logger.debug("[BSFManager] static {...}");
+ logger.error("[BSFManager] Syntax error in Languages resource bundle, exception :",nsee);
+
+ // TODO: leave in case only a no-op-logger is available or remove next two statements?
+ nsee.printStackTrace();
+ System.err.println("Syntax error in Languages resource bundle");
+ } catch (final MissingResourceException mre) {
+ final BSF_Log logger = BSF_LogFactory.getLog(BSFManager.class.getName());
+ logger.debug("[BSFManager] static {...}");
+ logger.error("[BSFManager] Initialization error, exception :",mre);
+
+ // TODO: leave in case only a no-op-logger is available or remove next two statements?
+ mre.printStackTrace();
+ System.err.println("Initialization error: " + mre.toString());
+ }
+ }
+
+ public BSFManager() {
+ pcs = new PropertyChangeSupport(this);
+ // handle logger
+ logger = BSF_LogFactory.getLog(this.getClass().getName());
+ }
+
+
+ /** Returns the version string of BSF.
+ *
+ * @return version string 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.
+ *
+ <br>Example: "<code>250.20120129</code>"
+ stands for: BSF version <code>2.5.0</code> as of <code>2012-01-29</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(final String lang,
+ final String source,
+ final int lineNo,
+ final int columnNo,
+ final Object funcBody,
+ final Vector paramNames,
+ final 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 (final PrivilegedActionException prive) {
+
+ logger.error("[BSFManager] 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 {@code CodeBuffer}.
+ *
+ * @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(final String lang,
+ final String source,
+ final int lineNo,
+ final int columnNo,
+ final Object funcBody,
+ final Vector paramNames,
+ final Vector arguments,
+ final 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 (final PrivilegedActionException prive) {
+
+ logger.error("[BSFManager] Exception :", prive);
+ throw (BSFException) prive.getException();
+ }
+ }
+
+ /**
+ * Compile the given expression of the given language into the given
+ * {@code CodeBuffer}.
+ *
+ * @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(final String lang,
+ final String source,
+ final int lineNo,
+ final int columnNo,
+ final Object expr,
+ final CodeBuffer cb)
+ throws BSFException {
+ logger.debug("BSFManager:compileExpr");
+
+ final BSFEngine e = loadScriptingEngine(lang);
+ final String sourcef = source;
+ final int lineNof = lineNo, columnNof = columnNo;
+ final Object exprf = expr;
+ final CodeBuffer cbf = cb;
+
+ try {
+ AccessController.doPrivileged(new PrivilegedExceptionAction() {
+ public Object run() throws Exception {
+ e.compileExpr(sourcef, lineNof, columnNof, exprf, cbf);
+ return null;
+ }
+ });
+ } catch (final PrivilegedActionException prive) {
+
+ logger.error("[BSFManager] Exception :", prive);
+ throw (BSFException) prive.getException();
+ }
+ }
+
+ /**
+ * Compile the given script of the given language into the given
+ * {@code CodeBuffer}.
+ *
+ * @param lang language identifier
+ * @param source (context info) the source of this script
+ (e.g., filename)
+ * @param lineNo (context info) the line number in source for script
+ * @param columnNo (context info) the column number in source for script
+ * @param script the script to compile
+ * @param cb code buffer to compile into
+ *
+ * @exception BSFException if any error while compiling the script
+ */
+ public void compileScript(final String lang,
+ final String source,
+ final int lineNo,
+ final int columnNo,
+ final Object script,
+ final CodeBuffer cb)
+ throws BSFException {
+ logger.debug("BSFManager:compileScript");
+
+ final BSFEngine e = loadScriptingEngine(lang);
+ final String sourcef = source;
+ final int lineNof = lineNo, columnNof = columnNo;
+ final Object scriptf = script;
+ final CodeBuffer cbf = cb;
+
+ try {
+ AccessController.doPrivileged(new PrivilegedExceptionAction() {
+ public Object run() throws Exception {
+ e.compileScript(sourcef, lineNof, columnNof,
+ scriptf, cbf);
+ return null;
+ }
+ });
+ } catch (final PrivilegedActionException prive) {
+
+ logger.error("[BSFManager] Exception :", prive);
+ throw (BSFException) prive.getException();
+ }
+ }
+
+ /**
+ * Declare a bean. The difference between declaring and registering
+ * is that engines are spsed to make declared beans "pre-available"
+ * in the scripts as far as possible. That is, if a script author
+ * needs a registered bean, he needs to look it up in some way. However
+ * if he needs a declared bean, the language has the responsibility to
+ * make those beans avaialable "automatically."
+ * <p>
+ * When a bean is declared it is automatically registered as well
+ * so that any declared bean can be gotton to by looking it up as well.
+ * <p>
+ * If any of the languages that are already running in this manager
+ * says they don't like this (by throwing an exception) then this
+ * method will simply quit with that exception. That is, any engines
+ * that come after than in the engine enumeration will not even be
+ * told about this new bean.
+ * <p>
+ * So, in general its best to declare beans before the manager has
+ * been asked to load any engines because then the user can be informed
+ * when an engine rejects it. Also, its much more likely that an engine
+ * can declare a bean at start time than it can at any time.
+ *
+ * @param beanName name to declare bean as
+ * @param bean the bean that's being declared
+ * @param type the type to represent the bean as
+ *
+ * @exception BSFException if any of the languages that are already
+ * running decides to throw an exception when asked to
+ * declare this bean.
+ */
+ public void declareBean(final String beanName, final Object bean, final Class type)
+ throws BSFException {
+ logger.debug("BSFManager:declareBean");
+
+ registerBean(beanName, bean);
+
+ final BSFDeclaredBean tempBean = new BSFDeclaredBean(beanName, bean, type);
+ declaredBeans.addElement(tempBean);
+
+ final Enumeration enginesEnum = loadedEngines.elements();
+ BSFEngine engine;
+ while (enginesEnum.hasMoreElements()) {
+ engine = (BSFEngine) enginesEnum.nextElement();
+ engine.declareBean(tempBean);
+ }
+ }
+
+ /**
+ * Evaluate the given expression of the given language 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 expr the expression to evaluate
+ *
+ * @exception BSFException if anything goes wrong while running the script
+ */
+ public Object eval(final String lang,
+ final String source,
+ final int lineNo,
+ final int columnNo,
+ final Object expr)
+ throws BSFException {
+ logger.debug("BSFManager:eval");
+
+ final BSFEngine e = loadScriptingEngine(lang);
+ final String sourcef = source;
+ final int lineNof = lineNo, columnNof = columnNo;
+ final Object exprf = expr;
+ Object result = null;
+
+ try {
+ final Object resultf =
+ AccessController.doPrivileged(new PrivilegedExceptionAction() {
+ public Object run() throws Exception {
+ return e.eval(sourcef, lineNof, columnNof, exprf);
+ }
+ });
+ result = resultf;
+ } catch (final PrivilegedActionException prive) {
+
+ logger.error("[BSFManager] Exception: ", prive);
+ throw (BSFException) prive.getException();
+ }
+
+ return result;
+ }
+
+ //////////////////////////////////////////////////////////////////////
+ //
+ // Convenience functions for exec'ing and eval'ing scripts directly
+ // without loading and dealing with engines etc..
+ //
+ //////////////////////////////////////////////////////////////////////
+
+ /**
+ * Execute the given script of the given language.
+ *
+ * @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 script the script to execute
+ *
+ * @exception BSFException if anything goes wrong while running the script
+ */
+ public void exec(final String lang,
+ final String source,
+ final int lineNo,
+ final int columnNo,
+ final Object script)
+ throws BSFException {
+ logger.debug("BSFManager:exec");
+
+ final BSFEngine e = loadScriptingEngine(lang);
+ final String sourcef = source;
+ final int lineNof = lineNo, columnNof = columnNo;
+ final Object scriptf = script;
+
+ try {
+ AccessController.doPrivileged(new PrivilegedExceptionAction() {
+ public Object run() throws Exception {
+ e.exec(sourcef, lineNof, columnNof, scriptf);
+ return null;
+ }
+ });
+ } catch (final PrivilegedActionException prive) {
+
+ logger.error("[BSFManager] Exception :", prive);
+ throw (BSFException) prive.getException();
+ }
+ }
+
+ /**
+ * Execute the given script of the given language, attempting to
+ * emulate an interactive session w/ the language.
+ *
+ * @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 script the script to execute
+ *
+ * @exception BSFException if anything goes wrong while running the script
+ */
+ public void iexec(final String lang,
+ final String source,
+ final int lineNo,
+ final int columnNo,
+ final Object script)
+ throws BSFException {
+ logger.debug("BSFManager:iexec");
+
+ final BSFEngine e = loadScriptingEngine(lang);
+ final String sourcef = source;
+ final int lineNof = lineNo, columnNof = columnNo;
+ final Object scriptf = script;
+
+ try {
+ AccessController.doPrivileged(new PrivilegedExceptionAction() {
+ public Object run() throws Exception {
+ e.iexec(sourcef, lineNof, columnNof, scriptf);
+ return null;
+ }
+ });
+ } catch (final PrivilegedActionException prive) {
+
+ logger.error("[BSFManager] Exception :", prive);
+ throw (BSFException) prive.getException();
+ }
+ }
+
+ /**
+ * Get classLoader
+ */
+ public ClassLoader getClassLoader() {
+ logger.debug("BSFManager:getClassLoader");
+ return classLoader;
+ }
+
+ /**
+ * Get classPath
+ */
+ public String getClassPath() {
+ logger.debug("BSFManager:getClassPath");
+ if (classPath == null) {
+ try {
+ classPath = System.getProperty("java.class.path");
+ } catch (final Throwable t) {
+
+ logger.debug("[BSFManager] Exception :", t);
+ // prolly a security exception .. so no can do
+ }
+ }
+ return classPath;
+ }
+
+ /**
+ * Determine the language of a script file by looking at the file
+ * extension.
+ *
+ * @param fileName the name of the file
+ *
+ * @return the scripting language the file is in if the file extension
+ * is known to me (must have been registered via
+ * registerScriptingEngine).
+ *
+ * @exception BSFException if file's extension is unknown.
+ */
+ public static String getLangFromFilename(final String fileName)
+ throws BSFException {
+ final int dotIndex = fileName.lastIndexOf(".");
+
+ if (dotIndex != -1) {
+ final String extn = fileName.substring(dotIndex + 1);
+ String langval = (String) extn2Lang.get(extn);
+ String lang = null;
+ int index, loops = 0;
+
+ if (langval != null) {
+ final ClassLoader tccl=Thread.currentThread().getContextClassLoader(); // rgf, 2009-09-10
+
+ while ((index = langval.indexOf(":", 0)) != -1) {
+ // Great. Multiple language engines registered
+ // for this extension.
+ // Try to find first one that is in our classpath.
+ lang = langval.substring(0, index);
+ langval = langval.substring(index + 1);
+ loops++;
+
+ // Test to see if in classpath
+ String engineName=null;
+ try {
+ engineName =
+ (String) registeredEngines.get(lang);
+
+ boolean bTryDefinedClassLoader=false;
+ if (tccl!=null) // context CL available, try it first
+ {
+ try
+ {
+ tccl.loadClass (engineName);
+ }
+ catch (final ClassNotFoundException cnfe)
+ {
+ bTryDefinedClassLoader=true;
+ }
+ }
+
+ if (bTryDefinedClassLoader || tccl==null) // not found, try defined CL next
+ {
+ definedClassLoader.loadClass(engineName);
+ }
+ }
+ catch (final ClassNotFoundException cnfe2) {
+ // Bummer.
+ lang = langval;
+ continue;
+ }
+
+ // Got past that? Good.
+ break;
+ }
+ if (loops == 0) { lang = langval; }
+ }
+
+ if (lang != null && lang != "") {
+ return lang;
+ }
+ }
+ throw new BSFException(BSFException.REASON_OTHER_ERROR,
+ "[BSFManager.getLangFromFilename] file extension missing or unknown: "
+ + "unable to determine language for '"
+ + fileName
+ + "'");
+ }
+
+ /**
+ * Return the current object registry of the manager.
+ *
+ * @return the current registry.
+ */
+ public ObjectRegistry getObjectRegistry() {
+ return objectRegistry;
+ }
+
+ /**
+ * Get tempDir
+ */
+ public String getTempDir() {
+ return tempDir;
+ }
+
+ /**
+ * Determine whether a language is registered.
+ *
+ * @param lang string identifying a language
+ *
+ * @return true iff it is
+ */
+ public static boolean isLanguageRegistered(final String lang) {
+ return (registeredEngines.get(lang) != null);
+ }
+
+ //////////////////////////////////////////////////////////////////////
+ //
+ // Bean scripting framework services
+ //
+ //////////////////////////////////////////////////////////////////////
+
+ /**
+ * Load a scripting engine based on the lang string identifying it.
+ *
+ * @param lang string identifying language
+ * @exception BSFException if the language is unknown (i.e., if it
+ * has not been registered) with a reason of
+ * REASON_UNKNOWN_LANGUAGE. If the language is known but
+ * if the interface can't be created for some reason, then
+ * the reason is set to REASON_OTHER_ERROR and the actual
+ * exception is passed on as well.
+ */
+ public BSFEngine loadScriptingEngine(final String lang) throws BSFException {
+ logger.debug("BSFManager:loadScriptingEngine");
+
+ // if its already loaded return that
+ BSFEngine eng = (BSFEngine) loadedEngines.get(lang);
+ if (eng != null) {
+ return eng;
+ }
+
+ // is it a registered language?
+ final String engineClassName = (String) registeredEngines.get(lang);
+ if (engineClassName == null) {
+ logger.error("[BSFManager] unsupported language: " + lang);
+ throw new BSFException(BSFException.REASON_UNKNOWN_LANGUAGE,
+ "[BSFManager.loadScriptingEngine()] unsupported language: " + lang);
+ }
+
+ // create the engine and initialize it. if anything goes wrong
+ // except.
+ try {
+
+ Class engineClass=null;
+
+ final ClassLoader tccl=Thread.currentThread().getContextClassLoader();
+ if (tccl!=null) {
+ try {
+ engineClass = tccl.loadClass (engineClassName);
+ }
+ catch (final ClassNotFoundException cnfe)
+ {}
+ }
+
+ if (engineClass==null) // not found, try the defined classLoader
+ {
+ engineClass = definedClassLoader.loadClass (engineClassName);
+ }
+
+ final BSFEngine engf = (BSFEngine) engineClass.newInstance();
+ final BSFManager thisf = this;
+ final String langf = lang;
+ final Vector dbf = declaredBeans;
+ AccessController.doPrivileged(new PrivilegedExceptionAction() {
+ public Object run() throws Exception {
+ engf.initialize(thisf, langf, dbf);
+ return null;
+ }
+ });
+ eng = engf;
+ loadedEngines.put(lang, eng);
+ pcs.addPropertyChangeListener(eng);
+ return eng;
+ } catch (final PrivilegedActionException prive) {
+
+ logger.error("[BSFManager] Exception :", prive);
+ throw (BSFException) prive.getException();
+ } catch (final Throwable t) {
+
+ logger.error("[BSFManager] Exception :", t);
+ throw new BSFException(BSFException.REASON_OTHER_ERROR,
+ "[BSFManager.loadScriptingEngine()] unable to load language: " + lang,
+ t);
+ }
+ }
+
+ /**
+ * return a handle to a bean registered in the bean registry by the
+ * application or a scripting engine. Returns null if bean is not found.
+ *
+ * @param beanName name of bean to look up
+ *
+ * @return the bean if its found or null
+ */
+ public Object lookupBean(final String beanName) {
+ logger.debug("BSFManager:lookupBean");
+
+ try {
+ return ((BSFDeclaredBean)objectRegistry.lookup(beanName)).bean;
+ } catch (final IllegalArgumentException e) {
+
+ logger.debug("[BSFManager] Exception :", e);
+ return null;
+ }
+ }
+
+ /**
+ * Registering a bean allows a scripting engine or the application to
+ * access that bean by name and to manipulate it.
+ *
+ * @param beanName name to register under
+ * @param bean the bean to register
+ */
+ public void registerBean(final String beanName, final Object bean) {
+ logger.debug("BSFManager:registerBean");
+
+ BSFDeclaredBean tempBean;
+
+ if(bean == null) {
+ tempBean = new BSFDeclaredBean(beanName, null, null);
+ } else {
+
+ tempBean = new BSFDeclaredBean(beanName, bean, bean.getClass());
+ }
+ objectRegistry.register(beanName, tempBean);
+ }
+
+ /**
+ * Register a scripting engine in the static registry of the
+ * BSFManager.
+ *
+ * @param lang string identifying language
+ * @param engineClassName fully qualified name of the class interfacing
+ * the language to BSF.
+ * @param extensions array of file extensions that should be mapped to
+ * this language type. may be null.
+ */
+ public static void registerScriptingEngine(final String lang,
+ final String engineClassName,
+ final String[] extensions) {
+ registeredEngines.put(lang, engineClassName);
+ if (extensions != null) {
+ for (int i = 0; i < extensions.length; i++) {
+ String langstr = (String) extn2Lang.get(extensions[i]);
+ langstr = (langstr == null) ? lang : lang + ":" + langstr;
+ extn2Lang.put(extensions[i], langstr);
+ }
+ }
+ }
+
+
+ /**
+ * Set the class loader for those that need to use it. Default is he
+ * who loaded me or null (i.e., its Class.forName).
+ *
+ * @param classLoader the class loader to use.
+ */
+ public void setClassLoader(final ClassLoader classLoader) {
+ logger.debug("BSFManager:setClassLoader");
+
+ pcs.firePropertyChange("classLoader", this.classLoader, classLoader);
+ this.classLoader = classLoader;
+ }
+
+ /**
+ * Set the classpath for those that need to use it. Default is the value
+ * of the java.class.path property.
+ *
+ * @param classPath the classpath to use
+ */
+ public void setClassPath(final String classPath) {
+ logger.debug("BSFManager:setClassPath");
+
+ pcs.firePropertyChange("classPath", this.classPath, classPath);
+ this.classPath = classPath;
+ }
+
+ /**
+ * Set the object registry used by this manager. By default a new
+ * one is created when the manager is new'ed and this overwrites
+ * that one.
+ *
+ * @param objectRegistry the registry to use
+ */
+ public void setObjectRegistry(final ObjectRegistry objectRegistry) {
+ logger.debug("BSFManager:setObjectRegistry");
+
+ this.objectRegistry = objectRegistry;
+ }
+
+ /**
+ * Temporary directory to put stuff into (for those who need to). Note
+ * that unless this directory is in the classpath or unless the
+ * classloader knows to look in here, any classes here will not
+ * be found! BSFManager provides a service method to load a class
+ * which uses either the classLoader provided by the class loader
+ * property or, if that fails, a class loader which knows to load from
+ * the tempdir to try to load the class. Default value of tempDir
+ * is "." (current working dir).
+ *
+ * @param tempDir the temporary directory
+ */
+ public void setTempDir(final String tempDir) {
+ logger.debug("BSFManager:setTempDir");
+
+ pcs.firePropertyChange("tempDir", this.tempDir, tempDir);
+ this.tempDir = tempDir;
+ }
+
+ /**
+ * Gracefully terminate all engines
+ */
+ public void terminate() {
+ logger.debug("BSFManager:terminate");
+
+ final Enumeration enginesEnum = loadedEngines.elements();
+ BSFEngine engine;
+ while (enginesEnum.hasMoreElements()) {
+ engine = (BSFEngine) enginesEnum.nextElement();
+ pcs.removePropertyChangeListener(engine); // rgf, 2014-12-30: removing memory leak
+ engine.terminate();
+ }
+
+ loadedEngines = new Hashtable();
+ }
+
+ /**
+ * Undeclare a previously declared bean. This removes the bean from
+ * the list of declared beans in the manager as well as asks every
+ * running engine to undeclared the bean. As with above, if any
+ * of the engines except when asked to undeclare, this method does
+ * not catch that exception. Quietly returns if the bean is unknown.
+ *
+ * @param beanName name of bean to undeclare
+ *
+ * @exception BSFException if any of the languages that are already
+ * running decides to throw an exception when asked to
+ * undeclare this bean.
+ */
+ public void undeclareBean(final String beanName) throws BSFException {
+ logger.debug("BSFManager:undeclareBean");
+
+ unregisterBean(beanName);
+
+ BSFDeclaredBean tempBean = null;
+ boolean found = false;
+ for (final Iterator i = declaredBeans.iterator(); i.hasNext();) {
+ tempBean = (BSFDeclaredBean) i.next();
+ if (tempBean.name.equals(beanName)) {
+ found = true;
+ break;
+ }
+ }
+
+ if (found) {
+ declaredBeans.removeElement(tempBean);
+
+ final Enumeration enginesEnum = loadedEngines.elements();
+ while (enginesEnum.hasMoreElements()) {
+ final BSFEngine engine = (BSFEngine) enginesEnum.nextElement();
+ engine.undeclareBean(tempBean);
+ }
+ }
+ }
+
+ /**
+ * Unregister a previously registered bean. Silent if name is not found.
+ *
+ * @param beanName name of bean to unregister
+ */
+ public void unregisterBean(final String beanName) {
+ logger.debug("BSFManager:unregisterBean");
+
+ objectRegistry.unregister(beanName);
+ }
+
+
+}
diff --git a/src/main/java/org/apache/bsf/BSF_Log.java b/src/main/java/org/apache/bsf/BSF_Log.java
index ae72c22..734a717 100644
--- a/src/main/java/org/apache/bsf/BSF_Log.java
+++ b/src/main/java/org/apache/bsf/BSF_Log.java
@@ -1,511 +1,510 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.lang.reflect.*;
-
-/** This class is used in BSF for logging (a delegator for <em>org.apache.commons.logging</em>,
- * which is needed for compilation) using the <code>org.apache.commons.logging.Log</code>
- * methods.
-
- Therefore this class implements all the <code>org.apache.commons.logging.Log</code>
- methods. If <code>org.apache.commons.logging.LogFactory</code> is available, then this
- * class is used to get an <code>org.apache.commons.logging.Log</code> instance to which to
- * forward the message.
-
- * Therefore, if Apache's common logging is available, then it is employed.
- * If Apache's commons logging is <em>not</em> available then a <em>no-op</em> behavior
- is employed, modelled after <code>org.apache.commons.logging.impl.NoOpLog</code>.
-
- @author Rony G. Flatscher, 2006-12-08
-*/
-
-/* ---rgf, 2007-01-29, loading and invoking all methods via reflection
- ---rgf, 2007-09-17, adjusted for using default class loader, if system class loader fails
- ---rgf, 2011-01-08, cf. [https://issues.apache.org/jira/browse/BSF-37]
- - context class loader may not be set, account for it (2009-09-10)
- - fix logic error if context class loader is not set (e.g. observed on MacOSX, 2011-01-08)
-*/
-
-//@Immutable
-public class BSF_Log // implements org.apache.commons.logging.Log
-{
- final private static int iDebug=0; // don't show any debug-info
- final static private Class oac_LogFactory;
- //NOTUSED final static private Method oac_LogFactoryGetLog_Clazz;
- final static private Method oac_LogFactoryGetLog_String;
-
- final static private Method meths[] = new Method [18]; // store the Log methods
- // define the slots in the array
- final private static int debug1 = 0 ;
- final private static int debug2 = 1 ;
- final private static int isDebugEnabled = 2 ;
- final private static int error1 = 3 ;
- final private static int error2 = 4 ;
- final private static int isErrorEnabled = 5 ;
- final private static int fatal1 = 6 ;
- final private static int fatal2 = 7 ;
- final private static int isFatalEnabled = 8 ;
- final private static int info1 = 9 ;
- final private static int info2 = 10 ;
- final private static int isInfoEnabled = 11 ;
- final private static int trace1 = 12 ;
- final private static int trace2 = 13 ;
- final private static int isTraceEnabled = 14 ;
- final private static int warn1 = 15 ;
- final private static int warn2 = 16 ;
- final private static int isWarnEnabled = 17 ;
-
- static { // try to demand load the apache commons logging LogFactory
-
- Class oac_LogFactory_ = null;
- //NOTUSED Method oac_LogFactoryGetLog_Clazz_ = null;
- Method oac_LogFactoryGetLog_String_ = null;
-
- try // rgf, 20070917: o.k., if not found, try definedClassLoader instead
- {
- ClassLoader cl= Thread.currentThread().getContextClassLoader();
-
- final String str4Log="org.apache.commons.logging.Log";
-
- Class logClass = null;
-
- if (cl!=null) // use current Thread's context class loader, if set
- {
- try {
- logClass = cl.loadClass(str4Log);
- }
- catch (final ClassNotFoundException e1) // not found by contextClassLoader
- {}
- }
-
- if (logClass==null) // not found, try defined class loader instead
- {
- final ClassLoader defCL=BSFManager.getDefinedClassLoader();
- logClass = defCL.loadClass(str4Log);
- cl=defCL; // class found, hence we use the definedClassLoader here
- }
-
- oac_LogFactory_ = cl.loadClass("org.apache.commons.logging.LogFactory");
-
- // get method with Class object argument
- //NOTUSED oac_LogFactoryGetLog_Clazz_ = oac_LogFactory_.getMethod("getLog", new Class[] {Class.class});
-
- // get method with String object argument
- oac_LogFactoryGetLog_String_ = oac_LogFactory_.getMethod("getLog", new Class[] {String.class});
-
- // get the Log methods
- final String str[][]={{"debug", "isDebugEnabled"},
- {"error", "isErrorEnabled"},
- {"fatal", "isFatalEnabled"},
- {"info", "isInfoEnabled" },
- {"trace", "isTraceEnabled"},
- {"warn", "isWarnEnabled" }};
- int i=0;
- for ( ; i<6; i++)
- {
- final int j=i*3;
- meths[j ]=logClass.getMethod(str[i][0], new Class[] {Object.class});
-
- meths[j+1]=logClass.getMethod(str[i][0], new Class[] {Object.class, Throwable.class});
-
- meths[j+2]=logClass.getMethod(str[i][1], new Class[] {} );
-
- }
- }
-
- catch (final ClassNotFoundException e)// o.k., so we do not use org.apache.commons.logging in this run
- {
- if (iDebug>1) {
- e.printStackTrace();
- }
- oac_LogFactory_=null; // make sure it does not get used
- oac_LogFactoryGetLog_String_=null; // make sure it does not get used
- }
- catch (final NoSuchMethodException e)// o.k., so we do not use org.apache.commons.logging in this run
- {
- if (iDebug>1) {
- e.printStackTrace();
- }
- oac_LogFactory_=null; // make sure it does not get used
- oac_LogFactoryGetLog_String_=null; // make sure it does not get used
- }
-
- // Set up final fields
- oac_LogFactory = oac_LogFactory_;
- //NOTUSED oac_LogFactoryGetLog_Clazz = oac_LogFactoryGetLog_Clazz_;
- oac_LogFactoryGetLog_String = oac_LogFactoryGetLog_String_;
- }
-
-
- /** Name of the BSF_Log instance. */
- final String name;
-
- /** Proxy object for <em>org.apache.commons.logging.Log</em>, if available. */
- private final Object oac_logger;
-
-
- public BSF_Log()
- {
- this("<?>");
- }
-
- public BSF_Log(final String name)
- {
- Object oac_logger_ = null;
- this.name=name;
- if (oac_LogFactory!=null)
- {
- try // try to get an org.apache.commons.logging.Log object from the LogFactory
- {
- oac_logger_=oac_LogFactoryGetLog_String.invoke(oac_LogFactory, new Object[] {name});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
- oac_logger = oac_logger_;
- }
-
- public BSF_Log(final Class clazz)
- {
- this(clazz.getName());
- }
-
- public void debug(final Object msg)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).debug(msg);
- meths[debug1].invoke(oac_logger, new Object [] {msg});
-
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
- public void debug(final Object msg, final Throwable t)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).debug(msg, t);
- meths[debug2].invoke(oac_logger, new Object [] {msg, t});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
- public void error(final Object msg)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).error(msg);
- meths[error1].invoke(oac_logger, new Object [] {msg});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
- public void error(final Object msg, final Throwable t)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).error(msg, t);
- meths[error2].invoke(oac_logger, new Object [] {msg, t});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
-
- public void fatal(final Object msg)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).fatal(msg);
- meths[fatal1].invoke(oac_logger, new Object [] {msg});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
- public void fatal(final Object msg, final Throwable t)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).fatal(msg, t);
- meths[fatal2].invoke(oac_logger, new Object [] {msg, t});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
-
- public void info (final Object msg)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).info(msg);
- meths[info1].invoke(oac_logger, new Object [] {msg});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
- public void info (final Object msg, final Throwable t)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).info(msg, t);
- meths[info2].invoke(oac_logger, new Object [] {msg, t});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
-
- public void trace(final Object msg)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).trace(msg);
- meths[trace1].invoke(oac_logger, new Object [] {msg});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
- public void trace(final Object msg, final Throwable t)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).trace(msg, t);
- meths[trace2].invoke(oac_logger, new Object [] {msg, t});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
-
- public void warn (final Object msg)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).warn(msg);
- meths[warn1].invoke(oac_logger, new Object [] {msg});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
- public void warn (final Object msg, final Throwable t)
- {
- if (oac_logger==null)
- {
- return; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // ((org.apache.commons.logging.Log) oac_logger).warn(msg, t);
- meths[warn2].invoke(oac_logger, new Object [] {msg, t});
- }
- catch (final Exception e) { e.printStackTrace(); }
- }
-
-
- public boolean isDebugEnabled()
- {
- if (oac_logger==null) {return false;} // no org.apache.commons.logging.Log object ?
-
- try
- {
- // return ((org.apache.commons.logging.Log) oac_logger).isDebugEnabled();
- return ((Boolean) meths[isDebugEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
- }
- catch (final Exception e) { }
- finally { return false; }
- }
-
- public boolean isErrorEnabled()
- {
- if (oac_logger==null)
- {
- return false; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // return ((org.apache.commons.logging.Log) oac_logger).isErrorEnabled();
- return ((Boolean) meths[isErrorEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
- }
- catch (final Exception e) { }
- finally { return false; }
- }
-
- public boolean isFatalEnabled()
- {
- if (oac_logger==null)
- {
- return false; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // return ((org.apache.commons.logging.Log) oac_logger).isFatalEnabled();
- return ((Boolean) meths[isFatalEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
- }
- catch (final Exception e) { }
- finally { return false; }
- }
-
- public boolean isInfoEnabled ()
- {
- if (oac_logger==null)
- {
- return false; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // return ((org.apache.commons.logging.Log) oac_logger).isInfoEnabled();
- return ((Boolean) meths[isInfoEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
- }
- catch (final Exception e) { }
- finally { return false; }
- }
-
- public boolean isTraceEnabled()
- {
- if (oac_logger==null)
- {
- return false; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // return ((org.apache.commons.logging.Log) oac_logger).isTraceEnabled();
- return ((Boolean) meths[isTraceEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
- }
- catch (final Exception e) { }
- finally { return false; }
- }
-
- public boolean isWarnEnabled ()
- {
- if (oac_logger==null)
- {
- return false; // no org.apache.commons.logging.Log object ?
- }
-
- try
- {
- // return ((org.apache.commons.logging.Log) oac_logger).isWarnEnabled();
- return ((Boolean) meths[isWarnEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
- }
- catch (final Exception e) { }
- finally { return false; }
- }
-
-
- // for development purposes only (to debug this class on its own)
- public static void main (final String args[]) {
- System.out.println("in BSF_Log ...");
- System.out.println("--------------------------------------------------------");
- System.out.println("--------------------------------------------------------");
- BSF_Log bl=new BSF_Log();
- dump(bl);
- bl=new BSF_Log(Class.class);
- dump(bl);
- bl=new BSF_Log("Rony was here...");
- dump(bl);
-
- }
-
- static void dump(final BSF_Log bl)
- {
- System.out.println("\n\tbl=["+bl+"] --->>> --->>> --->>>");
- System.err.print("/debug **/"); bl.debug("debug message. "); System.err.println("\\** debug.\\");
- System.err.print("/error **/"); bl.error("error message. "); System.err.println("\\** error.\\");
- System.err.print("/fatal **/"); bl.fatal("fatal message. "); System.err.println("\\** fatal.\\");
- System.err.print("/info **/"); bl.info ("info message. "); System.err.println("\\** info .\\");
- System.err.print("/trace **/"); bl.trace("trace message. "); System.err.println("\\** trace.\\");
- System.err.print("/warn **/"); bl.warn ("warn message. "); System.err.println("\\** warn .\\");
- System.err.println();
-
- final Throwable t=new Throwable ("Test from Rony for: "+bl);
- System.err.print("/debug **/"); bl.debug("debug message. ", t); System.err.println("\\** debug.\\");
- System.err.print("/error **/"); bl.error("error message. ", t); System.err.println("\\** error.\\");
- System.err.print("/fatal **/"); bl.fatal("fatal message. ", t); System.err.println("\\** fatal.\\");
- System.err.print("/info **/"); bl.info ("info message. ", t); System.err.println("\\** info .\\");
- System.err.print("/trace **/"); bl.trace("trace message. ", t); System.err.println("\\** trace.\\");
- System.err.print("/warn **/"); bl.warn ("warn message. ", t); System.err.println("\\** warn .\\");
- System.err.println();
-
- System.out.println("\tisDebugEnabled: "+bl.isDebugEnabled());
- System.out.println("\tisErrorEnabled: "+bl.isErrorEnabled());
- System.out.println("\tisFatalEnabled: "+bl.isFatalEnabled());
- System.out.println("\tisInfo Enabled: "+bl.isInfoEnabled());
- System.out.println("\tisTraceEnabled: "+bl.isTraceEnabled());
- System.out.println("\tisWarn Enabled: "+bl.isWarnEnabled());
-
- System.out.println("\tbl=["+bl+"] <<<--- <<<--- <<<---");
- System.out.println("--------------------------------------------------------");
- }
-}
-
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.lang.reflect.*;
+
+/** This class is used in BSF for logging (a delegator for <em>org.apache.commons.logging</em>,
+ * which is needed for compilation) using the <code>org.apache.commons.logging.Log</code>
+ * methods.
+
+ Therefore this class implements all the <code>org.apache.commons.logging.Log</code>
+ methods. If <code>org.apache.commons.logging.LogFactory</code> is available, then this
+ * class is used to get an <code>org.apache.commons.logging.Log</code> instance to which to
+ * forward the message.
+
+ * Therefore, if Apache's common logging is available, then it is employed.
+ * If Apache's commons logging is <em>not</em> available then a <em>no-op</em> behavior
+ is employed, modelled after <code>org.apache.commons.logging.impl.NoOpLog</code>.
+
+*/
+
+/* ---rgf, 2007-01-29, loading and invoking all methods via reflection
+ ---rgf, 2007-09-17, adjusted for using default class loader, if system class loader fails
+ ---rgf, 2011-01-08, cf. [https://issues.apache.org/jira/browse/BSF-37]
+ - context class loader may not be set, account for it (2009-09-10)
+ - fix logic error if context class loader is not set (e.g. observed on MacOSX, 2011-01-08)
+*/
+
+//@Immutable
+public class BSF_Log // implements org.apache.commons.logging.Log
+{
+ final private static int iDebug=0; // don't show any debug-info
+ final static private Class oac_LogFactory;
+ //NOTUSED final static private Method oac_LogFactoryGetLog_Clazz;
+ final static private Method oac_LogFactoryGetLog_String;
+
+ final static private Method meths[] = new Method [18]; // store the Log methods
+ // define the slots in the array
+ final private static int debug1 = 0 ;
+ final private static int debug2 = 1 ;
+ final private static int isDebugEnabled = 2 ;
+ final private static int error1 = 3 ;
+ final private static int error2 = 4 ;
+ final private static int isErrorEnabled = 5 ;
+ final private static int fatal1 = 6 ;
+ final private static int fatal2 = 7 ;
+ final private static int isFatalEnabled = 8 ;
+ final private static int info1 = 9 ;
+ final private static int info2 = 10 ;
+ final private static int isInfoEnabled = 11 ;
+ final private static int trace1 = 12 ;
+ final private static int trace2 = 13 ;
+ final private static int isTraceEnabled = 14 ;
+ final private static int warn1 = 15 ;
+ final private static int warn2 = 16 ;
+ final private static int isWarnEnabled = 17 ;
+
+ static { // try to demand load the apache commons logging LogFactory
+
+ Class oac_LogFactory_ = null;
+ //NOTUSED Method oac_LogFactoryGetLog_Clazz_ = null;
+ Method oac_LogFactoryGetLog_String_ = null;
+
+ try // rgf, 20070917: o.k., if not found, try definedClassLoader instead
+ {
+ ClassLoader cl= Thread.currentThread().getContextClassLoader();
+
+ final String str4Log="org.apache.commons.logging.Log";
+
+ Class logClass = null;
+
+ if (cl!=null) // use current Thread's context class loader, if set
+ {
+ try {
+ logClass = cl.loadClass(str4Log);
+ }
+ catch (final ClassNotFoundException e1) // not found by contextClassLoader
+ {}
+ }
+
+ if (logClass==null) // not found, try defined class loader instead
+ {
+ final ClassLoader defCL=BSFManager.getDefinedClassLoader();
+ logClass = defCL.loadClass(str4Log);
+ cl=defCL; // class found, hence we use the definedClassLoader here
+ }
+
+ oac_LogFactory_ = cl.loadClass("org.apache.commons.logging.LogFactory");
+
+ // get method with Class object argument
+ //NOTUSED oac_LogFactoryGetLog_Clazz_ = oac_LogFactory_.getMethod("getLog", new Class[] {Class.class});
+
+ // get method with String object argument
+ oac_LogFactoryGetLog_String_ = oac_LogFactory_.getMethod("getLog", new Class[] {String.class});
+
+ // get the Log methods
+ final String str[][]={{"debug", "isDebugEnabled"},
+ {"error", "isErrorEnabled"},
+ {"fatal", "isFatalEnabled"},
+ {"info", "isInfoEnabled" },
+ {"trace", "isTraceEnabled"},
+ {"warn", "isWarnEnabled" }};
+ int i=0;
+ for ( ; i<6; i++)
+ {
+ final int j=i*3;
+ meths[j ]=logClass.getMethod(str[i][0], new Class[] {Object.class});
+
+ meths[j+1]=logClass.getMethod(str[i][0], new Class[] {Object.class, Throwable.class});
+
+ meths[j+2]=logClass.getMethod(str[i][1], new Class[] {} );
+
+ }
+ }
+
+ catch (final ClassNotFoundException e)// o.k., so we do not use org.apache.commons.logging in this run
+ {
+ if (iDebug>1) {
+ e.printStackTrace();
+ }
+ oac_LogFactory_=null; // make sure it does not get used
+ oac_LogFactoryGetLog_String_=null; // make sure it does not get used
+ }
+ catch (final NoSuchMethodException e)// o.k., so we do not use org.apache.commons.logging in this run
+ {
+ if (iDebug>1) {
+ e.printStackTrace();
+ }
+ oac_LogFactory_=null; // make sure it does not get used
+ oac_LogFactoryGetLog_String_=null; // make sure it does not get used
+ }
+
+ // Set up final fields
+ oac_LogFactory = oac_LogFactory_;
+ //NOTUSED oac_LogFactoryGetLog_Clazz = oac_LogFactoryGetLog_Clazz_;
+ oac_LogFactoryGetLog_String = oac_LogFactoryGetLog_String_;
+ }
+
+
+ /** Name of the BSF_Log instance. */
+ final String name;
+
+ /** Proxy object for <em>org.apache.commons.logging.Log</em>, if available. */
+ private final Object oac_logger;
+
+
+ public BSF_Log()
+ {
+ this("<?>");
+ }
+
+ public BSF_Log(final String name)
+ {
+ Object oac_logger_ = null;
+ this.name=name;
+ if (oac_LogFactory!=null)
+ {
+ try // try to get an org.apache.commons.logging.Log object from the LogFactory
+ {
+ oac_logger_=oac_LogFactoryGetLog_String.invoke(oac_LogFactory, new Object[] {name});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+ oac_logger = oac_logger_;
+ }
+
+ public BSF_Log(final Class clazz)
+ {
+ this(clazz.getName());
+ }
+
+ public void debug(final Object msg)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).debug(msg);
+ meths[debug1].invoke(oac_logger, new Object [] {msg});
+
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+ public void debug(final Object msg, final Throwable t)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).debug(msg, t);
+ meths[debug2].invoke(oac_logger, new Object [] {msg, t});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+ public void error(final Object msg)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).error(msg);
+ meths[error1].invoke(oac_logger, new Object [] {msg});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+ public void error(final Object msg, final Throwable t)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).error(msg, t);
+ meths[error2].invoke(oac_logger, new Object [] {msg, t});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+
+ public void fatal(final Object msg)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).fatal(msg);
+ meths[fatal1].invoke(oac_logger, new Object [] {msg});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+ public void fatal(final Object msg, final Throwable t)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).fatal(msg, t);
+ meths[fatal2].invoke(oac_logger, new Object [] {msg, t});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+
+ public void info (final Object msg)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).info(msg);
+ meths[info1].invoke(oac_logger, new Object [] {msg});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+ public void info (final Object msg, final Throwable t)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).info(msg, t);
+ meths[info2].invoke(oac_logger, new Object [] {msg, t});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+
+ public void trace(final Object msg)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).trace(msg);
+ meths[trace1].invoke(oac_logger, new Object [] {msg});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+ public void trace(final Object msg, final Throwable t)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).trace(msg, t);
+ meths[trace2].invoke(oac_logger, new Object [] {msg, t});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+
+ public void warn (final Object msg)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).warn(msg);
+ meths[warn1].invoke(oac_logger, new Object [] {msg});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+ public void warn (final Object msg, final Throwable t)
+ {
+ if (oac_logger==null)
+ {
+ return; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // ((org.apache.commons.logging.Log) oac_logger).warn(msg, t);
+ meths[warn2].invoke(oac_logger, new Object [] {msg, t});
+ }
+ catch (final Exception e) { e.printStackTrace(); }
+ }
+
+
+ public boolean isDebugEnabled()
+ {
+ if (oac_logger==null) {return false;} // no org.apache.commons.logging.Log object ?
+
+ try
+ {
+ // return ((org.apache.commons.logging.Log) oac_logger).isDebugEnabled();
+ return ((Boolean) meths[isDebugEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
+ }
+ catch (final Exception e) { }
+ finally { return false; }
+ }
+
+ public boolean isErrorEnabled()
+ {
+ if (oac_logger==null)
+ {
+ return false; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // return ((org.apache.commons.logging.Log) oac_logger).isErrorEnabled();
+ return ((Boolean) meths[isErrorEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
+ }
+ catch (final Exception e) { }
+ finally { return false; }
+ }
+
+ public boolean isFatalEnabled()
+ {
+ if (oac_logger==null)
+ {
+ return false; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // return ((org.apache.commons.logging.Log) oac_logger).isFatalEnabled();
+ return ((Boolean) meths[isFatalEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
+ }
+ catch (final Exception e) { }
+ finally { return false; }
+ }
+
+ public boolean isInfoEnabled ()
+ {
+ if (oac_logger==null)
+ {
+ return false; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // return ((org.apache.commons.logging.Log) oac_logger).isInfoEnabled();
+ return ((Boolean) meths[isInfoEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
+ }
+ catch (final Exception e) { }
+ finally { return false; }
+ }
+
+ public boolean isTraceEnabled()
+ {
+ if (oac_logger==null)
+ {
+ return false; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // return ((org.apache.commons.logging.Log) oac_logger).isTraceEnabled();
+ return ((Boolean) meths[isTraceEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
+ }
+ catch (final Exception e) { }
+ finally { return false; }
+ }
+
+ public boolean isWarnEnabled ()
+ {
+ if (oac_logger==null)
+ {
+ return false; // no org.apache.commons.logging.Log object ?
+ }
+
+ try
+ {
+ // return ((org.apache.commons.logging.Log) oac_logger).isWarnEnabled();
+ return ((Boolean) meths[isWarnEnabled].invoke(oac_logger, new Object [] {})).booleanValue();
+ }
+ catch (final Exception e) { }
+ finally { return false; }
+ }
+
+
+ // for development purposes only (to debug this class on its own)
+ public static void main (final String args[]) {
+ System.out.println("in BSF_Log ...");
+ System.out.println("--------------------------------------------------------");
+ System.out.println("--------------------------------------------------------");
+ BSF_Log bl=new BSF_Log();
+ dump(bl);
+ bl=new BSF_Log(Class.class);
+ dump(bl);
+ bl=new BSF_Log("Rony was here...");
+ dump(bl);
+
+ }
+
+ static void dump(final BSF_Log bl)
+ {
+ System.out.println("\n\tbl=["+bl+"] --->>> --->>> --->>>");
+ System.err.print("/debug **/"); bl.debug("debug message. "); System.err.println("\\** debug.\\");
+ System.err.print("/error **/"); bl.error("error message. "); System.err.println("\\** error.\\");
+ System.err.print("/fatal **/"); bl.fatal("fatal message. "); System.err.println("\\** fatal.\\");
+ System.err.print("/info **/"); bl.info ("info message. "); System.err.println("\\** info .\\");
+ System.err.print("/trace **/"); bl.trace("trace message. "); System.err.println("\\** trace.\\");
+ System.err.print("/warn **/"); bl.warn ("warn message. "); System.err.println("\\** warn .\\");
+ System.err.println();
+
+ final Throwable t=new Throwable ("Test from Rony for: "+bl);
+ System.err.print("/debug **/"); bl.debug("debug message. ", t); System.err.println("\\** debug.\\");
+ System.err.print("/error **/"); bl.error("error message. ", t); System.err.println("\\** error.\\");
+ System.err.print("/fatal **/"); bl.fatal("fatal message. ", t); System.err.println("\\** fatal.\\");
+ System.err.print("/info **/"); bl.info ("info message. ", t); System.err.println("\\** info .\\");
+ System.err.print("/trace **/"); bl.trace("trace message. ", t); System.err.println("\\** trace.\\");
+ System.err.print("/warn **/"); bl.warn ("warn message. ", t); System.err.println("\\** warn .\\");
+ System.err.println();
+
+ System.out.println("\tisDebugEnabled: "+bl.isDebugEnabled());
+ System.out.println("\tisErrorEnabled: "+bl.isErrorEnabled());
+ System.out.println("\tisFatalEnabled: "+bl.isFatalEnabled());
+ System.out.println("\tisInfo Enabled: "+bl.isInfoEnabled());
+ System.out.println("\tisTraceEnabled: "+bl.isTraceEnabled());
+ System.out.println("\tisWarn Enabled: "+bl.isWarnEnabled());
+
+ System.out.println("\tbl=["+bl+"] <<<--- <<<--- <<<---");
+ System.out.println("--------------------------------------------------------");
+ }
+}
+
diff --git a/src/main/java/org/apache/bsf/BSF_LogFactory.java b/src/main/java/org/apache/bsf/BSF_LogFactory.java
index 42381df..638efe9 100644
--- a/src/main/java/org/apache/bsf/BSF_LogFactory.java
+++ b/src/main/java/org/apache/bsf/BSF_LogFactory.java
@@ -1,45 +1,43 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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;
-
-/** This class is used in BSF as BSF_LogFactory returning a BSF_Log instance, which is
- * a delegator for an <code>org.apache.commons.logging.Log</code> object.
- *
- It implements the static <code>org.apache.commons.logging.LogFactory.getLog({String|Class} object)</code>
- * methods which return an instance of the class <code>org.apache.bsf.BSF_Log</code>, which in
- * turn implements all the methods of the <code>org.apache.commons.logging.Log</code> interface class.
- *
-
- @author Rony G. Flatscher, 2006-12-08
-*/
-
-public class BSF_LogFactory
-{
- protected BSF_LogFactory() {} // mimickries org.apache.commons.logging.LogFactory
-
- static public BSF_Log getLog (final String name)
- {
- return new BSF_Log(name);
- }
-
- static public BSF_Log getLog (final Class clz)
- {
- return new BSF_Log(clz);
- }
-}
-
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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;
+
+/** This class is used in BSF as BSF_LogFactory returning a BSF_Log instance, which is
+ * a delegator for an <code>org.apache.commons.logging.Log</code> object.
+ *
+ It implements the static <code>org.apache.commons.logging.LogFactory.getLog({String|Class} object)</code>
+ * methods which return an instance of the class <code>org.apache.bsf.BSF_Log</code>, which in
+ * turn implements all the methods of the <code>org.apache.commons.logging.Log</code> interface class.
+ *
+*/
+
+public class BSF_LogFactory
+{
+ protected BSF_LogFactory() {} // mimickries org.apache.commons.logging.LogFactory
+
+ static public BSF_Log getLog (final String name)
+ {
+ return new BSF_Log(name);
+ }
+
+ static public BSF_Log getLog (final Class clz)
+ {
+ return new BSF_Log(clz);
+ }
+}
+
diff --git a/src/main/java/org/apache/bsf/Main.java b/src/main/java/org/apache/bsf/Main.java
index d7b4ec0..01505fe 100644
--- a/src/main/java/org/apache/bsf/Main.java
+++ b/src/main/java/org/apache/bsf/Main.java
@@ -1,189 +1,185 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.awt.Frame;
-import java.awt.event.WindowAdapter;
-import java.awt.event.WindowEvent;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
-import java.io.Reader;
-import java.util.Hashtable;
-
-import org.apache.bsf.util.CodeBuffer;
-import org.apache.bsf.util.IOUtils;
-
-/**
- * This is the main driver for BSF to be run on the command line
- * to eval/exec/compile scripts directly.
- *
- * @author Sanjiva Weerawarana
- * @author Matthew J. Duftler
- * @author Sam Ruby
- */
-public class Main {
- private static final String ARG_IN = "-in";
- private static final String ARG_LANG = "-lang";
- private static final String ARG_MODE = "-mode";
- private static final String ARG_OUT = "-out";
- private static final String ARG_VAL_EVAL = "eval";
- private static final String ARG_VAL_EXEC = "exec";
- private static final String ARG_VAL_COMPILE = "compile";
- private static final String DEFAULT_IN_FILE_NAME = "<STDIN>";
- private static final String DEFAULT_MODE = ARG_VAL_EVAL;
- private static final String DEFAULT_CLASS_NAME = "Test";
-
- /**
- * Static driver to be able to run BSF scripts from the command line.
- *
- * @param args command line arguments
- *
- * @exception IOException if any I/O error while loading script
- */
- public static void main(final String[] args) throws IOException {
- try {
- if ((args.length == 0) || (args.length % 2 != 0)) {
- printHelp();
- System.exit(1);
- }
-
- final Hashtable argsTable = new Hashtable();
-
- argsTable.put(ARG_OUT, DEFAULT_CLASS_NAME);
- argsTable.put(ARG_MODE, DEFAULT_MODE);
-
- for (int i = 0; i < args.length; i += 2) {
- argsTable.put(args[i], args[i + 1]);
- }
-
- String inFileName = (String) argsTable.get(ARG_IN);
- String language = (String) argsTable.get(ARG_LANG);
-
- if (language == null) {
- if (inFileName != null) {
- language = BSFManager.getLangFromFilename(inFileName);
- } else {
- throw new BSFException(
- BSFException.REASON_OTHER_ERROR,
- "unable to determine language");
- }
- }
-
- Reader in;
-
- if (inFileName != null) {
- in = new FileReader(inFileName);
- } else {
- in = new InputStreamReader(System.in);
- inFileName = DEFAULT_IN_FILE_NAME;
- }
-
- final BSFManager mgr = new BSFManager();
- final String mode = (String) argsTable.get(ARG_MODE);
-
- if (mode.equals(ARG_VAL_COMPILE)) {
- final String outClassName = (String) argsTable.get(ARG_OUT);
- final FileWriter out = new FileWriter(outClassName + ".java");
- final PrintWriter pw = new PrintWriter(out);
-
- final CodeBuffer cb = new CodeBuffer();
- cb.setClassName(outClassName);
- mgr.compileScript(
- language,
- inFileName,
- 0,
- 0,
- IOUtils.getStringFromReader(in),
- cb);
- cb.print(pw, true);
- out.close();
- } else {
- if (mode.equals(ARG_VAL_EXEC)) {
- mgr.exec(language, inFileName, 0, 0, IOUtils.getStringFromReader(in));
- } else { /* eval */
- final Object obj = mgr.eval(language, inFileName, 0, 0, IOUtils.getStringFromReader(in));
-
-
- // Try to display the result.
-
- if (obj instanceof java.awt.Component) {
- Frame f;
- if (obj instanceof Frame) {
- f = (Frame) obj;
- } else {
- f = new Frame ("BSF Result: " + inFileName);
- f.add ((java.awt.Component) obj);
- }
- // Add a window listener to quit on closing.
- f.addWindowListener(
- new WindowAdapter () {
- public void windowClosing (final WindowEvent e) {
- System.exit (0);
- }
- }
- );
- f.pack ();
- // f.show(); // javac 1.5 warns to use f.show(), Apache build scripts abort as a result :(
- f.setVisible(true); // available since Java 1.1
- } else {
- System.err.println("Result: " + obj);
-
- }
-
- System.err.println("Result: " + obj);
- }
- }
- } catch (final BSFException e) {
- e.printStackTrace();
- }
- }
-
- private static void printHelp() {
- System.err.println("Usage:");
- System.err.println();
- System.err.println(" java " + Main.class.getName() + " [args]");
- System.err.println();
- System.err.println(" args:");
- System.err.println();
- System.err.println(
- " [-in fileName] default: " + DEFAULT_IN_FILE_NAME);
- System.err.println(
- " [-lang languageName] default: "
- + "<If -in is specified and -lang");
- System.err.println(
- " "
- + " is not, attempt to determine");
- System.err.println(
- " "
- + " language from file extension;");
- System.err.println(
- " "
- + " otherwise, -lang is required.>");
- System.err.println(
- " [-mode (eval|exec|compile)] default: " + DEFAULT_MODE);
- System.err.println();
- System.err.println(
- " Additional args used only if -mode is " + "set to \"compile\":");
- System.err.println();
- System.err.println(
- " [-out className] default: " + DEFAULT_CLASS_NAME);
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.awt.Frame;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.io.Reader;
+import java.util.Hashtable;
+
+import org.apache.bsf.util.CodeBuffer;
+import org.apache.bsf.util.IOUtils;
+
+/**
+ * This is the main driver for BSF to be run on the command line
+ * to eval/exec/compile scripts directly.
+ */
+public class Main {
+ private static final String ARG_IN = "-in";
+ private static final String ARG_LANG = "-lang";
+ private static final String ARG_MODE = "-mode";
+ private static final String ARG_OUT = "-out";
+ private static final String ARG_VAL_EVAL = "eval";
+ private static final String ARG_VAL_EXEC = "exec";
+ private static final String ARG_VAL_COMPILE = "compile";
+ private static final String DEFAULT_IN_FILE_NAME = "<STDIN>";
+ private static final String DEFAULT_MODE = ARG_VAL_EVAL;
+ private static final String DEFAULT_CLASS_NAME = "Test";
+
+ /**
+ * Static driver to be able to run BSF scripts from the command line.
+ *
+ * @param args command line arguments
+ *
+ * @exception IOException if any I/O error while loading script
+ */
+ public static void main(final String[] args) throws IOException {
+ try {
+ if ((args.length == 0) || (args.length % 2 != 0)) {
+ printHelp();
+ System.exit(1);
+ }
+
+ final Hashtable argsTable = new Hashtable();
+
+ argsTable.put(ARG_OUT, DEFAULT_CLASS_NAME);
+ argsTable.put(ARG_MODE, DEFAULT_MODE);
+
+ for (int i = 0; i < args.length; i += 2) {
+ argsTable.put(args[i], args[i + 1]);
+ }
+
+ String inFileName = (String) argsTable.get(ARG_IN);
+ String language = (String) argsTable.get(ARG_LANG);
+
+ if (language == null) {
+ if (inFileName != null) {
+ language = BSFManager.getLangFromFilename(inFileName);
+ } else {
+ throw new BSFException(
+ BSFException.REASON_OTHER_ERROR,
+ "unable to determine language");
+ }
+ }
+
+ Reader in;
+
+ if (inFileName != null) {
+ in = new FileReader(inFileName);
+ } else {
+ in = new InputStreamReader(System.in);
+ inFileName = DEFAULT_IN_FILE_NAME;
+ }
+
+ final BSFManager mgr = new BSFManager();
+ final String mode = (String) argsTable.get(ARG_MODE);
+
+ if (mode.equals(ARG_VAL_COMPILE)) {
+ final String outClassName = (String) argsTable.get(ARG_OUT);
+ final FileWriter out = new FileWriter(outClassName + ".java");
+ final PrintWriter pw = new PrintWriter(out);
+
+ final CodeBuffer cb = new CodeBuffer();
+ cb.setClassName(outClassName);
+ mgr.compileScript(
+ language,
+ inFileName,
+ 0,
+ 0,
+ IOUtils.getStringFromReader(in),
+ cb);
+ cb.print(pw, true);
+ out.close();
+ } else {
+ if (mode.equals(ARG_VAL_EXEC)) {
+ mgr.exec(language, inFileName, 0, 0, IOUtils.getStringFromReader(in));
+ } else { /* eval */
+ final Object obj = mgr.eval(language, inFileName, 0, 0, IOUtils.getStringFromReader(in));
+
+
+ // Try to display the result.
+
+ if (obj instanceof java.awt.Component) {
+ Frame f;
+ if (obj instanceof Frame) {
+ f = (Frame) obj;
+ } else {
+ f = new Frame ("BSF Result: " + inFileName);
+ f.add ((java.awt.Component) obj);
+ }
+ // Add a window listener to quit on closing.
+ f.addWindowListener(
+ new WindowAdapter () {
+ public void windowClosing (final WindowEvent e) {
+ System.exit (0);
+ }
+ }
+ );
+ f.pack ();
+ // f.show(); // javac 1.5 warns to use f.show(), Apache build scripts abort as a result :(
+ f.setVisible(true); // available since Java 1.1
+ } else {
+ System.err.println("Result: " + obj);
+
+ }
+
+ System.err.println("Result: " + obj);
+ }
+ }
+ } catch (final BSFException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static void printHelp() {
+ System.err.println("Usage:");
+ System.err.println();
+ System.err.println(" java " + Main.class.getName() + " [args]");
+ System.err.println();
+ System.err.println(" args:");
+ System.err.println();
+ System.err.println(
+ " [-in fileName] default: " + DEFAULT_IN_FILE_NAME);
+ System.err.println(
+ " [-lang languageName] default: "
+ + "<If -in is specified and -lang");
+ System.err.println(
+ " "
+ + " is not, attempt to determine");
+ System.err.println(
+ " "
+ + " language from file extension;");
+ System.err.println(
+ " "
+ + " otherwise, -lang is required.>");
+ System.err.println(
+ " [-mode (eval|exec|compile)] default: " + DEFAULT_MODE);
+ System.err.println();
+ System.err.println(
+ " Additional args used only if -mode is " + "set to \"compile\":");
+ System.err.println();
+ System.err.println(
+ " [-out className] default: " + DEFAULT_CLASS_NAME);
+ }
+}
diff --git a/src/main/java/org/apache/bsf/engines/jacl/JaclEngine.java b/src/main/java/org/apache/bsf/engines/jacl/JaclEngine.java
index e1e3e5a..29faa2e 100644
--- a/src/main/java/org/apache/bsf/engines/jacl/JaclEngine.java
+++ b/src/main/java/org/apache/bsf/engines/jacl/JaclEngine.java
@@ -1,141 +1,139 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.engines.jacl;
-
-import java.util.Vector;
-
-import org.apache.bsf.BSFDeclaredBean;
-import org.apache.bsf.BSFException;
-import org.apache.bsf.BSFManager;
-import org.apache.bsf.util.BSFEngineImpl;
-
-import tcl.lang.Interp;
-import tcl.lang.ReflectObject;
-import tcl.lang.TclDouble;
-import tcl.lang.TclException;
-import tcl.lang.TclInteger;
-import tcl.lang.TclObject;
-import tcl.lang.TclString;
-
-/**
- * This is the interface to Scriptics's Jacl (Tcl) from the
- * Bean Scripting Framework.
- * <p>
- *
- * @author Sanjiva Weerawarana
- */
-
-public class JaclEngine extends BSFEngineImpl {
- /* the Jacl interpretor object */
- private Interp interp;
-
- /**
- *
- * @param method The name of the method to call.
- * @param args an array of arguments to be
- * passed to the extension, which may be either
- * Vectors of Nodes, or Strings.
- */
- public Object call (final Object obj, final String method, final Object[] args)
- throws BSFException {
- final StringBuffer tclScript = new StringBuffer (method);
- if (args != null) {
- for( int i = 0 ; i < args.length ; i++ ) {
- tclScript.append (" ");
- tclScript.append (args[i].toString ());
- }
- }
- return eval ("<function call>", 0, 0, tclScript.toString ());
- }
- /**
- * Declare a bean
- */
- public void declareBean (final BSFDeclaredBean bean) throws BSFException {
- final String expr = "set " + bean.name + " [bsf lookupBean \"" + bean.name +
- "\"]";
- eval ("<declare bean>", 0, 0, expr);
- }
- /**
- * This is used by an application to evaluate a string containing
- * some expression.
- */
- public Object eval (final String source, final int lineNo, final int columnNo,
- final Object oscript) throws BSFException {
- final String script = oscript.toString ();
- try {
- interp.eval (script);
- final TclObject result = interp.getResult();
- final Object internalRep = result.getInternalRep();
-
- // if the object has a corresponding Java type, unwrap it
- if (internalRep instanceof ReflectObject) {
- return ReflectObject.get(interp,result);
- }
- if (internalRep instanceof TclString) {
- return result.toString();
- }
- if (internalRep instanceof TclDouble) {
- return new Double(TclDouble.get(interp,result));
- }
- if (internalRep instanceof TclInteger) {
- return new Integer(TclInteger.get(interp,result));
- }
-
- return result;
- } catch (final TclException e) {
- throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
- "error while eval'ing Jacl expression: " +
- interp.getResult (), e);
- }
- }
- /**
- * Initialize the engine.
- */
- public void initialize (final BSFManager mgr, final String lang,
- final Vector declaredBeans) throws BSFException {
- super.initialize (mgr, lang, declaredBeans);
-
- // create interpreter
- interp = new Interp();
-
- // register the extension that user's can use to get at objects
- // registered by the app
- interp.createCommand ("bsf", new BSFCommand (mgr, this));
-
- // Make java functions be available to Jacl
- try {
- interp.eval("jaclloadjava");
- } catch (final TclException e) {
- throw new BSFException (BSFException.REASON_OTHER_ERROR,
- "error while loading java package: " +
- interp.getResult (), e);
- }
-
- final int size = declaredBeans.size ();
- for (int i = 0; i < size; i++) {
- declareBean ((BSFDeclaredBean) declaredBeans.elementAt (i));
- }
- }
-
- /**
- * Undeclare a previously declared bean.
- */
- public void undeclareBean (final BSFDeclaredBean bean) throws BSFException {
- eval ("<undeclare bean>", 0, 0, "set " + bean.name + " \"\"");
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.engines.jacl;
+
+import java.util.Vector;
+
+import org.apache.bsf.BSFDeclaredBean;
+import org.apache.bsf.BSFException;
+import org.apache.bsf.BSFManager;
+import org.apache.bsf.util.BSFEngineImpl;
+
+import tcl.lang.Interp;
+import tcl.lang.ReflectObject;
+import tcl.lang.TclDouble;
+import tcl.lang.TclException;
+import tcl.lang.TclInteger;
+import tcl.lang.TclObject;
+import tcl.lang.TclString;
+
+/**
+ * This is the interface to Scriptics's Jacl (Tcl) from the
+ * Bean Scripting Framework.
+ * <p>
+ */
+
+public class JaclEngine extends BSFEngineImpl {
+ /* the Jacl interpretor object */
+ private Interp interp;
+
+ /**
+ *
+ * @param method The name of the method to call.
+ * @param args an array of arguments to be
+ * passed to the extension, which may be either
+ * Vectors of Nodes, or Strings.
+ */
+ public Object call (final Object obj, final String method, final Object[] args)
+ throws BSFException {
+ final StringBuffer tclScript = new StringBuffer (method);
+ if (args != null) {
+ for( int i = 0 ; i < args.length ; i++ ) {
+ tclScript.append (" ");
+ tclScript.append (args[i].toString ());
+ }
+ }
+ return eval ("<function call>", 0, 0, tclScript.toString ());
+ }
+ /**
+ * Declare a bean
+ */
+ public void declareBean (final BSFDeclaredBean bean) throws BSFException {
+ final String expr = "set " + bean.name + " [bsf lookupBean \"" + bean.name +
+ "\"]";
+ eval ("<declare bean>", 0, 0, expr);
+ }
+ /**
+ * This is used by an application to evaluate a string containing
+ * some expression.
+ */
+ public Object eval (final String source, final int lineNo, final int columnNo,
+ final Object oscript) throws BSFException {
+ final String script = oscript.toString ();
+ try {
+ interp.eval (script);
+ final TclObject result = interp.getResult();
+ final Object internalRep = result.getInternalRep();
+
+ // if the object has a corresponding Java type, unwrap it
+ if (internalRep instanceof ReflectObject) {
+ return ReflectObject.get(interp,result);
+ }
+ if (internalRep instanceof TclString) {
+ return result.toString();
+ }
+ if (internalRep instanceof TclDouble) {
+ return new Double(TclDouble.get(interp,result));
+ }
+ if (internalRep instanceof TclInteger) {
+ return new Integer(TclInteger.get(interp,result));
+ }
+
+ return result;
+ } catch (final TclException e) {
+ throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
+ "error while eval'ing Jacl expression: " +
+ interp.getResult (), e);
+ }
+ }
+ /**
+ * Initialize the engine.
+ */
+ public void initialize (final BSFManager mgr, final String lang,
+ final Vector declaredBeans) throws BSFException {
+ super.initialize (mgr, lang, declaredBeans);
+
+ // create interpreter
+ interp = new Interp();
+
+ // register the extension that user's can use to get at objects
+ // registered by the app
+ interp.createCommand ("bsf", new BSFCommand (mgr, this));
+
+ // Make java functions be available to Jacl
+ try {
+ interp.eval("jaclloadjava");
+ } catch (final TclException e) {
+ throw new BSFException (BSFException.REASON_OTHER_ERROR,
+ "error while loading java package: " +
+ interp.getResult (), e);
+ }
+
+ final int size = declaredBeans.size ();
+ for (int i = 0; i < size; i++) {
+ declareBean ((BSFDeclaredBean) declaredBeans.elementAt (i));
+ }
+ }
+
+ /**
+ * Undeclare a previously declared bean.
+ */
+ public void undeclareBean (final BSFDeclaredBean bean) throws BSFException {
+ eval ("<undeclare bean>", 0, 0, "set " + bean.name + " \"\"");
+ }
+}
diff --git a/src/main/java/org/apache/bsf/engines/java/JavaEngine.java b/src/main/java/org/apache/bsf/engines/java/JavaEngine.java
index 3fb8b82..c487d1f 100644
--- a/src/main/java/org/apache/bsf/engines/java/JavaEngine.java
+++ b/src/main/java/org/apache/bsf/engines/java/JavaEngine.java
@@ -1,358 +1,356 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.engines.java;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FilenameFilter;
-import java.lang.reflect.Method;
-import java.util.Hashtable;
-import java.util.Vector;
-
-import org.apache.bsf.BSFException;
-import org.apache.bsf.BSFManager;
-import org.apache.bsf.BSF_Log;
-import org.apache.bsf.BSF_LogFactory;
-
-import org.apache.bsf.util.BSFEngineImpl;
-import org.apache.bsf.util.CodeBuffer;
-import org.apache.bsf.util.EngineUtils;
-import org.apache.bsf.util.JavaUtils;
-import org.apache.bsf.util.MethodUtils;
-import org.apache.bsf.util.ObjInfo;
-
-/**
- * This is the interface to Java from the
- * Bean Scripting Framework.
- * <p>
- * The Java code must be written script-style -- that is, just the body of
- * the function, without class or method headers or footers.
- * The JavaEngine will generate those via a "boilerplate" wrapper:
- * <pre>
- * <code>
- * import java.lang.*;
- * import java.util.*;
- * public class $$CLASSNAME$$ {
- * static public Object BSFJavaEngineEntry(org.apache.bsf.BSFManager bsf) {
- * // Your code will be placed here
- * }
- * }
- * </code>
- * </pre>
- * $$CLASSNAME$$ will be replaced by a generated classname of the form
- * BSFJava*, and the bsf parameter can be used to retrieve application
- * objects registered with the Bean Scripting Framework.
- * <p>
- * If you use the placeholder string $$CLASSNAME$$ elsewhere
- * in your script -- including within text strings -- BSFJavaEngine will
- * replace it with the generated name of the class before the Java code
- * is compiled.
- * <p>
- * <h2>Hazards:</h2>
- * <p>
- * NOTE that it is your responsibility to convert the code into an acceptable
- * Java string. If you're invoking the JavaEngine directly (as in the
- * JSPLikeInJava example) that means \"quoting\" characters that would
- * otherwise cause trouble.
- * <p>
- * ALSO NOTE that it is your responsibility to return an object, or null in
- * lieu thereof!
- * <p>
- * Since the code has to be compiled to a Java classfile, invoking it involves
- * a fair amount of computation to load and execute the compiler. We are
- * currently making an attempt to manage that by caching the class
- * after it has been loaded, but the indexing is fairly primitive. It has
- * been suggested that the Bean Scripting Framework may want to support
- * preload-and-name-script and execute-preloaded-script-by-name options to
- * provide better control over when and how much overhead occurs.
- * <p>
- * @author Joe Kesselman
- * @author Rony G. Flatscher (added BSF_Log[Factory] to allow BSF to run without org.apache.commons.logging present)
- */
-public class JavaEngine extends BSFEngineImpl {
- Class javaclass = null;
- static Hashtable codeToClass = new Hashtable();
- static String serializeCompilation = "";
- static String placeholder = "$$CLASSNAME$$";
- String minorPrefix;
-
- // private Log logger = LogFactory.getLog(this.getClass().getName());
- private BSF_Log logger = null;
-
- /**
- * Create a scratchfile, open it for writing, return its name.
- * Relies on the filesystem to provide us with uniqueness testing.
- * NOTE THAT uniqueFileOffset continues to count; we don't want to
- * risk reusing a classname we have previously loaded in this session
- * even if the classfile has been deleted.
- */
- private int uniqueFileOffset = -1;
-
- private class GeneratedFile {
- File file = null;
- FileOutputStream fos = null;
- String className = null;
- GeneratedFile(final File file, final FileOutputStream fos, final String className) {
- this.file = file;
- this.fos = fos;
- this.className = className;
- }
- }
-
- /**
- * Constructor.
- */
- public JavaEngine () {
- // handle logger
- logger = BSF_LogFactory.getLog(this.getClass().getName());
- // Do compilation-possible check here??????????????
- }
-
- public Object call (final Object object, final String method, final Object[] args)
- throws BSFException
- {
- throw new BSFException (BSFException.REASON_UNSUPPORTED_FEATURE,
- "call() is not currently supported by JavaEngine");
- }
-
- public void compileScript (final String source, final int lineNo, final int columnNo,
- final Object script, final CodeBuffer cb) throws BSFException {
- final ObjInfo oldRet = cb.getFinalServiceMethodStatement ();
-
- if (oldRet != null && oldRet.isExecutable ()) {
- cb.addServiceMethodStatement (oldRet.objName + ";");
- }
-
- cb.addServiceMethodStatement (script.toString ());
- cb.setFinalServiceMethodStatement (null);
- }
-
- /**
- * This is used by an application to evaluate a string containing
- * some expression. It should store the "bsf" handle where the
- * script can get to it, for callback purposes.
- * <p>
- * Note that Java compilation imposes serious overhead,
- * but in exchange you get full Java performance
- * once the classes have been created (minus the cache lookup cost).
- * <p>
- * Nobody knows whether javac is threadsafe.
- * I'm going to serialize access to protect it.
- * <p>
- * There is no published API for invoking javac as a class. There's a trick
- * that seems to work for Java 1.1.x, but it stopped working in Java 1.2.
- * We will attempt to use it, then if necessary fall back on invoking
- * javac via the command line.
- */
- public Object eval (final String source, final int lineNo, final int columnNo,
- final Object oscript) throws BSFException
- {
- Object retval = null;
- String classname = null;
- GeneratedFile gf = null;
-
- final String basescript = oscript.toString();
- String script = basescript; // May be altered by $$CLASSNAME$$ expansion
-
- try {
- // Do we already have a class exactly matching this code?
- javaclass = (Class)codeToClass.get(basescript);
-
- if(javaclass != null) {
- classname=javaclass.getName();
- } else {
- gf = openUniqueFile(tempDir, "BSFJava",".java");
- if( gf == null) {
- throw new BSFException("couldn't create JavaEngine scratchfile");
- }
- // Obtain classname
- classname = gf.className;
-
- // Write the kluge header to the file.
- gf.fos.write(("import java.lang.*;"+
- "import java.util.*;"+
- "public class "+classname+" {\n" +
- " static public Object BSFJavaEngineEntry(org.apache.bsf.BSFManager bsf) {\n")
- .getBytes());
-
- // Edit the script to replace placeholder with the generated
- // classname. Note that this occurs _after_ the cache was checked!
- int startpoint = script.indexOf(placeholder);
- int endpoint;
- if(startpoint >= 0) {
- final StringBuffer changed = new StringBuffer();
- for(; startpoint >=0; startpoint = script.indexOf(placeholder,startpoint)) {
- changed.setLength(0); // Reset for 2nd pass or later
- if(startpoint > 0) {
- changed.append(script.substring(0,startpoint));
- }
- changed.append(classname);
- endpoint = startpoint+placeholder.length();
- if(endpoint < script.length()) {
- changed.append(script.substring(endpoint));
- }
- script = changed.toString();
- }
- }
-
- // MJD - debug
-// BSFDeclaredBean tempBean;
-// String className;
-//
-// for (int i = 0; i < declaredBeans.size (); i++) {
-// tempBean = (BSFDeclaredBean) declaredBeans.elementAt (i);
-// className = StringUtils.getClassName (tempBean.bean.getClass ());
-//
-// gf.fos.write ((className + " " +
-// tempBean.name + " = (" + className +
-// ")bsf.lookupBean(\"" +
-// tempBean.name + "\");").getBytes ());
-// }
- // MJD - debug
-
- // Copy the input to the file.
- // Assumes all available -- probably mistake, but same as other engines.
- gf.fos.write(script.getBytes());
- // Close the method and class
- gf.fos.write(("\n }\n}\n").getBytes());
- gf.fos.close();
-
- // Compile through Java to .class file
- // May not be threadsafe. Serialize access on static object:
- synchronized(serializeCompilation) {
- JavaUtils.JDKcompile(gf.file.getPath(), classPath);
- }
-
- // Load class.
- javaclass = EngineUtils.loadClass(mgr, classname);
-
- // Stash class for reuse
- codeToClass.put(basescript, javaclass);
- }
-
- final Object[] callArgs = {mgr};
- retval = internalCall(this,"BSFJavaEngineEntry",callArgs);
- }
-
-
- catch(final Exception e) {
- e.printStackTrace ();
- throw new BSFException (BSFException.REASON_IO_ERROR, e.getMessage ());
- } finally {
- // Cleanup: delete the .java and .class files
-
-// if(gf!=null && gf.file!=null && gf.file.exists())
-// gf.file.delete(); // .java file
-
-
- if(classname!=null) {
- // Generated class
- File file = new File(tempDir+File.separatorChar+classname+".class");
-// if(file.exists())
-// file.delete();
-
- // Search for and clean up minor classes, classname$xxx.class
- file = new File(tempDir); // ***** Is this required?
- minorPrefix = classname+"$"; // Indirect arg to filter
- final String[] minorClassfiles = file.list(new FilenameFilter()
- {
- // Starts with classname$ and ends with .class
- public boolean accept(final File dir,final String name) {
- return
- (0 == name.indexOf(minorPrefix))
- &&
- (name.lastIndexOf(".class") == name.length()-6);
- }
- });
- for(int i = 0; i < minorClassfiles.length; ++i) {
- file = new File(minorClassfiles[i]);
-// file.delete();
- }
- }
- }
- return retval;
- }
-
- public void initialize (final BSFManager mgr, final String lang,
- final Vector declaredBeans) throws BSFException {
- super.initialize (mgr, lang, declaredBeans);
- }
- /**
- * Return an object from an extension.
- * @param object Object on which to make the internal_call (ignored).
- * @param method The name of the method to internal_call.
- * @param args an array of arguments to be
- * passed to the extension, which may be either
- * Vectors of Nodes, or Strings.
- */
- Object internalCall (final Object object, final String method, final Object[] args)
- throws BSFException
- {
- //***** ISSUE: Only static methods are currently supported
- Object retval = null;
- try {
- if(javaclass != null) {
- //***** This should call the lookup used in BML, for typesafety
- final Class[] argtypes = new Class[args.length];
- for(int i=0; i<args.length; ++i) {
- argtypes[i]=args[i].getClass();
- }
- final Method m = MethodUtils.getMethod(javaclass, method, argtypes);
- retval = m.invoke(null, args);
- }
- }
- catch(final Exception e) {
- throw new BSFException (BSFException.REASON_IO_ERROR, e.getMessage ());
- }
- return retval;
- }
-
- private GeneratedFile openUniqueFile(final String directory,final String prefix,final String suffix) {
- File file = null;
- FileOutputStream fos = null;
- final int max = 1000; // Don't try forever
- GeneratedFile gf = null;
- int i;
- String className = null;
- for(i=max,++uniqueFileOffset; fos==null && i>0;--i,++uniqueFileOffset) {
- // Probably a timing hazard here... ***************
- try {
- className = prefix+uniqueFileOffset;
- file = new File(directory+File.separatorChar+className+suffix);
- if(file != null && !file.exists()) {
- fos = new FileOutputStream(file);
- }
- }
- catch(final Exception e) {
- // File could not be opened for write, or Security Exception
- // was thrown. If someone else created the file before we could
- // open it, that's probably a threading conflict and we don't
- // bother reporting it.
- if(!file.exists()) {
- logger.error("openUniqueFile: unexpected ", e);
- }
- }
- }
- if(fos==null) {
- logger.error("openUniqueFile: Failed "+max+"attempts.");
- } else {
- gf = new GeneratedFile(file,fos,className);
- }
- return gf;
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.engines.java;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FilenameFilter;
+import java.lang.reflect.Method;
+import java.util.Hashtable;
+import java.util.Vector;
+
+import org.apache.bsf.BSFException;
+import org.apache.bsf.BSFManager;
+import org.apache.bsf.BSF_Log;
+import org.apache.bsf.BSF_LogFactory;
+
+import org.apache.bsf.util.BSFEngineImpl;
+import org.apache.bsf.util.CodeBuffer;
+import org.apache.bsf.util.EngineUtils;
+import org.apache.bsf.util.JavaUtils;
+import org.apache.bsf.util.MethodUtils;
+import org.apache.bsf.util.ObjInfo;
+
+/**
+ * This is the interface to Java from the
+ * Bean Scripting Framework.
+ * <p>
+ * The Java code must be written script-style -- that is, just the body of
+ * the function, without class or method headers or footers.
+ * The JavaEngine will generate those via a "boilerplate" wrapper:
+ * <pre>
+ * <code>
+ * import java.lang.*;
+ * import java.util.*;
+ * public class $$CLASSNAME$$ {
+ * static public Object BSFJavaEngineEntry(org.apache.bsf.BSFManager bsf) {
+ * // Your code will be placed here
+ * }
+ * }
+ * </code>
+ * </pre>
+ * $$CLASSNAME$$ will be replaced by a generated classname of the form
+ * BSFJava*, and the bsf parameter can be used to retrieve application
+ * objects registered with the Bean Scripting Framework.
+ * <p>
+ * If you use the placeholder string $$CLASSNAME$$ elsewhere
+ * in your script -- including within text strings -- BSFJavaEngine will
+ * replace it with the generated name of the class before the Java code
+ * is compiled.
+ * <p>
+ * <h2>Hazards:</h2>
+ * <p>
+ * NOTE that it is your responsibility to convert the code into an acceptable
+ * Java string. If you're invoking the JavaEngine directly (as in the
+ * JSPLikeInJava example) that means \"quoting\" characters that would
+ * otherwise cause trouble.
+ * <p>
+ * ALSO NOTE that it is your responsibility to return an object, or null in
+ * lieu thereof!
+ * <p>
+ * Since the code has to be compiled to a Java classfile, invoking it involves
+ * a fair amount of computation to load and execute the compiler. We are
+ * currently making an attempt to manage that by caching the class
+ * after it has been loaded, but the indexing is fairly primitive. It has
+ * been suggested that the Bean Scripting Framework may want to support
+ * preload-and-name-script and execute-preloaded-script-by-name options to
+ * provide better control over when and how much overhead occurs.
+ * <p>
+ */
+public class JavaEngine extends BSFEngineImpl {
+ Class javaclass = null;
+ static Hashtable codeToClass = new Hashtable();
+ static String serializeCompilation = "";
+ static String placeholder = "$$CLASSNAME$$";
+ String minorPrefix;
+
+ // private Log logger = LogFactory.getLog(this.getClass().getName());
+ private BSF_Log logger = null;
+
+ /**
+ * Create a scratchfile, open it for writing, return its name.
+ * Relies on the filesystem to provide us with uniqueness testing.
+ * NOTE THAT uniqueFileOffset continues to count; we don't want to
+ * risk reusing a classname we have previously loaded in this session
+ * even if the classfile has been deleted.
+ */
+ private int uniqueFileOffset = -1;
+
+ private class GeneratedFile {
+ File file = null;
+ FileOutputStream fos = null;
+ String className = null;
+ GeneratedFile(final File file, final FileOutputStream fos, final String className) {
+ this.file = file;
+ this.fos = fos;
+ this.className = className;
+ }
+ }
+
+ /**
+ * Constructor.
+ */
+ public JavaEngine () {
+ // handle logger
+ logger = BSF_LogFactory.getLog(this.getClass().getName());
+ // Do compilation-possible check here??????????????
+ }
+
+ public Object call (final Object object, final String method, final Object[] args)
+ throws BSFException
+ {
+ throw new BSFException (BSFException.REASON_UNSUPPORTED_FEATURE,
+ "call() is not currently supported by JavaEngine");
+ }
+
+ public void compileScript (final String source, final int lineNo, final int columnNo,
+ final Object script, final CodeBuffer cb) throws BSFException {
+ final ObjInfo oldRet = cb.getFinalServiceMethodStatement ();
+
+ if (oldRet != null && oldRet.isExecutable ()) {
+ cb.addServiceMethodStatement (oldRet.objName + ";");
+ }
+
+ cb.addServiceMethodStatement (script.toString ());
+ cb.setFinalServiceMethodStatement (null);
+ }
+
+ /**
+ * This is used by an application to evaluate a string containing
+ * some expression. It should store the "bsf" handle where the
+ * script can get to it, for callback purposes.
+ * <p>
+ * Note that Java compilation imposes serious overhead,
+ * but in exchange you get full Java performance
+ * once the classes have been created (minus the cache lookup cost).
+ * <p>
+ * Nobody knows whether javac is threadsafe.
+ * I'm going to serialize access to protect it.
+ * <p>
+ * There is no published API for invoking javac as a class. There's a trick
+ * that seems to work for Java 1.1.x, but it stopped working in Java 1.2.
+ * We will attempt to use it, then if necessary fall back on invoking
+ * javac via the command line.
+ */
+ public Object eval (final String source, final int lineNo, final int columnNo,
+ final Object oscript) throws BSFException
+ {
+ Object retval = null;
+ String classname = null;
+ GeneratedFile gf = null;
+
+ final String basescript = oscript.toString();
+ String script = basescript; // May be altered by $$CLASSNAME$$ expansion
+
+ try {
+ // Do we already have a class exactly matching this code?
+ javaclass = (Class)codeToClass.get(basescript);
+
+ if(javaclass != null) {
+ classname=javaclass.getName();
+ } else {
+ gf = openUniqueFile(tempDir, "BSFJava",".java");
+ if( gf == null) {
+ throw new BSFException("couldn't create JavaEngine scratchfile");
+ }
+ // Obtain classname
+ classname = gf.className;
+
+ // Write the kluge header to the file.
+ gf.fos.write(("import java.lang.*;"+
+ "import java.util.*;"+
+ "public class "+classname+" {\n" +
+ " static public Object BSFJavaEngineEntry(org.apache.bsf.BSFManager bsf) {\n")
+ .getBytes());
+
+ // Edit the script to replace placeholder with the generated
+ // classname. Note that this occurs _after_ the cache was checked!
+ int startpoint = script.indexOf(placeholder);
+ int endpoint;
+ if(startpoint >= 0) {
+ final StringBuffer changed = new StringBuffer();
+ for(; startpoint >=0; startpoint = script.indexOf(placeholder,startpoint)) {
+ changed.setLength(0); // Reset for 2nd pass or later
+ if(startpoint > 0) {
+ changed.append(script.substring(0,startpoint));
+ }
+ changed.append(classname);
+ endpoint = startpoint+placeholder.length();
+ if(endpoint < script.length()) {
+ changed.append(script.substring(endpoint));
+ }
+ script = changed.toString();
+ }
+ }
+
+ // MJD - debug
+// BSFDeclaredBean tempBean;
+// String className;
+//
+// for (int i = 0; i < declaredBeans.size (); i++) {
+// tempBean = (BSFDeclaredBean) declaredBeans.elementAt (i);
+// className = StringUtils.getClassName (tempBean.bean.getClass ());
+//
+// gf.fos.write ((className + " " +
+// tempBean.name + " = (" + className +
+// ")bsf.lookupBean(\"" +
+// tempBean.name + "\");").getBytes ());
+// }
+ // MJD - debug
+
+ // Copy the input to the file.
+ // Assumes all available -- probably mistake, but same as other engines.
+ gf.fos.write(script.getBytes());
+ // Close the method and class
+ gf.fos.write(("\n }\n}\n").getBytes());
+ gf.fos.close();
+
+ // Compile through Java to .class file
+ // May not be threadsafe. Serialize access on static object:
+ synchronized(serializeCompilation) {
+ JavaUtils.JDKcompile(gf.file.getPath(), classPath);
+ }
+
+ // Load class.
+ javaclass = EngineUtils.loadClass(mgr, classname);
+
+ // Stash class for reuse
+ codeToClass.put(basescript, javaclass);
+ }
+
+ final Object[] callArgs = {mgr};
+ retval = internalCall(this,"BSFJavaEngineEntry",callArgs);
+ }
+
+
+ catch(final Exception e) {
+ e.printStackTrace ();
+ throw new BSFException (BSFException.REASON_IO_ERROR, e.getMessage ());
+ } finally {
+ // Cleanup: delete the .java and .class files
+
+// if(gf!=null && gf.file!=null && gf.file.exists())
+// gf.file.delete(); // .java file
+
+
+ if(classname!=null) {
+ // Generated class
+ File file = new File(tempDir+File.separatorChar+classname+".class");
+// if(file.exists())
+// file.delete();
+
+ // Search for and clean up minor classes, classname$xxx.class
+ file = new File(tempDir); // ***** Is this required?
+ minorPrefix = classname+"$"; // Indirect arg to filter
+ final String[] minorClassfiles = file.list(new FilenameFilter()
+ {
+ // Starts with classname$ and ends with .class
+ public boolean accept(final File dir,final String name) {
+ return
+ (0 == name.indexOf(minorPrefix))
+ &&
+ (name.lastIndexOf(".class") == name.length()-6);
+ }
+ });
+ for(int i = 0; i < minorClassfiles.length; ++i) {
+ file = new File(minorClassfiles[i]);
+// file.delete();
+ }
+ }
+ }
+ return retval;
+ }
+
+ public void initialize (final BSFManager mgr, final String lang,
+ final Vector declaredBeans) throws BSFException {
+ super.initialize (mgr, lang, declaredBeans);
+ }
+ /**
+ * Return an object from an extension.
+ * @param object Object on which to make the internal_call (ignored).
+ * @param method The name of the method to internal_call.
+ * @param args an array of arguments to be
+ * passed to the extension, which may be either
+ * Vectors of Nodes, or Strings.
+ */
+ Object internalCall (final Object object, final String method, final Object[] args)
+ throws BSFException
+ {
+ //***** ISSUE: Only static methods are currently supported
+ Object retval = null;
+ try {
+ if(javaclass != null) {
+ //***** This should call the lookup used in BML, for typesafety
+ final Class[] argtypes = new Class[args.length];
+ for(int i=0; i<args.length; ++i) {
+ argtypes[i]=args[i].getClass();
+ }
+ final Method m = MethodUtils.getMethod(javaclass, method, argtypes);
+ retval = m.invoke(null, args);
+ }
+ }
+ catch(final Exception e) {
+ throw new BSFException (BSFException.REASON_IO_ERROR, e.getMessage ());
+ }
+ return retval;
+ }
+
+ private GeneratedFile openUniqueFile(final String directory,final String prefix,final String suffix) {
+ File file = null;
+ FileOutputStream fos = null;
+ final int max = 1000; // Don't try forever
+ GeneratedFile gf = null;
+ int i;
+ String className = null;
+ for(i=max,++uniqueFileOffset; fos==null && i>0;--i,++uniqueFileOffset) {
+ // Probably a timing hazard here... ***************
+ try {
+ className = prefix+uniqueFileOffset;
+ file = new File(directory+File.separatorChar+className+suffix);
+ if(file != null && !file.exists()) {
+ fos = new FileOutputStream(file);
+ }
+ }
+ catch(final Exception e) {
+ // File could not be opened for write, or Security Exception
+ // was thrown. If someone else created the file before we could
+ // open it, that's probably a threading conflict and we don't
+ // bother reporting it.
+ if(!file.exists()) {
+ logger.error("openUniqueFile: unexpected ", e);
+ }
+ }
+ }
+ if(fos==null) {
+ logger.error("openUniqueFile: Failed "+max+"attempts.");
+ } else {
+ gf = new GeneratedFile(file,fos,className);
+ }
+ return gf;
+ }
+}
diff --git a/src/main/java/org/apache/bsf/engines/javaclass/JavaClassEngine.java b/src/main/java/org/apache/bsf/engines/javaclass/JavaClassEngine.java
index 1762cb5..283e9c2 100644
--- a/src/main/java/org/apache/bsf/engines/javaclass/JavaClassEngine.java
+++ b/src/main/java/org/apache/bsf/engines/javaclass/JavaClassEngine.java
@@ -1,74 +1,72 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.engines.javaclass;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-import org.apache.bsf.BSFException;
-import org.apache.bsf.util.BSFEngineImpl;
-import org.apache.bsf.util.MethodUtils;
-
-/**
- * This is the interface to scripts consisting of Java objects from the
- * Bean Scripting Framework.
- *
- * @author Sanjiva Weerawarana
- */
-public class JavaClassEngine extends BSFEngineImpl {
- /**
- * call the named method of the given object. If object is an instance
- * of Class, then the call is a static call on that object. If not, its
- * an instance method call or a static call (as per Java) on the given
- * object.
- */
- public Object call (final Object object, final String method, final Object[] args)
- throws BSFException {
- // determine arg types
- Class[] argTypes = null;
- if (args != null) {
- argTypes = new Class[args.length];
- for (int i = 0; i < args.length; i++) {
- argTypes[i] = (args[i] != null) ? args[i].getClass () : null;
- }
- }
-
- // now find method with the right signature, call it and return result
- try {
- final Method m = MethodUtils.getMethod (object, method, argTypes);
- return m.invoke (object, args);
- } catch (final Exception e) {
- // something went wrong while invoking method
- final Throwable t = (e instanceof InvocationTargetException) ?
- ((InvocationTargetException)e).getTargetException () :
- null;
- throw new BSFException (BSFException.REASON_OTHER_ERROR,
- "method invocation failed: " + e +
- ((t==null)?"":(" target exception: "+t)), t);
- }
- }
- /**
- * This is used by an application to evaluate an object containing
- * some expression - clearly not possible for compiled code ..
- */
- public Object eval (final String source, final int lineNo, final int columnNo,
- final Object oscript) throws BSFException {
- throw new BSFException (BSFException.REASON_UNSUPPORTED_FEATURE,
- "Java bytecode engine can't evaluate expressions");
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.engines.javaclass;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import org.apache.bsf.BSFException;
+import org.apache.bsf.util.BSFEngineImpl;
+import org.apache.bsf.util.MethodUtils;
+
+/**
+ * This is the interface to scripts consisting of Java objects from the
+ * Bean Scripting Framework.
+ */
+public class JavaClassEngine extends BSFEngineImpl {
+ /**
+ * call the named method of the given object. If object is an instance
+ * of Class, then the call is a static call on that object. If not, its
+ * an instance method call or a static call (as per Java) on the given
+ * object.
+ */
+ public Object call (final Object object, final String method, final Object[] args)
+ throws BSFException {
+ // determine arg types
+ Class[] argTypes = null;
+ if (args != null) {
+ argTypes = new Class[args.length];
+ for (int i = 0; i < args.length; i++) {
+ argTypes[i] = (args[i] != null) ? args[i].getClass () : null;
+ }
+ }
+
+ // now find method with the right signature, call it and return result
+ try {
+ final Method m = MethodUtils.getMethod (object, method, argTypes);
+ return m.invoke (object, args);
+ } catch (final Exception e) {
+ // something went wrong while invoking method
+ final Throwable t = (e instanceof InvocationTargetException) ?
+ ((InvocationTargetException)e).getTargetException () :
+ null;
+ throw new BSFException (BSFException.REASON_OTHER_ERROR,
+ "method invocation failed: " + e +
+ ((t==null)?"":(" target exception: "+t)), t);
+ }
+ }
+ /**
+ * This is used by an application to evaluate an object containing
+ * some expression - clearly not possible for compiled code ..
+ */
+ public Object eval (final String source, final int lineNo, final int columnNo,
+ final Object oscript) throws BSFException {
+ throw new BSFException (BSFException.REASON_UNSUPPORTED_FEATURE,
+ "Java bytecode engine can't evaluate expressions");
+ }
+}
diff --git a/src/main/java/org/apache/bsf/engines/javascript/JavaScriptEngine.java b/src/main/java/org/apache/bsf/engines/javascript/JavaScriptEngine.java
index 792cf40..da4a3ad 100644
--- a/src/main/java/org/apache/bsf/engines/javascript/JavaScriptEngine.java
+++ b/src/main/java/org/apache/bsf/engines/javascript/JavaScriptEngine.java
@@ -1,239 +1,234 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.engines.javascript;
-
-import java.util.Iterator;
-import java.util.Vector;
-
-import org.apache.bsf.BSFDeclaredBean;
-import org.apache.bsf.BSFException;
-import org.apache.bsf.BSFManager;
-import org.apache.bsf.util.BSFEngineImpl;
-import org.apache.bsf.util.BSFFunctions;
-import org.mozilla.javascript.Context;
-import org.mozilla.javascript.EvaluatorException;
-import org.mozilla.javascript.Function;
-import org.mozilla.javascript.ImporterTopLevel;
-import org.mozilla.javascript.JavaScriptException;
-import org.mozilla.javascript.NativeJavaObject;
-import org.mozilla.javascript.Scriptable;
-import org.mozilla.javascript.WrappedException;
-import org.mozilla.javascript.Wrapper;
-
-/**
- * This is the interface to Netscape's Rhino (JavaScript) from the
- * Bean Scripting Framework.
- * <p>
- * The original version of this code was first written by Adam Peller
- * for use in LotusXSL. Sanjiva took his code and adapted it for BSF.
- *
- * @author Adam Peller <pe...@lotus.com>
- * @author Sanjiva Weerawarana
- * @author Matthew J. Duftler
- * @author Norris Boyd
- */
-public class JavaScriptEngine extends BSFEngineImpl {
- /**
- * The global script object, where all embedded functions are defined,
- * as well as the standard ECMA "core" objects.
- */
- private Scriptable global;
-
- /**
- * Return an object from an extension.
- * @param object Object on which to make the call (ignored).
- * @param method The name of the method to call.
- * @param args an array of arguments to be
- * passed to the extension, which may be either
- * Vectors of Nodes, or Strings.
- */
- public Object call(final Object object, final String method, final Object[] args)
- throws BSFException {
-
- Object retval = null;
- Context cx;
-
- try {
- cx = Context.enter();
-
- // REMIND: convert arg list Vectors here?
-
- final Object fun = global.get(method, global);
- // NOTE: Source and line arguments are nonsense in a call().
- // Any way to make these arguments *sensible?
- if (fun == Scriptable.NOT_FOUND) {
- throw new EvaluatorException("function " + method +
- " not found.", "none", 0);
- }
-
- cx.setOptimizationLevel(-1);
- cx.setGeneratingDebug(false);
- cx.setGeneratingSource(false);
- cx.setOptimizationLevel(0);
- cx.setDebugger(null, null);
-
- retval =
- ((Function) fun).call(cx, global, global, args);
-
-// ScriptRuntime.call(cx, fun, global, args, global);
-
- if (retval instanceof Wrapper) {
- retval = ((Wrapper) retval).unwrap();
- }
- }
- catch (final Throwable t) {
- handleError(t);
- }
- finally {
- Context.exit();
- }
- return retval;
- }
-
- public void declareBean(final BSFDeclaredBean bean) throws BSFException {
- if ((bean.bean instanceof Number) ||
- (bean.bean instanceof String) ||
- (bean.bean instanceof Boolean)) {
- global.put(bean.name, global, bean.bean);
- }
- else {
- // Must wrap non-scriptable objects before presenting to Rhino
- final Scriptable wrapped = Context.toObject(bean.bean, global);
- global.put(bean.name, global, wrapped);
- }
- }
-
- /**
- * This is used by an application to evaluate a string containing
- * some expression.
- */
- public Object eval(final String source, final int lineNo, final int columnNo, final Object oscript)
- throws BSFException {
-
- final String scriptText = oscript.toString();
- Object retval = null;
- Context cx;
-
- try {
- cx = Context.enter();
-
- cx.setOptimizationLevel(-1);
- cx.setGeneratingDebug(false);
- cx.setGeneratingSource(false);
- cx.setOptimizationLevel(0);
- cx.setDebugger(null, null);
-
- retval = cx.evaluateString(global, scriptText,
- source, lineNo,
- null);
-
- if (retval instanceof NativeJavaObject) {
- retval = ((NativeJavaObject) retval).unwrap();
- }
-
- }
- catch (final Throwable t) { // includes JavaScriptException, rethrows Errors
- handleError(t);
- }
- finally {
- Context.exit();
- }
- return retval;
- }
-
- private void handleError(Throwable t) throws BSFException {
- if (t instanceof WrappedException) {
- t = ((WrappedException) t).getWrappedException();
- }
-
- String message = null;
- Throwable target = t;
-
- if (t instanceof JavaScriptException) {
- message = t.getLocalizedMessage();
-
- // Is it an exception wrapped in a JavaScriptException?
- final Object value = ((JavaScriptException) t).getValue();
- if (value instanceof Throwable) {
- // likely a wrapped exception from a LiveConnect call.
- // Display its stack trace as a diagnostic
- target = (Throwable) value;
- }
- }
- else if (t instanceof EvaluatorException ||
- t instanceof SecurityException) {
- message = t.getLocalizedMessage();
- }
- else if (t instanceof RuntimeException) {
- message = "Internal Error: " + t.toString();
- }
- else if (t instanceof StackOverflowError) {
- message = "Stack Overflow";
- }
-
- if (message == null) {
- message = t.toString();
- }
-
- if (t instanceof Error && !(t instanceof StackOverflowError)) {
- // Re-throw Errors because we're supposed to let the JVM see it
- // Don't re-throw StackOverflows, because we know we've
- // corrected the situation by aborting the loop and
- // a long stacktrace would end up on the user's console
- throw (Error) t;
- }
- else {
- throw new BSFException(BSFException.REASON_OTHER_ERROR,
- "JavaScript Error: " + message,
- target);
- }
- }
-
- /**
- * Initialize the engine.
- * Put the manager into the context-manager
- * map hashtable too.
- */
- public void initialize(final BSFManager mgr, final String lang, final Vector declaredBeans)
- throws BSFException {
-
- super.initialize(mgr, lang, declaredBeans);
-
- // Initialize context and global scope object
- try {
- final Context cx = Context.enter();
- global = new ImporterTopLevel(cx);
- final Scriptable bsf = Context.toObject(new BSFFunctions(mgr, this), global);
- global.put("bsf", global, bsf);
-
- for(final Iterator it = declaredBeans.iterator(); it.hasNext();) {
- declareBean((BSFDeclaredBean) it.next());
- }
- }
- catch (final Throwable t) {
-
- }
- finally {
- Context.exit();
- }
- }
-
- public void undeclareBean(final BSFDeclaredBean bean) throws BSFException {
- global.delete(bean.name);
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.engines.javascript;
+
+import java.util.Iterator;
+import java.util.Vector;
+
+import org.apache.bsf.BSFDeclaredBean;
+import org.apache.bsf.BSFException;
+import org.apache.bsf.BSFManager;
+import org.apache.bsf.util.BSFEngineImpl;
+import org.apache.bsf.util.BSFFunctions;
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.EvaluatorException;
+import org.mozilla.javascript.Function;
+import org.mozilla.javascript.ImporterTopLevel;
+import org.mozilla.javascript.JavaScriptException;
+import org.mozilla.javascript.NativeJavaObject;
+import org.mozilla.javascript.Scriptable;
+import org.mozilla.javascript.WrappedException;
+import org.mozilla.javascript.Wrapper;
+
+/**
+ * This is the interface to Netscape's Rhino (JavaScript) from the
+ * Bean Scripting Framework.
+ * <p>
+ * The original version of this code was first written by Adam Peller
+ * for use in LotusXSL. Sanjiva took his code and adapted it for BSF.
+ */
+public class JavaScriptEngine extends BSFEngineImpl {
+ /**
+ * The global script object, where all embedded functions are defined,
+ * as well as the standard ECMA "core" objects.
+ */
+ private Scriptable global;
+
+ /**
+ * Return an object from an extension.
+ * @param object Object on which to make the call (ignored).
+ * @param method The name of the method to call.
+ * @param args an array of arguments to be
+ * passed to the extension, which may be either
+ * Vectors of Nodes, or Strings.
+ */
+ public Object call(final Object object, final String method, final Object[] args)
+ throws BSFException {
+
+ Object retval = null;
+ Context cx;
+
+ try {
+ cx = Context.enter();
+
+ // REMIND: convert arg list Vectors here?
+
+ final Object fun = global.get(method, global);
+ // NOTE: Source and line arguments are nonsense in a call().
+ // Any way to make these arguments *sensible?
+ if (fun == Scriptable.NOT_FOUND) {
+ throw new EvaluatorException("function " + method +
+ " not found.", "none", 0);
+ }
+
+ cx.setOptimizationLevel(-1);
+ cx.setGeneratingDebug(false);
+ cx.setGeneratingSource(false);
+ cx.setOptimizationLevel(0);
+ cx.setDebugger(null, null);
+
+ retval =
+ ((Function) fun).call(cx, global, global, args);
+
+// ScriptRuntime.call(cx, fun, global, args, global);
+
+ if (retval instanceof Wrapper) {
+ retval = ((Wrapper) retval).unwrap();
+ }
+ }
+ catch (final Throwable t) {
+ handleError(t);
+ }
+ finally {
+ Context.exit();
+ }
+ return retval;
+ }
+
+ public void declareBean(final BSFDeclaredBean bean) throws BSFException {
+ if ((bean.bean instanceof Number) ||
+ (bean.bean instanceof String) ||
+ (bean.bean instanceof Boolean)) {
+ global.put(bean.name, global, bean.bean);
+ }
+ else {
+ // Must wrap non-scriptable objects before presenting to Rhino
+ final Scriptable wrapped = Context.toObject(bean.bean, global);
+ global.put(bean.name, global, wrapped);
+ }
+ }
+
+ /**
+ * This is used by an application to evaluate a string containing
+ * some expression.
+ */
+ public Object eval(final String source, final int lineNo, final int columnNo, final Object oscript)
+ throws BSFException {
+
+ final String scriptText = oscript.toString();
+ Object retval = null;
+ Context cx;
+
+ try {
+ cx = Context.enter();
+
+ cx.setOptimizationLevel(-1);
+ cx.setGeneratingDebug(false);
+ cx.setGeneratingSource(false);
+ cx.setOptimizationLevel(0);
+ cx.setDebugger(null, null);
+
+ retval = cx.evaluateString(global, scriptText,
+ source, lineNo,
+ null);
+
+ if (retval instanceof NativeJavaObject) {
+ retval = ((NativeJavaObject) retval).unwrap();
+ }
+
+ }
+ catch (final Throwable t) { // includes JavaScriptException, rethrows Errors
+ handleError(t);
+ }
+ finally {
+ Context.exit();
+ }
+ return retval;
+ }
+
+ private void handleError(Throwable t) throws BSFException {
+ if (t instanceof WrappedException) {
+ t = ((WrappedException) t).getWrappedException();
+ }
+
+ String message = null;
+ Throwable target = t;
+
+ if (t instanceof JavaScriptException) {
+ message = t.getLocalizedMessage();
+
+ // Is it an exception wrapped in a JavaScriptException?
+ final Object value = ((JavaScriptException) t).getValue();
+ if (value instanceof Throwable) {
+ // likely a wrapped exception from a LiveConnect call.
+ // Display its stack trace as a diagnostic
+ target = (Throwable) value;
+ }
+ }
+ else if (t instanceof EvaluatorException ||
+ t instanceof SecurityException) {
+ message = t.getLocalizedMessage();
+ }
+ else if (t instanceof RuntimeException) {
+ message = "Internal Error: " + t.toString();
+ }
+ else if (t instanceof StackOverflowError) {
+ message = "Stack Overflow";
+ }
+
+ if (message == null) {
+ message = t.toString();
+ }
+
+ if (t instanceof Error && !(t instanceof StackOverflowError)) {
+ // Re-throw Errors because we're supposed to let the JVM see it
+ // Don't re-throw StackOverflows, because we know we've
+ // corrected the situation by aborting the loop and
+ // a long stacktrace would end up on the user's console
+ throw (Error) t;
+ }
+ else {
+ throw new BSFException(BSFException.REASON_OTHER_ERROR,
+ "JavaScript Error: " + message,
+ target);
+ }
+ }
+
+ /**
+ * Initialize the engine.
+ * Put the manager into the context-manager
+ * map hashtable too.
+ */
+ public void initialize(final BSFManager mgr, final String lang, final Vector declaredBeans)
+ throws BSFException {
+
+ super.initialize(mgr, lang, declaredBeans);
+
+ // Initialize context and global scope object
+ try {
+ final Context cx = Context.enter();
+ global = new ImporterTopLevel(cx);
+ final Scriptable bsf = Context.toObject(new BSFFunctions(mgr, this), global);
+ global.put("bsf", global, bsf);
+
+ for(final Iterator it = declaredBeans.iterator(); it.hasNext();) {
+ declareBean((BSFDeclaredBean) it.next());
+ }
+ }
+ catch (final Throwable t) {
+
+ }
+ finally {
+ Context.exit();
+ }
+ }
+
+ public void undeclareBean(final BSFDeclaredBean bean) throws BSFException {
+ global.delete(bean.name);
+ }
+}
diff --git a/src/main/java/org/apache/bsf/engines/jython/JythonEngine.java b/src/main/java/org/apache/bsf/engines/jython/JythonEngine.java
index c6d724d..5396b25 100644
--- a/src/main/java/org/apache/bsf/engines/jython/JythonEngine.java
+++ b/src/main/java/org/apache/bsf/engines/jython/JythonEngine.java
@@ -1,284 +1,279 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.engines.jython;
-
-import java.beans.PropertyChangeEvent;
-import java.io.ByteArrayInputStream;
-import java.util.Vector;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.bsf.BSFDeclaredBean;
-import org.apache.bsf.BSFException;
-import org.apache.bsf.BSFManager;
-import org.apache.bsf.util.BSFEngineImpl;
-import org.apache.bsf.util.BSFFunctions;
-import org.python.core.Py;
-import org.python.core.PyException;
-import org.python.core.PyJavaInstance;
-import org.python.core.PyObject;
-import org.python.core.PySystemState;
-import org.python.util.InteractiveInterpreter;
-
-/**
- * This is the interface to Jython (http://www.jython.org/) from BSF.
- * It's derived from the JPython 1.x engine
- *
- * @author Sanjiva Weerawarana
- * @author Finn Bock <bc...@worldonline.dk>
- * @author Chuck Murcko
- * @author Sonny To" <so...@gmail.com>, 2006-10-30
- */
-
-public class JythonEngine extends BSFEngineImpl {
- BSFPythonInterpreter interp;
- private final static Pattern fromRegExp = Pattern.compile("from ([.^\\S]*)");
-
- /**
- * call the named method of the given object.
- */
- public Object call (final Object object, final String method, final Object[] args)
- throws BSFException {
- try {
- PyObject[] pyargs = Py.EmptyObjects;
-
- if (args != null) {
- pyargs = new PyObject[args.length];
- for (int i = 0; i < pyargs.length; i++) {
- pyargs[i] = Py.java2py(args[i]);
- }
- }
-
- if (object != null) {
- final PyObject o = Py.java2py(object);
- return unwrap(o.invoke(method, pyargs));
- }
-
- PyObject m = interp.get(method);
-
- if (m == null) {
- m = interp.eval(method);
- }
- if (m != null) {
- return unwrap(m.__call__(pyargs));
- }
-
- return null;
- } catch (final PyException e) {
- throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
- "exception from Jython:\n" + e, e);
- }
- }
-
- /**
- * Declare a bean
- */
- public void declareBean (final BSFDeclaredBean bean) throws BSFException {
- interp.set (bean.name, bean.bean);
- }
-
- /**
- * Evaluate an anonymous function (differs from eval() in that apply()
- * handles multiple lines).
- */
- public Object apply (final String source, final int lineNo, final int columnNo,
- final Object funcBody, final Vector paramNames,
- final Vector arguments) throws BSFException {
- try {
- /* We wrapper the original script in a function definition, and
- * evaluate the function. A hack, no question, but it allows
- * apply() to pretend to work on Jython.
- */
- final StringBuffer script = new StringBuffer(byteify(funcBody.toString()));
- int index = 0;
- script.insert(0, "def bsf_temp_fn():\n");
-
- while (index < script.length()) {
- if (script.charAt(index) == '\n') {
- script.insert(index+1, '\t');
- }
- index++;
- }
-
- final String scriptStr = script.toString ();
- importPackage(scriptStr);
- interp.exec (scriptStr);
-
- Object result = interp.eval ("bsf_temp_fn()");
-
- if (result instanceof PyJavaInstance) {
- result = ((PyJavaInstance)result).__tojava__(Object.class);
- }
- return result;
- } catch (final PyException e) {
- throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
- "exception from Jython:\n" + e, e);
- }
- }
-
- /**
- * Evaluate an expression.
- */
- public Object eval (final String source, final int lineNo, final int columnNo,
- final Object script) throws BSFException {
- try {
- final String scriptStr = byteify(script.toString ());
- importPackage(scriptStr);
- Object result = interp.eval (scriptStr);
- if (result instanceof PyJavaInstance) {
- result = ((PyJavaInstance)result).__tojava__(Object.class);
- }
- return result;
- } catch (final PyException e) {
- throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
- "exception from Jython:\n" + e, e);
- }
- }
-
- /**
- * Execute a script.
- */
- public void exec (final String source, final int lineNo, final int columnNo,
- final Object script) throws BSFException {
- try {
- final String scriptStr = byteify(script.toString());
- importPackage(scriptStr);
- interp.exec (scriptStr);
- } catch (final PyException e) {
- throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
- "exception from Jython:\n" + e, e);
- }
- }
-
- private void importPackage(final String script) {
- final Matcher matcher = fromRegExp.matcher(script);
- while (matcher.find()) {
- final String packageName = matcher.group(1);
- PySystemState.add_package(packageName);
- }
- }
-
- /**
- * Execute script code, emulating console interaction.
- */
- public void iexec (final String source, final int lineNo, final int columnNo,
- final Object script) throws BSFException {
- String scriptStr = byteify(script.toString());
- importPackage(scriptStr);
- final int newline = scriptStr.indexOf("\n");
-
- if (newline > -1) {
- scriptStr = scriptStr.substring(0, newline);
- }
-
- try {
- if (interp.buffer.length() > 0) {
- interp.buffer.append("\n");
- }
- interp.buffer.append(scriptStr);
- if (!(interp.runsource(interp.buffer.toString()))) {
- interp.resetbuffer();
- }
- } catch (final PyException e) {
- interp.resetbuffer();
- throw new BSFException(BSFException.REASON_EXECUTION_ERROR,
- "exception from Jython:\n" + e, e);
- }
- }
-
- /**
- * Initialize the engine.
- */
- public void initialize (final BSFManager mgr, final String lang,
- final Vector declaredBeans) throws BSFException {
- super.initialize (mgr, lang, declaredBeans);
-
- // create an interpreter
- interp = new BSFPythonInterpreter ();
-
- // ensure that output and error streams are re-directed correctly
- interp.setOut(System.out);
- interp.setErr(System.err);
-
- // register the mgr with object name "bsf"
- interp.set ("bsf", new BSFFunctions (mgr, this));
-
- // Declare all declared beans to the interpreter
- final int size = declaredBeans.size ();
- for (int i = 0; i < size; i++) {
- declareBean ((BSFDeclaredBean) declaredBeans.elementAt (i));
- }
- }
-
- /**
- * Undeclare a previously declared bean.
- */
- public void undeclareBean (final BSFDeclaredBean bean) throws BSFException {
- interp.set (bean.name, null);
- }
-
- public Object unwrap(final PyObject result) {
- if (result != null) {
- final Object ret = result.__tojava__(Object.class);
- if (ret != Py.NoConversion) {
- return ret;
- }
- }
- return result;
- }
-
- private String byteify (final String orig) {
- // Ugh. Jython likes to be fed bytes, rather than the input string.
- final ByteArrayInputStream bais =
- new ByteArrayInputStream(orig.getBytes());
- final StringBuffer s = new StringBuffer();
- int c;
-
- while ((c = bais.read()) >= 0) {
- s.append((char)c);
- }
-
- return s.toString();
- }
-
- private class BSFPythonInterpreter extends InteractiveInterpreter {
-
- public BSFPythonInterpreter() {
- }
-
- // Override runcode so as not to print the stack dump
- public void runcode(final PyObject code) {
- try {
- this.exec(code);
- } catch (final PyException exc) {
- throw exc;
- }
- }
- }
-
-
- public void propertyChange(final PropertyChangeEvent e) {
- super.propertyChange(e);
- final String name = e.getPropertyName();
- final Object value = e.getNewValue();
- if (name.equals("classLoader")) {
- Py.getSystemState().setClassLoader((ClassLoader) value);
- }
-
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.engines.jython;
+
+import java.beans.PropertyChangeEvent;
+import java.io.ByteArrayInputStream;
+import java.util.Vector;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.bsf.BSFDeclaredBean;
+import org.apache.bsf.BSFException;
+import org.apache.bsf.BSFManager;
+import org.apache.bsf.util.BSFEngineImpl;
+import org.apache.bsf.util.BSFFunctions;
+import org.python.core.Py;
+import org.python.core.PyException;
+import org.python.core.PyJavaInstance;
+import org.python.core.PyObject;
+import org.python.core.PySystemState;
+import org.python.util.InteractiveInterpreter;
+
+/**
+ * This is the interface to Jython (http://www.jython.org/) from BSF.
+ * It's derived from the JPython 1.x engine
+ */
+
+public class JythonEngine extends BSFEngineImpl {
+ BSFPythonInterpreter interp;
+ private final static Pattern fromRegExp = Pattern.compile("from ([.^\\S]*)");
+
+ /**
+ * call the named method of the given object.
+ */
+ public Object call (final Object object, final String method, final Object[] args)
+ throws BSFException {
+ try {
+ PyObject[] pyargs = Py.EmptyObjects;
+
+ if (args != null) {
+ pyargs = new PyObject[args.length];
+ for (int i = 0; i < pyargs.length; i++) {
+ pyargs[i] = Py.java2py(args[i]);
+ }
+ }
+
+ if (object != null) {
+ final PyObject o = Py.java2py(object);
+ return unwrap(o.invoke(method, pyargs));
+ }
+
+ PyObject m = interp.get(method);
+
+ if (m == null) {
+ m = interp.eval(method);
+ }
+ if (m != null) {
+ return unwrap(m.__call__(pyargs));
+ }
+
+ return null;
+ } catch (final PyException e) {
+ throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
+ "exception from Jython:\n" + e, e);
+ }
+ }
+
+ /**
+ * Declare a bean
+ */
+ public void declareBean (final BSFDeclaredBean bean) throws BSFException {
+ interp.set (bean.name, bean.bean);
+ }
+
+ /**
+ * Evaluate an anonymous function (differs from eval() in that apply()
+ * handles multiple lines).
+ */
+ public Object apply (final String source, final int lineNo, final int columnNo,
+ final Object funcBody, final Vector paramNames,
+ final Vector arguments) throws BSFException {
+ try {
+ /* We wrapper the original script in a function definition, and
+ * evaluate the function. A hack, no question, but it allows
+ * apply() to pretend to work on Jython.
+ */
+ final StringBuffer script = new StringBuffer(byteify(funcBody.toString()));
+ int index = 0;
+ script.insert(0, "def bsf_temp_fn():\n");
+
+ while (index < script.length()) {
+ if (script.charAt(index) == '\n') {
+ script.insert(index+1, '\t');
+ }
+ index++;
+ }
+
+ final String scriptStr = script.toString ();
+ importPackage(scriptStr);
+ interp.exec (scriptStr);
+
+ Object result = interp.eval ("bsf_temp_fn()");
+
+ if (result instanceof PyJavaInstance) {
+ result = ((PyJavaInstance)result).__tojava__(Object.class);
+ }
+ return result;
+ } catch (final PyException e) {
+ throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
+ "exception from Jython:\n" + e, e);
+ }
+ }
+
+ /**
+ * Evaluate an expression.
+ */
+ public Object eval (final String source, final int lineNo, final int columnNo,
+ final Object script) throws BSFException {
+ try {
+ final String scriptStr = byteify(script.toString ());
+ importPackage(scriptStr);
+ Object result = interp.eval (scriptStr);
+ if (result instanceof PyJavaInstance) {
+ result = ((PyJavaInstance)result).__tojava__(Object.class);
+ }
+ return result;
+ } catch (final PyException e) {
+ throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
+ "exception from Jython:\n" + e, e);
+ }
+ }
+
+ /**
+ * Execute a script.
+ */
+ public void exec (final String source, final int lineNo, final int columnNo,
+ final Object script) throws BSFException {
+ try {
+ final String scriptStr = byteify(script.toString());
+ importPackage(scriptStr);
+ interp.exec (scriptStr);
+ } catch (final PyException e) {
+ throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
+ "exception from Jython:\n" + e, e);
+ }
+ }
+
+ private void importPackage(final String script) {
+ final Matcher matcher = fromRegExp.matcher(script);
+ while (matcher.find()) {
+ final String packageName = matcher.group(1);
+ PySystemState.add_package(packageName);
+ }
+ }
+
+ /**
+ * Execute script code, emulating console interaction.
+ */
+ public void iexec (final String source, final int lineNo, final int columnNo,
+ final Object script) throws BSFException {
+ String scriptStr = byteify(script.toString());
+ importPackage(scriptStr);
+ final int newline = scriptStr.indexOf("\n");
+
+ if (newline > -1) {
+ scriptStr = scriptStr.substring(0, newline);
+ }
+
+ try {
+ if (interp.buffer.length() > 0) {
+ interp.buffer.append("\n");
+ }
+ interp.buffer.append(scriptStr);
+ if (!(interp.runsource(interp.buffer.toString()))) {
+ interp.resetbuffer();
+ }
+ } catch (final PyException e) {
+ interp.resetbuffer();
+ throw new BSFException(BSFException.REASON_EXECUTION_ERROR,
+ "exception from Jython:\n" + e, e);
+ }
+ }
+
+ /**
+ * Initialize the engine.
+ */
+ public void initialize (final BSFManager mgr, final String lang,
+ final Vector declaredBeans) throws BSFException {
+ super.initialize (mgr, lang, declaredBeans);
+
+ // create an interpreter
+ interp = new BSFPythonInterpreter ();
+
+ // ensure that output and error streams are re-directed correctly
+ interp.setOut(System.out);
+ interp.setErr(System.err);
+
+ // register the mgr with object name "bsf"
+ interp.set ("bsf", new BSFFunctions (mgr, this));
+
+ // Declare all declared beans to the interpreter
+ final int size = declaredBeans.size ();
+ for (int i = 0; i < size; i++) {
+ declareBean ((BSFDeclaredBean) declaredBeans.elementAt (i));
+ }
+ }
+
+ /**
+ * Undeclare a previously declared bean.
+ */
+ public void undeclareBean (final BSFDeclaredBean bean) throws BSFException {
+ interp.set (bean.name, null);
+ }
+
+ public Object unwrap(final PyObject result) {
+ if (result != null) {
+ final Object ret = result.__tojava__(Object.class);
+ if (ret != Py.NoConversion) {
+ return ret;
+ }
+ }
+ return result;
+ }
+
+ private String byteify (final String orig) {
+ // Ugh. Jython likes to be fed bytes, rather than the input string.
+ final ByteArrayInputStream bais =
+ new ByteArrayInputStream(orig.getBytes());
+ final StringBuffer s = new StringBuffer();
+ int c;
+
+ while ((c = bais.read()) >= 0) {
+ s.append((char)c);
+ }
+
+ return s.toString();
+ }
+
+ private class BSFPythonInterpreter extends InteractiveInterpreter {
+
+ public BSFPythonInterpreter() {
+ }
+
+ // Override runcode so as not to print the stack dump
+ public void runcode(final PyObject code) {
+ try {
+ this.exec(code);
+ } catch (final PyException exc) {
+ throw exc;
+ }
+ }
+ }
+
+
+ public void propertyChange(final PropertyChangeEvent e) {
+ super.propertyChange(e);
+ final String name = e.getPropertyName();
+ final Object value = e.getNewValue();
+ if (name.equals("classLoader")) {
+ Py.getSystemState().setClassLoader((ClassLoader) value);
+ }
+
+ }
+}
diff --git a/src/main/java/org/apache/bsf/engines/netrexx/NetRexxEngine.java b/src/main/java/org/apache/bsf/engines/netrexx/NetRexxEngine.java
index 5c08244..19e95db 100644
--- a/src/main/java/org/apache/bsf/engines/netrexx/NetRexxEngine.java
+++ b/src/main/java/org/apache/bsf/engines/netrexx/NetRexxEngine.java
@@ -1,502 +1,498 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.engines.netrexx;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FilenameFilter;
-import java.io.PrintWriter;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Hashtable;
-import java.util.Vector;
-
-import org.apache.bsf.BSFDeclaredBean;
-import org.apache.bsf.BSFException;
-import org.apache.bsf.BSFManager;
-import org.apache.bsf.BSF_Log;
-import org.apache.bsf.BSF_LogFactory;
-import org.apache.bsf.util.BSFEngineImpl;
-import org.apache.bsf.util.BSFFunctions;
-import org.apache.bsf.util.EngineUtils;
-import org.apache.bsf.util.MethodUtils;
-import org.apache.bsf.util.StringUtils;
-
-/**
- * This is the interface to NetRexx from the
- * Bean Scripting Framework.
- * <p>
- * The NetRexx code must be written script-style, without a "class" or
- * "properties" section preceeding the executable code. The NetRexxEngine will
- * generate a prefix for this code:
- * <pre>
- * <code>
- * class $$CLASSNAME$$;
- * method BSFNetRexxEngineEntry(bsf=org.apache.bsf.BSFManager) public static;
- * </code>
- * </pre>
- * $$CLASSNAME$$ will be replaced by a generated classname of the form
- * BSFNetRexx*, and the bsf parameter can be used to retrieve application
- * objects registered with the Bean Scripting Framework.
- * <p>
- * If you use the placeholder string $$CLASSNAME$$ elsewhere
- * in your script -- including within text strings -- BSFNetRexxEngine will
- * replace it with the generated name of the class before the NetRexx code
- * is compiled.
- * <p>
- * If you need to use full NetRexx functionality, we recommend that your
- * NetRexx script define and invoke a "minor class", with or without the
- * "dependent" keyword as suits your needs. You'll have to use $$CLASSNAME$$
- * in naming the minor class, since the name of the main class is synthesized;
- * for example, to create the minor class "bar" you'd write
- * "class $$CLASSNAME$$.Bar".
- * <p>
- * <h2>Hazards:</h2>
- * <p>
- * Since NetRexx has to be _compiled_ to a Java classfile, invoking it involves
- * a fair amount of computation to load and execute the compiler. We are
- * currently making an attempt to manage that by caching the class
- * after it has been loaded, but the indexing is fairly primitive; we
- * hash against the script string to find the class for it.
- * <p>
- * Minor-class .class files are now being deleted after the major class loads.
- * This coould potentially cause problems.
- *
- * @author Joe Kesselman
- * @author Sanjiva Weerawarana
- * @author Rony G. Flatscher (added BSF_Log[Factory] to allow BSF to run without org.apache.commons.logging present)
- */
-public class NetRexxEngine extends BSFEngineImpl
-{
- BSFFunctions mgrfuncs;
- static Hashtable codeToClass=new Hashtable();
- static String serializeCompilation="";
- static String placeholder="$$CLASSNAME$$";
- String minorPrefix;
-
- // private Log logger = LogFactory.getLog(this.getClass().getName());
- private BSF_Log logger = null;
-
- /**
- * Create a scratchfile, open it for writing, return its name.
- * Relies on the filesystem to provide us with uniqueness testing.
- * NOTE THAT uniqueFileOffset continues to count; we don't want to
- * risk reusing a classname we have previously loaded in this session
- * even if the classfile has been deleted.
- *
- * I've made the offset static, due to concerns about reuse/reentrancy
- * of the NetRexx engine.
- */
- private static int uniqueFileOffset=0;
- private class GeneratedFile
- {
- File file=null;
- FileOutputStream fos=null;
- String className=null;
- GeneratedFile(File file,FileOutputStream fos,String className)
- {
- this.file=file;
- this.fos=fos;
- this.className=className;
- }
- }
-
- // rexxclass used to be an instance variable, on the theory that
- // each NetRexxEngine was an instance of a specific script.
- // BSF is currently reusing Engines, so caching the class
- // no longer makes sense.
- // Class rexxclass;
-
- /**
- * Constructor.
- */
- public NetRexxEngine ()
- {
- // handle logger
- logger = BSF_LogFactory.getLog(this.getClass().getName());
- /*
- The following line is intended to cause the constructor to
- throw a NoClassDefFoundError if the NetRexxC.zip dependency
- is not resolved.
-
- If this line was not here, the problem would not surface until
- the actual processing of a script. We want to know all is well
- at the time the engine is instantiated, not when we attempt to
- process a script.
- */
-
- new netrexx.lang.BadArgumentException();
- }
- /**
- * Return an object from an extension.
- * @param object object from which to call our static method
- * @param method The name of the method to call.
- * @param args an array of arguments to be
- * passed to the extension, which may be either
- * Vectors of Nodes, or Strings.
- */
- public Object call (Object object, String method, Object[] args)
- throws BSFException
- {
- throw new BSFException(BSFException.REASON_UNSUPPORTED_FEATURE,
- "NetRexx doesn't currently support call()",
- null);
- }
- /**
- * Invoke a static method.
- * @param rexxclass Class to invoke the method against
- * @param method The name of the method to call.
- * @param args an array of arguments to be
- * passed to the extension, which may be either
- * Vectors of Nodes, or Strings.
- */
- Object callStatic(Class rexxclass, String method, Object[] args)
- throws BSFException
- {
- //***** ISSUE: Currently supports only static methods
- Object retval = null;
- try
- {
- if (rexxclass != null)
- {
- //***** This should call the lookup used in BML, for typesafety
- Class[] argtypes=new Class[args.length];
- for(int i=0;i<args.length;++i)
- argtypes[i]=args[i].getClass();
-
- Method m=MethodUtils.getMethod(rexxclass, method, argtypes);
- retval=m.invoke(null,args);
- }
- else
- {
- logger.error("NetRexxEngine: ERROR: rexxclass==null!");
- }
- }
- catch(Exception e)
- {
- e.printStackTrace ();
- if (e instanceof InvocationTargetException)
- {
- Throwable t = ((InvocationTargetException)e).getTargetException ();
- t.printStackTrace ();
- }
- throw new BSFException (BSFException.REASON_IO_ERROR,
- e.getMessage (),
- e);
- }
- return retval;
- }
- public void declareBean (BSFDeclaredBean bean) throws BSFException {}
- /**
- * Override impl of execute. In NetRexx, methods which do not wish
- * to return a value should be invoked via exec, which will cause them
- * to be generated without the "returns" clause.
- * Those which wish to return a value should call eval instead.
- * which will add "returns java.lang.Object" to the header.
- *
- * Note: It would be nice to have the "real" return type avaialable, so
- * we could do something more type-safe than Object, and so we could
- * return primitive types without having to enclose them in their
- * object wrappers. BSF does not currently support that concept.
- */
- public Object eval (String source, int lineNo, int columnNo,
- Object script)
- throws BSFException
- {
- return execEvalShared(source, lineNo, columnNo, script,true);
- }
- /**
- * Override impl of execute. In NetRexx, methods which do not wish
- * to return a value should be invoked via exec, which will cause them
- * to be generated without the "returns" clause.
- * Those which wish to return a value should call eval instead.
- * which will add "returns java.lang.Object" to the header.
- */
- public void exec (String source, int lineNo, int columnNo,
- Object script)
- throws BSFException
- {
- execEvalShared(source, lineNo, columnNo, script,false);
- }
- /**
- * This is shared code for the exec() and eval() operations. It will
- * evaluate a string containing a NetRexx method body -- which may be
- * as simple as a single return statement.
- * It should store the "bsf" handle where the
- * script can get to it, for callback purposes.
- * <p>
- * Note that NetRexx compilation imposes serious overhead -- 11 seconds for
- * the first compile, about 3 thereafter -- but in exchange you get
- * Java-like speeds once the classes have been created (minus the cache
- * lookup cost).
- * <p>
- * Nobody knows whether javac is threadsafe.
- * I'm going to serialize access to the compilers to protect it.
- */
- public Object execEvalShared (String source, int lineNo, int columnNo,
- Object oscript,boolean returnsObject)
- throws BSFException
- {
- Object retval=null;
- String classname=null;
- GeneratedFile gf=null;
-
- // Moved into the exec process; see comment above.
- Class rexxclass=null;
-
- String basescript=oscript.toString();
- String script=basescript; // May be altered by $$CLASSNAME$$ expansion
-
- try {
- // Do we already have a class exactly matching this code?
- rexxclass=(Class)codeToClass.get(basescript);
-
- if(rexxclass!=null)
-
- {
- logger.debug("NetRexxEngine: Found pre-compiled class" +
- " for script '" + basescript + "'");
- classname=rexxclass.getName();
- }
- else
- {
- gf=openUniqueFile(tempDir,"BSFNetRexx",".nrx");
- if(gf==null)
- throw new BSFException("couldn't create NetRexx scratchfile");
-
- // Obtain classname
- classname=gf.className;
-
- // Decide whether to declare a return type
- String returnsDecl="";
- if(returnsObject)
- returnsDecl="returns java.lang.Object";
-
- // Write the kluge header to the file.
- // ***** By doing so we give up the ability to use Property blocks.
- gf.fos.write(("class "+classname+";\n")
- .getBytes());
- gf.fos.write(
- ("method BSFNetRexxEngineEntry(bsf=org.apache.bsf.util.BSFFunctions) "+
- " public static "+returnsDecl+";\n")
- .getBytes());
-
- // Edit the script to replace placeholder with the generated
- // classname. Note that this occurs _after_ the cache was
- // checked!
- int startpoint,endpoint;
- if((startpoint=script.indexOf(placeholder))>=0)
- {
- StringBuffer changed=new StringBuffer();
- for(;
- startpoint>=0;
- startpoint=script.indexOf(placeholder,startpoint))
- {
- changed.setLength(0); // Reset for 2nd pass or later
- if(startpoint>0)
- changed.append(script.substring(0,startpoint));
- changed.append(classname);
- endpoint=startpoint+placeholder.length();
- if(endpoint<script.length())
- changed.append(script.substring(endpoint));
- script=changed.toString();
- }
- }
-
- BSFDeclaredBean tempBean;
- String className;
-
- for (int i = 0; i < declaredBeans.size (); i++)
- {
- tempBean = (BSFDeclaredBean) declaredBeans.elementAt (i);
- className = StringUtils.getClassName (tempBean.type);
-
- gf.fos.write ((tempBean.name + " =" + className + " bsf.lookupBean(\"" +
- tempBean.name + "\");").getBytes());
- }
-
- if(returnsObject)
- gf.fos.write("return ".getBytes());
-
- // Copy the input to the file.
- // Assumes all available -- probably mistake, but same as
- // other engines.
- gf.fos.write(script.getBytes());
- gf.fos.close();
-
- logger.debug("NetRexxEngine: wrote temp file " +
- gf.file.getPath () + ", now compiling");
-
- // Compile through Java to .class file
- String command=gf.file.getPath(); //classname;
- if (logger.isDebugEnabled()) {
- command += " -verbose4";
- } else {
- command += " -noverbose";
- command += " -noconsole";
- }
-
- netrexx.lang.Rexx cmdline= new netrexx.lang.Rexx(command);
- int retValue;
-
- // May not be threadsafe. Serialize access on static object:
- synchronized(serializeCompilation)
- {
- // compile to a .java file
- retValue =
- COM.ibm.netrexx.process.NetRexxC.main(cmdline,
- new PrintWriter(System.err));
- }
-
- // Check if there were errors while compiling the Rexx code.
- if (retValue == 2)
- {
- throw new BSFException(BSFException.REASON_EXECUTION_ERROR,
- "There were NetRexx errors.");
- }
-
- // Load class.
- logger.debug("NetRexxEngine: loading class "+classname);
- rexxclass=EngineUtils.loadClass (mgr, classname);
-
- // Stash class for reuse
- codeToClass.put(basescript,rexxclass);
- }
-
- Object[] args={mgrfuncs};
- retval=callStatic(rexxclass, "BSFNetRexxEngineEntry",args);
- }
- catch (BSFException e)
- {
- // Just forward the exception on.
- throw e;
- }
- catch(Exception e)
- {
- e.printStackTrace ();
- if (e instanceof InvocationTargetException)
- {
- Throwable t = ((InvocationTargetException)e).getTargetException ();
- t.printStackTrace ();
- }
- throw new BSFException (BSFException.REASON_IO_ERROR,
- e.getMessage (), e);
- }
- finally
- {
- // Cleanup: delete the .nrx and .class files
- // (if any) generated by NetRexx Trace requests.
-
- if(gf!=null && gf.file!=null && gf.file.exists())
- gf.file.delete(); // .nrx file
-
- if(classname!=null)
- {
- // Generated src
- File file=new File(tempDir+File.separatorChar+classname+".java");
- if(file.exists())
- file.delete();
-
- // Generated class
- file=new File(classname+".class");
- if(file.exists())
- file.delete();
-
- // Can this be done without disrupting trace?
- file=new File(tempDir+File.separatorChar+classname+".crossref");
- if(file.exists())
- file.delete();
-
- // Search for and clean up minor classes, classname$xxx.class
- file=new File(tempDir);
- minorPrefix=classname+"$"; // Indirect arg to filter
- String[] minor_classfiles=
- file.list(
- // ANONYMOUS CLASS for filter:
- new FilenameFilter()
- {
- // Starts with classname$ and ends with .class
- public boolean accept(File dir,String name)
- {
- return
- (0==name.indexOf(minorPrefix))
- &&
- (name.lastIndexOf(".class")==name.length()-6)
- ;
- }
- }
- );
- if(minor_classfiles!=null)
- for(int i=minor_classfiles.length;i>0;)
- {
- file=new File(minor_classfiles[--i]);
- file.delete();
- }
- }
- }
-
- return retval;
- }
- public void initialize(BSFManager mgr, String lang,Vector declaredBeans)
- throws BSFException
- {
- super.initialize(mgr, lang, declaredBeans);
- mgrfuncs = new BSFFunctions (mgr, this);
- }
-private GeneratedFile openUniqueFile(String directory,String prefix,String suffix)
- {
- File file=null,obj=null;
- FileOutputStream fos=null;
- int max=1000; // Don't try forever
- GeneratedFile gf=null;
- int i;
- String className = null;
- for(i=max,++uniqueFileOffset;
- fos==null && i>0;
- --i,++uniqueFileOffset)
- {
- // Probably a timing hazard here... ***************
- try
- {
- className = prefix+uniqueFileOffset;
- file=new File(directory+File.separatorChar+className+suffix);
- obj=new File(directory+File.separatorChar+className+".class");
- if(file!=null && !file.exists() & obj!=null & !obj.exists())
- fos=new FileOutputStream(file);
- }
- catch(Exception e)
- {
- // File could not be opened for write, or Security Exception
- // was thrown. If someone else created the file before we could
- // open it, that's probably a threading conflict and we don't
- // bother reporting it.
- if(!file.exists())
- {
- logger.error("openUniqueFile: unexpected "+e);
- }
- }
- }
- if(fos==null)
- logger.error("openUniqueFile: Failed "+max+"attempts.");
- else
- gf=new GeneratedFile(file,fos,className);
- return gf;
- }
-
- public void undeclareBean (BSFDeclaredBean bean) throws BSFException {}
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.engines.netrexx;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FilenameFilter;
+import java.io.PrintWriter;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Hashtable;
+import java.util.Vector;
+
+import org.apache.bsf.BSFDeclaredBean;
+import org.apache.bsf.BSFException;
+import org.apache.bsf.BSFManager;
+import org.apache.bsf.BSF_Log;
+import org.apache.bsf.BSF_LogFactory;
+import org.apache.bsf.util.BSFEngineImpl;
+import org.apache.bsf.util.BSFFunctions;
+import org.apache.bsf.util.EngineUtils;
+import org.apache.bsf.util.MethodUtils;
+import org.apache.bsf.util.StringUtils;
+
+/**
+ * This is the interface to NetRexx from the
+ * Bean Scripting Framework.
+ * <p>
+ * The NetRexx code must be written script-style, without a "class" or
+ * "properties" section preceeding the executable code. The NetRexxEngine will
+ * generate a prefix for this code:
+ * <pre>
+ * <code>
+ * class $$CLASSNAME$$;
+ * method BSFNetRexxEngineEntry(bsf=org.apache.bsf.BSFManager) public static;
+ * </code>
+ * </pre>
+ * $$CLASSNAME$$ will be replaced by a generated classname of the form
+ * BSFNetRexx*, and the bsf parameter can be used to retrieve application
+ * objects registered with the Bean Scripting Framework.
+ * <p>
+ * If you use the placeholder string $$CLASSNAME$$ elsewhere
+ * in your script -- including within text strings -- BSFNetRexxEngine will
+ * replace it with the generated name of the class before the NetRexx code
+ * is compiled.
+ * <p>
+ * If you need to use full NetRexx functionality, we recommend that your
+ * NetRexx script define and invoke a "minor class", with or without the
+ * "dependent" keyword as suits your needs. You'll have to use $$CLASSNAME$$
+ * in naming the minor class, since the name of the main class is synthesized;
+ * for example, to create the minor class "bar" you'd write
+ * "class $$CLASSNAME$$.Bar".
+ * <p>
+ * <h2>Hazards:</h2>
+ * <p>
+ * Since NetRexx has to be _compiled_ to a Java classfile, invoking it involves
+ * a fair amount of computation to load and execute the compiler. We are
+ * currently making an attempt to manage that by caching the class
+ * after it has been loaded, but the indexing is fairly primitive; we
+ * hash against the script string to find the class for it.
+ * <p>
+ * Minor-class .class files are now being deleted after the major class loads.
+ * This coould potentially cause problems.
+ */
+public class NetRexxEngine extends BSFEngineImpl
+{
+ BSFFunctions mgrfuncs;
+ static Hashtable codeToClass=new Hashtable();
+ static String serializeCompilation="";
+ static String placeholder="$$CLASSNAME$$";
+ String minorPrefix;
+
+ // private Log logger = LogFactory.getLog(this.getClass().getName());
+ private BSF_Log logger = null;
+
+ /**
+ * Create a scratchfile, open it for writing, return its name.
+ * Relies on the filesystem to provide us with uniqueness testing.
+ * NOTE THAT uniqueFileOffset continues to count; we don't want to
+ * risk reusing a classname we have previously loaded in this session
+ * even if the classfile has been deleted.
+ *
+ * I've made the offset static, due to concerns about reuse/reentrancy
+ * of the NetRexx engine.
+ */
+ private static int uniqueFileOffset=0;
+ private class GeneratedFile
+ {
+ File file=null;
+ FileOutputStream fos=null;
+ String className=null;
+ GeneratedFile(File file,FileOutputStream fos,String className)
+ {
+ this.file=file;
+ this.fos=fos;
+ this.className=className;
+ }
+ }
+
+ // rexxclass used to be an instance variable, on the theory that
+ // each NetRexxEngine was an instance of a specific script.
+ // BSF is currently reusing Engines, so caching the class
+ // no longer makes sense.
+ // Class rexxclass;
+
+ /**
+ * Constructor.
+ */
+ public NetRexxEngine ()
+ {
+ // handle logger
+ logger = BSF_LogFactory.getLog(this.getClass().getName());
+ /*
+ The following line is intended to cause the constructor to
+ throw a NoClassDefFoundError if the NetRexxC.zip dependency
+ is not resolved.
+
+ If this line was not here, the problem would not surface until
+ the actual processing of a script. We want to know all is well
+ at the time the engine is instantiated, not when we attempt to
+ process a script.
+ */
+
+ new netrexx.lang.BadArgumentException();
+ }
+ /**
+ * Return an object from an extension.
+ * @param object object from which to call our static method
+ * @param method The name of the method to call.
+ * @param args an array of arguments to be
+ * passed to the extension, which may be either
+ * Vectors of Nodes, or Strings.
+ */
+ public Object call (Object object, String method, Object[] args)
+ throws BSFException
+ {
+ throw new BSFException(BSFException.REASON_UNSUPPORTED_FEATURE,
+ "NetRexx doesn't currently support call()",
+ null);
+ }
+ /**
+ * Invoke a static method.
+ * @param rexxclass Class to invoke the method against
+ * @param method The name of the method to call.
+ * @param args an array of arguments to be
+ * passed to the extension, which may be either
+ * Vectors of Nodes, or Strings.
+ */
+ Object callStatic(Class rexxclass, String method, Object[] args)
+ throws BSFException
+ {
+ //***** ISSUE: Currently supports only static methods
+ Object retval = null;
+ try
+ {
+ if (rexxclass != null)
+ {
+ //***** This should call the lookup used in BML, for typesafety
+ Class[] argtypes=new Class[args.length];
+ for(int i=0;i<args.length;++i)
+ argtypes[i]=args[i].getClass();
+
+ Method m=MethodUtils.getMethod(rexxclass, method, argtypes);
+ retval=m.invoke(null,args);
+ }
+ else
+ {
+ logger.error("NetRexxEngine: ERROR: rexxclass==null!");
+ }
+ }
+ catch(Exception e)
+ {
+ e.printStackTrace ();
+ if (e instanceof InvocationTargetException)
+ {
+ Throwable t = ((InvocationTargetException)e).getTargetException ();
+ t.printStackTrace ();
+ }
+ throw new BSFException (BSFException.REASON_IO_ERROR,
+ e.getMessage (),
+ e);
+ }
+ return retval;
+ }
+ public void declareBean (BSFDeclaredBean bean) throws BSFException {}
+ /**
+ * Override impl of execute. In NetRexx, methods which do not wish
+ * to return a value should be invoked via exec, which will cause them
+ * to be generated without the "returns" clause.
+ * Those which wish to return a value should call eval instead.
+ * which will add "returns java.lang.Object" to the header.
+ *
+ * Note: It would be nice to have the "real" return type avaialable, so
+ * we could do something more type-safe than Object, and so we could
+ * return primitive types without having to enclose them in their
+ * object wrappers. BSF does not currently support that concept.
+ */
+ public Object eval (String source, int lineNo, int columnNo,
+ Object script)
+ throws BSFException
+ {
+ return execEvalShared(source, lineNo, columnNo, script,true);
+ }
+ /**
+ * Override impl of execute. In NetRexx, methods which do not wish
+ * to return a value should be invoked via exec, which will cause them
+ * to be generated without the "returns" clause.
+ * Those which wish to return a value should call eval instead.
+ * which will add "returns java.lang.Object" to the header.
+ */
+ public void exec (String source, int lineNo, int columnNo,
+ Object script)
+ throws BSFException
+ {
+ execEvalShared(source, lineNo, columnNo, script,false);
+ }
+ /**
+ * This is shared code for the exec() and eval() operations. It will
+ * evaluate a string containing a NetRexx method body -- which may be
+ * as simple as a single return statement.
+ * It should store the "bsf" handle where the
+ * script can get to it, for callback purposes.
+ * <p>
+ * Note that NetRexx compilation imposes serious overhead -- 11 seconds for
+ * the first compile, about 3 thereafter -- but in exchange you get
+ * Java-like speeds once the classes have been created (minus the cache
+ * lookup cost).
+ * <p>
+ * Nobody knows whether javac is threadsafe.
+ * I'm going to serialize access to the compilers to protect it.
+ */
+ public Object execEvalShared (String source, int lineNo, int columnNo,
+ Object oscript,boolean returnsObject)
+ throws BSFException
+ {
+ Object retval=null;
+ String classname=null;
+ GeneratedFile gf=null;
+
+ // Moved into the exec process; see comment above.
+ Class rexxclass=null;
+
+ String basescript=oscript.toString();
+ String script=basescript; // May be altered by $$CLASSNAME$$ expansion
+
+ try {
+ // Do we already have a class exactly matching this code?
+ rexxclass=(Class)codeToClass.get(basescript);
+
+ if(rexxclass!=null)
+
+ {
+ logger.debug("NetRexxEngine: Found pre-compiled class" +
+ " for script '" + basescript + "'");
+ classname=rexxclass.getName();
+ }
+ else
+ {
+ gf=openUniqueFile(tempDir,"BSFNetRexx",".nrx");
+ if(gf==null)
+ throw new BSFException("couldn't create NetRexx scratchfile");
+
+ // Obtain classname
+ classname=gf.className;
+
+ // Decide whether to declare a return type
+ String returnsDecl="";
+ if(returnsObject)
+ returnsDecl="returns java.lang.Object";
+
+ // Write the kluge header to the file.
+ // ***** By doing so we give up the ability to use Property blocks.
+ gf.fos.write(("class "+classname+";\n")
+ .getBytes());
+ gf.fos.write(
+ ("method BSFNetRexxEngineEntry(bsf=org.apache.bsf.util.BSFFunctions) "+
+ " public static "+returnsDecl+";\n")
+ .getBytes());
+
+ // Edit the script to replace placeholder with the generated
+ // classname. Note that this occurs _after_ the cache was
+ // checked!
+ int startpoint,endpoint;
+ if((startpoint=script.indexOf(placeholder))>=0)
+ {
+ StringBuffer changed=new StringBuffer();
+ for(;
+ startpoint>=0;
+ startpoint=script.indexOf(placeholder,startpoint))
+ {
+ changed.setLength(0); // Reset for 2nd pass or later
+ if(startpoint>0)
+ changed.append(script.substring(0,startpoint));
+ changed.append(classname);
+ endpoint=startpoint+placeholder.length();
+ if(endpoint<script.length())
+ changed.append(script.substring(endpoint));
+ script=changed.toString();
+ }
+ }
+
+ BSFDeclaredBean tempBean;
+ String className;
+
+ for (int i = 0; i < declaredBeans.size (); i++)
+ {
+ tempBean = (BSFDeclaredBean) declaredBeans.elementAt (i);
+ className = StringUtils.getClassName (tempBean.type);
+
+ gf.fos.write ((tempBean.name + " =" + className + " bsf.lookupBean(\"" +
+ tempBean.name + "\");").getBytes());
+ }
+
+ if(returnsObject)
+ gf.fos.write("return ".getBytes());
+
+ // Copy the input to the file.
+ // Assumes all available -- probably mistake, but same as
+ // other engines.
+ gf.fos.write(script.getBytes());
+ gf.fos.close();
+
+ logger.debug("NetRexxEngine: wrote temp file " +
+ gf.file.getPath () + ", now compiling");
+
+ // Compile through Java to .class file
+ String command=gf.file.getPath(); //classname;
+ if (logger.isDebugEnabled()) {
+ command += " -verbose4";
+ } else {
+ command += " -noverbose";
+ command += " -noconsole";
+ }
+
+ netrexx.lang.Rexx cmdline= new netrexx.lang.Rexx(command);
+ int retValue;
+
+ // May not be threadsafe. Serialize access on static object:
+ synchronized(serializeCompilation)
+ {
+ // compile to a .java file
+ retValue =
+ COM.ibm.netrexx.process.NetRexxC.main(cmdline,
+ new PrintWriter(System.err));
+ }
+
+ // Check if there were errors while compiling the Rexx code.
+ if (retValue == 2)
+ {
+ throw new BSFException(BSFException.REASON_EXECUTION_ERROR,
+ "There were NetRexx errors.");
+ }
+
+ // Load class.
+ logger.debug("NetRexxEngine: loading class "+classname);
+ rexxclass=EngineUtils.loadClass (mgr, classname);
+
+ // Stash class for reuse
+ codeToClass.put(basescript,rexxclass);
+ }
+
+ Object[] args={mgrfuncs};
+ retval=callStatic(rexxclass, "BSFNetRexxEngineEntry",args);
+ }
+ catch (BSFException e)
+ {
+ // Just forward the exception on.
+ throw e;
+ }
+ catch(Exception e)
+ {
+ e.printStackTrace ();
+ if (e instanceof InvocationTargetException)
+ {
+ Throwable t = ((InvocationTargetException)e).getTargetException ();
+ t.printStackTrace ();
+ }
+ throw new BSFException (BSFException.REASON_IO_ERROR,
+ e.getMessage (), e);
+ }
+ finally
+ {
+ // Cleanup: delete the .nrx and .class files
+ // (if any) generated by NetRexx Trace requests.
+
+ if(gf!=null && gf.file!=null && gf.file.exists())
+ gf.file.delete(); // .nrx file
+
+ if(classname!=null)
+ {
+ // Generated src
+ File file=new File(tempDir+File.separatorChar+classname+".java");
+ if(file.exists())
+ file.delete();
+
+ // Generated class
+ file=new File(classname+".class");
+ if(file.exists())
+ file.delete();
+
+ // Can this be done without disrupting trace?
+ file=new File(tempDir+File.separatorChar+classname+".crossref");
+ if(file.exists())
+ file.delete();
+
+ // Search for and clean up minor classes, classname$xxx.class
+ file=new File(tempDir);
+ minorPrefix=classname+"$"; // Indirect arg to filter
+ String[] minor_classfiles=
+ file.list(
+ // ANONYMOUS CLASS for filter:
+ new FilenameFilter()
+ {
+ // Starts with classname$ and ends with .class
+ public boolean accept(File dir,String name)
+ {
+ return
+ (0==name.indexOf(minorPrefix))
+ &&
+ (name.lastIndexOf(".class")==name.length()-6)
+ ;
+ }
+ }
+ );
+ if(minor_classfiles!=null)
+ for(int i=minor_classfiles.length;i>0;)
+ {
+ file=new File(minor_classfiles[--i]);
+ file.delete();
+ }
+ }
+ }
+
+ return retval;
+ }
+ public void initialize(BSFManager mgr, String lang,Vector declaredBeans)
+ throws BSFException
+ {
+ super.initialize(mgr, lang, declaredBeans);
+ mgrfuncs = new BSFFunctions (mgr, this);
+ }
+private GeneratedFile openUniqueFile(String directory,String prefix,String suffix)
+ {
+ File file=null,obj=null;
+ FileOutputStream fos=null;
+ int max=1000; // Don't try forever
+ GeneratedFile gf=null;
+ int i;
+ String className = null;
+ for(i=max,++uniqueFileOffset;
+ fos==null && i>0;
+ --i,++uniqueFileOffset)
+ {
+ // Probably a timing hazard here... ***************
+ try
+ {
+ className = prefix+uniqueFileOffset;
+ file=new File(directory+File.separatorChar+className+suffix);
+ obj=new File(directory+File.separatorChar+className+".class");
+ if(file!=null && !file.exists() & obj!=null & !obj.exists())
+ fos=new FileOutputStream(file);
+ }
+ catch(Exception e)
+ {
+ // File could not be opened for write, or Security Exception
+ // was thrown. If someone else created the file before we could
+ // open it, that's probably a threading conflict and we don't
+ // bother reporting it.
+ if(!file.exists())
+ {
+ logger.error("openUniqueFile: unexpected "+e);
+ }
+ }
+ }
+ if(fos==null)
+ logger.error("openUniqueFile: Failed "+max+"attempts.");
+ else
+ gf=new GeneratedFile(file,fos,className);
+ return gf;
+ }
+
+ public void undeclareBean (BSFDeclaredBean bean) throws BSFException {}
+}
diff --git a/src/main/java/org/apache/bsf/engines/xslt/XSLTEngine.java b/src/main/java/org/apache/bsf/engines/xslt/XSLTEngine.java
index a4d6271..cf1e70d 100644
--- a/src/main/java/org/apache/bsf/engines/xslt/XSLTEngine.java
+++ b/src/main/java/org/apache/bsf/engines/xslt/XSLTEngine.java
@@ -1,203 +1,198 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.engines.xslt;
-
-import java.io.File;
-import java.io.Reader;
-import java.io.StringReader;
-import java.net.URL;
-import java.util.Vector;
-
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamSource;
-
-import org.apache.bsf.BSFDeclaredBean;
-import org.apache.bsf.BSFException;
-import org.apache.bsf.BSFManager;
-import org.apache.bsf.BSF_Log;
-import org.apache.bsf.BSF_LogFactory;
-import org.apache.bsf.util.BSFEngineImpl;
-import org.apache.bsf.util.BSFFunctions;
-import org.apache.xpath.objects.XObject;
-import org.w3c.dom.Node;
-
-/**
- * Xerces XSLT interface to BSF. Requires Xalan and Xerces from Apache.
- *
- * This integration uses the BSF registry to pass in any src document
- * and stylesheet base URI that the user may wish to set.
- *
- * @author Sanjiva Weerawarana
- * @author Sam Ruby
- *
- * Re-implemented for the Xalan 2 codebase
- *
- * @author Victor J. Orlikowski
- * @author Rony G. Flatscher (added BSF_Log[Factory] to allow BSF to run without org.apache.commons.logging present)
- */
-public class XSLTEngine extends BSFEngineImpl {
- TransformerFactory tFactory;
- Transformer transformer;
-
- // Log logger = LogFactory.getLog(this.getClass().getName());
- BSF_Log logger = null;
-
- public XSLTEngine ()
- {
- // handle logger
- logger = BSF_LogFactory.getLog(this.getClass().getName());
- }
-
-
- /**
- * call the named method of the given object.
- */
- public Object call (final Object object, final String method, final Object[] args)
- throws BSFException {
- throw new BSFException (BSFException.REASON_UNSUPPORTED_FEATURE,
- "BSF:XSLTEngine can't call methods");
- }
-
- /**
- * Declare a bean by setting it as a parameter
- */
- public void declareBean (final BSFDeclaredBean bean) throws BSFException {
- transformer.setParameter (bean.name, new XObject (bean.bean));
- }
-
- /**
- * Evaluate an expression. In this case, an expression is assumed
- * to be a stylesheet of the template style (see the XSLT spec).
- */
- public Object eval (final String source, final int lineNo, final int columnNo,
- final Object oscript) throws BSFException {
- // get the style base URI (the place from where Xerces XSLT will
- // look for imported/included files and referenced docs): if a
- // bean named "xslt:styleBaseURI" is registered, then cvt it
- // to a string and use that. Otherwise use ".", which means the
- // base is the directory where the process is running from
- final Object sbObj = mgr.lookupBean ("xslt:styleBaseURI");
- final String styleBaseURI = (sbObj == null) ? "." : sbObj.toString ();
-
- // Locate the stylesheet.
- StreamSource styleSource;
-
- styleSource =
- new StreamSource(new StringReader(oscript.toString ()));
- styleSource.setSystemId(styleBaseURI);
-
- try {
- transformer = tFactory.newTransformer(styleSource);
- } catch (final Exception e) {
- logger.error("Exception from Xerces XSLT:", e);
- throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
- "Exception from Xerces XSLT: " + e, e);
- }
-
- // get the src to work on: if a bean named "xslt:src" is registered
- // and its a Node, then use it as the source. If its not a Node, then
- // if its a URL parse it, if not treat it as a file and make a URL and
- // parse it and go. If no xslt:src is found, use an empty document
- // (stylesheet is treated as a literal result element stylesheet)
- final Object srcObj = mgr.lookupBean ("xslt:src");
- Object xis = null;
- if (srcObj != null) {
- if (srcObj instanceof Node) {
- xis = new DOMSource((Node)srcObj);
- } else {
- try {
- String mesg = "as anything";
- if (srcObj instanceof Reader) {
- xis = new StreamSource ((Reader) srcObj);
- mesg = "as a Reader";
- } else if (srcObj instanceof File) {
- xis = new StreamSource ((File) srcObj);
- mesg = "as a file";
- } else {
- final String srcObjstr=srcObj.toString();
- xis = new StreamSource (new StringReader(srcObjstr));
- if (srcObj instanceof URL) {
- mesg = "as a URL";
- } else {
- ((StreamSource) xis).setPublicId (srcObjstr);
- mesg = "as an XML string";
- }
- }
-
- if (xis == null) {
- throw new Exception ("Unable to get input from '" +
- srcObj + "' " + mesg);
- }
- } catch (final Exception e) {
- throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
- "BSF:XSLTEngine: unable to get " +
- "input from '" + srcObj + "' as XML", e);
- }
- }
- } else {
- // create an empty document - real src must come into the
- // stylesheet using "doc(...)" [see XSLT spec] or the stylesheet
- // must be of literal result element type
- xis = new StreamSource();
- }
-
- // set all declared beans as parameters.
- for (int i = 0; i < declaredBeans.size (); i++) {
- final BSFDeclaredBean b = (BSFDeclaredBean) declaredBeans.elementAt (i);
- transformer.setParameter (b.name, new XObject (b.bean));
- }
-
- // declare a "bsf" parameter which is the BSF handle so that
- // the script can do BSF stuff if it wants to
- transformer.setParameter ("bsf",
- new XObject (new BSFFunctions (mgr, this)));
-
- // do it
- try {
- final DOMResult result = new DOMResult();
- transformer.transform ((StreamSource) xis, result);
- return new XSLTResultNode (result.getNode());
- } catch (final Exception e) {
- throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
- "exception while eval'ing XSLT script" + e, e);
- }
- }
-
- /**
- * Initialize the engine.
- */
- public void initialize (final BSFManager mgr, final String lang,
- final Vector declaredBeans) throws BSFException {
- super.initialize (mgr, lang, declaredBeans);
-
- tFactory = TransformerFactory.newInstance();
- }
-
- /**
- * Undeclare a bean by setting he parameter represeting it to null
- */
- public void undeclareBean (final BSFDeclaredBean bean) throws BSFException {
- // Cannot clear only one parameter in Xalan 2, so we set it to null
- if ((transformer.getParameter (bean.name)) != null) {
- transformer.setParameter (bean.name, null);
- }
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.engines.xslt;
+
+import java.io.File;
+import java.io.Reader;
+import java.io.StringReader;
+import java.net.URL;
+import java.util.Vector;
+
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamSource;
+
+import org.apache.bsf.BSFDeclaredBean;
+import org.apache.bsf.BSFException;
+import org.apache.bsf.BSFManager;
+import org.apache.bsf.BSF_Log;
+import org.apache.bsf.BSF_LogFactory;
+import org.apache.bsf.util.BSFEngineImpl;
+import org.apache.bsf.util.BSFFunctions;
+import org.apache.xpath.objects.XObject;
+import org.w3c.dom.Node;
+
+/**
+ * Xerces XSLT interface to BSF. Requires Xalan and Xerces from Apache.
+ *
+ * This integration uses the BSF registry to pass in any src document
+ * and stylesheet base URI that the user may wish to set.
+ *
+ * Re-implemented for the Xalan 2 codebase
+ *
+ */
+public class XSLTEngine extends BSFEngineImpl {
+ TransformerFactory tFactory;
+ Transformer transformer;
+
+ // Log logger = LogFactory.getLog(this.getClass().getName());
+ BSF_Log logger = null;
+
+ public XSLTEngine ()
+ {
+ // handle logger
+ logger = BSF_LogFactory.getLog(this.getClass().getName());
+ }
+
+
+ /**
+ * call the named method of the given object.
+ */
+ public Object call (final Object object, final String method, final Object[] args)
+ throws BSFException {
+ throw new BSFException (BSFException.REASON_UNSUPPORTED_FEATURE,
+ "BSF:XSLTEngine can't call methods");
+ }
+
+ /**
+ * Declare a bean by setting it as a parameter
+ */
+ public void declareBean (final BSFDeclaredBean bean) throws BSFException {
+ transformer.setParameter (bean.name, new XObject (bean.bean));
+ }
+
+ /**
+ * Evaluate an expression. In this case, an expression is assumed
+ * to be a stylesheet of the template style (see the XSLT spec).
+ */
+ public Object eval (final String source, final int lineNo, final int columnNo,
+ final Object oscript) throws BSFException {
+ // get the style base URI (the place from where Xerces XSLT will
+ // look for imported/included files and referenced docs): if a
+ // bean named "xslt:styleBaseURI" is registered, then cvt it
+ // to a string and use that. Otherwise use ".", which means the
+ // base is the directory where the process is running from
+ final Object sbObj = mgr.lookupBean ("xslt:styleBaseURI");
+ final String styleBaseURI = (sbObj == null) ? "." : sbObj.toString ();
+
+ // Locate the stylesheet.
+ StreamSource styleSource;
+
+ styleSource =
+ new StreamSource(new StringReader(oscript.toString ()));
+ styleSource.setSystemId(styleBaseURI);
+
+ try {
+ transformer = tFactory.newTransformer(styleSource);
+ } catch (final Exception e) {
+ logger.error("Exception from Xerces XSLT:", e);
+ throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
+ "Exception from Xerces XSLT: " + e, e);
+ }
+
+ // get the src to work on: if a bean named "xslt:src" is registered
+ // and its a Node, then use it as the source. If its not a Node, then
+ // if its a URL parse it, if not treat it as a file and make a URL and
+ // parse it and go. If no xslt:src is found, use an empty document
+ // (stylesheet is treated as a literal result element stylesheet)
+ final Object srcObj = mgr.lookupBean ("xslt:src");
+ Object xis = null;
+ if (srcObj != null) {
+ if (srcObj instanceof Node) {
+ xis = new DOMSource((Node)srcObj);
+ } else {
+ try {
+ String mesg = "as anything";
+ if (srcObj instanceof Reader) {
+ xis = new StreamSource ((Reader) srcObj);
+ mesg = "as a Reader";
+ } else if (srcObj instanceof File) {
+ xis = new StreamSource ((File) srcObj);
+ mesg = "as a file";
+ } else {
+ final String srcObjstr=srcObj.toString();
+ xis = new StreamSource (new StringReader(srcObjstr));
+ if (srcObj instanceof URL) {
+ mesg = "as a URL";
+ } else {
+ ((StreamSource) xis).setPublicId (srcObjstr);
+ mesg = "as an XML string";
+ }
+ }
+
+ if (xis == null) {
+ throw new Exception ("Unable to get input from '" +
+ srcObj + "' " + mesg);
+ }
+ } catch (final Exception e) {
+ throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
+ "BSF:XSLTEngine: unable to get " +
+ "input from '" + srcObj + "' as XML", e);
+ }
+ }
+ } else {
+ // create an empty document - real src must come into the
+ // stylesheet using "doc(...)" [see XSLT spec] or the stylesheet
+ // must be of literal result element type
+ xis = new StreamSource();
+ }
+
+ // set all declared beans as parameters.
+ for (int i = 0; i < declaredBeans.size (); i++) {
+ final BSFDeclaredBean b = (BSFDeclaredBean) declaredBeans.elementAt (i);
+ transformer.setParameter (b.name, new XObject (b.bean));
+ }
+
+ // declare a "bsf" parameter which is the BSF handle so that
+ // the script can do BSF stuff if it wants to
+ transformer.setParameter ("bsf",
+ new XObject (new BSFFunctions (mgr, this)));
+
+ // do it
+ try {
+ final DOMResult result = new DOMResult();
+ transformer.transform ((StreamSource) xis, result);
+ return new XSLTResultNode (result.getNode());
+ } catch (final Exception e) {
+ throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
+ "exception while eval'ing XSLT script" + e, e);
+ }
+ }
+
+ /**
+ * Initialize the engine.
+ */
+ public void initialize (final BSFManager mgr, final String lang,
+ final Vector declaredBeans) throws BSFException {
+ super.initialize (mgr, lang, declaredBeans);
+
+ tFactory = TransformerFactory.newInstance();
+ }
+
+ /**
+ * Undeclare a bean by setting he parameter represeting it to null
+ */
+ public void undeclareBean (final BSFDeclaredBean bean) throws BSFException {
+ // Cannot clear only one parameter in Xalan 2, so we set it to null
+ if ((transformer.getParameter (bean.name)) != null) {
+ transformer.setParameter (bean.name, null);
+ }
+ }
+}
diff --git a/src/main/java/org/apache/bsf/util/BSFClassLoader.java b/src/main/java/org/apache/bsf/util/BSFClassLoader.java
index dd85fc7..a9c60ab 100644
--- a/src/main/java/org/apache/bsf/util/BSFClassLoader.java
+++ b/src/main/java/org/apache/bsf/util/BSFClassLoader.java
@@ -1,76 +1,74 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.util;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.Hashtable;
-
-/**
- * This class loader knows to load a class from the tempDir dir
- * of the environment of the given manager.
- *
- * @author Sanjiva Weerawarana
- */
-class BSFClassLoader extends ClassLoader {
- Hashtable cache = new Hashtable ();
- String tempDir = ".";
-
- // note the non-public constructor - this is only avail within
- // this package.
- BSFClassLoader () {
- }
- public synchronized Class loadClass (final String name, final boolean resolve)
- throws ClassNotFoundException {
- Class c = (Class) cache.get (name);
- if (c == null) {
- // is it a system class
- try {
- c = findSystemClass (name);
- cache.put (name, c);
- return c;
- } catch (final ClassNotFoundException e) {
- // nope
- }
- try {
- final byte[] data = loadClassData (name);
- c = defineClass (name, data, 0, data.length);
- cache.put (name, c);
- } catch (final Exception e) {
- e.printStackTrace ();
- throw new ClassNotFoundException ("unable to resolve class '" +
- name + "'");
- }
- }
- if (resolve) {
- resolveClass (c);
- }
- return c;
- }
- private byte[] loadClassData (final String name) throws Exception {
- final String fileName = tempDir + File.separatorChar + name + ".class";
- final FileInputStream fi = new FileInputStream (fileName);
- final byte[] data = new byte[fi.available ()];
- fi.read (data);
- fi.close();
- return data;
- }
- public void setTempDir (final String tempDir) {
- this.tempDir = tempDir;
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.Hashtable;
+
+/**
+ * This class loader knows to load a class from the tempDir dir
+ * of the environment of the given manager.
+ */
+class BSFClassLoader extends ClassLoader {
+ Hashtable cache = new Hashtable ();
+ String tempDir = ".";
+
+ // note the non-public constructor - this is only avail within
+ // this package.
+ BSFClassLoader () {
+ }
+ public synchronized Class loadClass (final String name, final boolean resolve)
+ throws ClassNotFoundException {
+ Class c = (Class) cache.get (name);
+ if (c == null) {
+ // is it a system class
+ try {
+ c = findSystemClass (name);
+ cache.put (name, c);
+ return c;
+ } catch (final ClassNotFoundException e) {
+ // nope
+ }
+ try {
+ final byte[] data = loadClassData (name);
+ c = defineClass (name, data, 0, data.length);
+ cache.put (name, c);
+ } catch (final Exception e) {
+ e.printStackTrace ();
+ throw new ClassNotFoundException ("unable to resolve class '" +
+ name + "'");
+ }
+ }
+ if (resolve) {
+ resolveClass (c);
+ }
+ return c;
+ }
+ private byte[] loadClassData (final String name) throws Exception {
+ final String fileName = tempDir + File.separatorChar + name + ".class";
+ final FileInputStream fi = new FileInputStream (fileName);
+ final byte[] data = new byte[fi.available ()];
+ fi.read (data);
+ fi.close();
+ return data;
+ }
+ public void setTempDir (final String tempDir) {
+ this.tempDir = tempDir;
+ }
+}
diff --git a/src/main/java/org/apache/bsf/util/BSFEngineImpl.java b/src/main/java/org/apache/bsf/util/BSFEngineImpl.java
index 014f8b0..4ccb955 100644
--- a/src/main/java/org/apache/bsf/util/BSFEngineImpl.java
+++ b/src/main/java/org/apache/bsf/util/BSFEngineImpl.java
@@ -1,204 +1,200 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.util;
-
-import java.beans.PropertyChangeEvent;
-import java.util.Vector;
-
-import org.apache.bsf.BSFDeclaredBean;
-import org.apache.bsf.BSFEngine;
-import org.apache.bsf.BSFException;
-import org.apache.bsf.BSFManager;
-
-/**
- * This is a base implementation of the BSFEngine interface which
- * engine implementations may choose to extend to get the basic
- * methods of the interface implemented.
- * <p>
- *
- * @author Sanjiva Weerawarana
- * @author Olivier Gruber (added original debugging support)
- */
-
-public abstract class BSFEngineImpl implements BSFEngine {
-
- protected BSFManager mgr; // my manager
- protected String lang; // my language string
- protected Vector declaredBeans; // BSFDeclaredBeans
- protected String classPath;
- protected String tempDir;
- protected ClassLoader classLoader;
-
- /**
- * Default impl of apply - calls eval ignoring parameters and returns
- * the result.
- */
- public Object apply(final String source, final int lineNo, final int columnNo,
- final Object funcBody, final Vector paramNames, final Vector arguments)
- throws BSFException {
- return eval(source, lineNo, columnNo, funcBody);
- }
-
- /**
- * Default impl of compileApply - calls compileExpr ignoring parameters.
- */
- public void compileApply(final String source, final int lineNo, final int columnNo,
- final Object funcBody, final Vector paramNames,
- final Vector arguments, final CodeBuffer cb)
- throws BSFException {
- compileExpr(source, lineNo, columnNo, funcBody, cb);
- }
-
- /**
- * Default impl of compileExpr - generates code that'll create a new
- * manager, evaluate the expression, and return the value.
- */
- public void compileExpr(final String source, final int lineNo, final int columnNo,
- final Object expr, final CodeBuffer cb) throws BSFException {
- ObjInfo bsfInfo = cb.getSymbol("bsf");
-
- if (bsfInfo == null) {
- bsfInfo = new ObjInfo(BSFManager.class, "bsf");
- cb.addFieldDeclaration("org.apache.bsf.BSFManager bsf = " +
- "new org.apache.bsf.BSFManager();");
- cb.putSymbol("bsf", bsfInfo);
- }
-
- String evalString = bsfInfo.objName + ".eval(\"" + lang + "\", ";
- evalString += "request.getRequestURI(), " + lineNo + ", " + columnNo;
- evalString += "," + StringUtils.lineSeparator;
- evalString += StringUtils.getSafeString(expr.toString()) + ")";
-
- final ObjInfo oldRet = cb.getFinalServiceMethodStatement();
-
- if (oldRet != null && oldRet.isExecutable()) {
- cb.addServiceMethodStatement(oldRet.objName + ";");
- }
-
- cb.setFinalServiceMethodStatement(new ObjInfo(Object.class,
- evalString));
-
- cb.addServiceMethodException("org.apache.bsf.BSFException");
- }
-
- /**
- * Default impl of compileScript - generates code that'll create a new
- * manager, and execute the script.
- */
- public void compileScript(final String source, final int lineNo, final int columnNo,
- final Object script, final CodeBuffer cb)
- throws BSFException {
- ObjInfo bsfInfo = cb.getSymbol("bsf");
-
- if (bsfInfo == null) {
- bsfInfo = new ObjInfo(BSFManager.class, "bsf");
- cb.addFieldDeclaration("org.apache.bsf.BSFManager bsf = " +
- "new org.apache.bsf.BSFManager();");
- cb.putSymbol("bsf", bsfInfo);
- }
-
- String execString = bsfInfo.objName + ".exec(\"" + lang + "\", ";
- execString += "request.getRequestURI(), " + lineNo + ", " + columnNo;
- execString += "," + StringUtils.lineSeparator;
- execString += StringUtils.getSafeString(script.toString()) + ")";
-
- final ObjInfo oldRet = cb.getFinalServiceMethodStatement();
-
- if (oldRet != null && oldRet.isExecutable()) {
- cb.addServiceMethodStatement(oldRet.objName + ";");
- }
-
- cb.setFinalServiceMethodStatement(new ObjInfo(void.class, execString));
-
- cb.addServiceMethodException("org.apache.bsf.BSFException");
- }
-
- public void declareBean(final BSFDeclaredBean bean) throws BSFException {
- throw new BSFException(BSFException.REASON_UNSUPPORTED_FEATURE,
- "language " + lang +
- " does not support declareBean(...).");
- }
-
- /**
- * Default impl of execute - calls eval and ignores the result.
- */
- public void exec(final String source, final int lineNo, final int columnNo, final Object script)
- throws BSFException {
- eval(source, lineNo, columnNo, script);
- }
-
- /**
- * Default impl of interactive execution - calls eval and ignores the result.
- */
- public void iexec(final String source, final int lineNo, final int columnNo, final Object script)
- throws BSFException {
- eval(source, lineNo, columnNo, script);
- }
-
- /**
- * initialize the engine; called right after construction by
- * the manager. Declared beans are simply kept in a vector and
- * that's it. Subclasses must do whatever they want with it.
- */
- public void initialize(final BSFManager mgr, final String lang, final Vector declaredBeans)
- throws BSFException {
-
- this.mgr = mgr;
- this.lang = lang;
- this.declaredBeans = declaredBeans;
-
- // initialize my properties from those of the manager. It'll send
- // propagate change events to me
- this.classPath = mgr.getClassPath();
- this.tempDir = mgr.getTempDir();
- this.classLoader = mgr.getClassLoader();
- }
-
- /**
- * Receive property change events from the manager and update my fields
- * as needed.
- *
- * @param e PropertyChange event with the change data
- */
- public void propertyChange(final PropertyChangeEvent e) {
- final String name = e.getPropertyName();
- final Object value = e.getNewValue();
-
- if (name.equals("classPath")) {
- classPath = (String) value;
- }
- else if (name.equals("tempDir")) {
- tempDir = (String) value;
- }
- else if (name.equals("classLoader")) {
- classLoader = (ClassLoader) value;
- }
- }
-
- public void terminate() {
- mgr = null;
- declaredBeans = null;
- classLoader = null;
- }
-
- public void undeclareBean(final BSFDeclaredBean bean) throws BSFException {
- throw new BSFException(BSFException.REASON_UNSUPPORTED_FEATURE,
- "language " + lang +
- " does not support undeclareBean(...).");
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.util;
+
+import java.beans.PropertyChangeEvent;
+import java.util.Vector;
+
+import org.apache.bsf.BSFDeclaredBean;
+import org.apache.bsf.BSFEngine;
+import org.apache.bsf.BSFException;
+import org.apache.bsf.BSFManager;
+
+/**
+ * This is a base implementation of the BSFEngine interface which
+ * engine implementations may choose to extend to get the basic
+ * methods of the interface implemented.
+ */
+
+public abstract class BSFEngineImpl implements BSFEngine {
+
+ protected BSFManager mgr; // my manager
+ protected String lang; // my language string
+ protected Vector declaredBeans; // BSFDeclaredBeans
+ protected String classPath;
+ protected String tempDir;
+ protected ClassLoader classLoader;
+
+ /**
+ * Default impl of apply - calls eval ignoring parameters and returns
+ * the result.
+ */
+ public Object apply(final String source, final int lineNo, final int columnNo,
+ final Object funcBody, final Vector paramNames, final Vector arguments)
+ throws BSFException {
+ return eval(source, lineNo, columnNo, funcBody);
+ }
+
+ /**
+ * Default impl of compileApply - calls compileExpr ignoring parameters.
+ */
+ public void compileApply(final String source, final int lineNo, final int columnNo,
+ final Object funcBody, final Vector paramNames,
+ final Vector arguments, final CodeBuffer cb)
+ throws BSFException {
+ compileExpr(source, lineNo, columnNo, funcBody, cb);
+ }
+
+ /**
+ * Default impl of compileExpr - generates code that'll create a new
+ * manager, evaluate the expression, and return the value.
+ */
+ public void compileExpr(final String source, final int lineNo, final int columnNo,
+ final Object expr, final CodeBuffer cb) throws BSFException {
+ ObjInfo bsfInfo = cb.getSymbol("bsf");
+
+ if (bsfInfo == null) {
+ bsfInfo = new ObjInfo(BSFManager.class, "bsf");
+ cb.addFieldDeclaration("org.apache.bsf.BSFManager bsf = " +
+ "new org.apache.bsf.BSFManager();");
+ cb.putSymbol("bsf", bsfInfo);
+ }
+
+ String evalString = bsfInfo.objName + ".eval(\"" + lang + "\", ";
+ evalString += "request.getRequestURI(), " + lineNo + ", " + columnNo;
+ evalString += "," + StringUtils.lineSeparator;
+ evalString += StringUtils.getSafeString(expr.toString()) + ")";
+
+ final ObjInfo oldRet = cb.getFinalServiceMethodStatement();
+
+ if (oldRet != null && oldRet.isExecutable()) {
+ cb.addServiceMethodStatement(oldRet.objName + ";");
+ }
+
+ cb.setFinalServiceMethodStatement(new ObjInfo(Object.class,
+ evalString));
+
+ cb.addServiceMethodException("org.apache.bsf.BSFException");
+ }
+
+ /**
+ * Default impl of compileScript - generates code that'll create a new
+ * manager, and execute the script.
+ */
+ public void compileScript(final String source, final int lineNo, final int columnNo,
+ final Object script, final CodeBuffer cb)
+ throws BSFException {
+ ObjInfo bsfInfo = cb.getSymbol("bsf");
+
+ if (bsfInfo == null) {
+ bsfInfo = new ObjInfo(BSFManager.class, "bsf");
+ cb.addFieldDeclaration("org.apache.bsf.BSFManager bsf = " +
+ "new org.apache.bsf.BSFManager();");
+ cb.putSymbol("bsf", bsfInfo);
+ }
+
+ String execString = bsfInfo.objName + ".exec(\"" + lang + "\", ";
+ execString += "request.getRequestURI(), " + lineNo + ", " + columnNo;
+ execString += "," + StringUtils.lineSeparator;
+ execString += StringUtils.getSafeString(script.toString()) + ")";
+
+ final ObjInfo oldRet = cb.getFinalServiceMethodStatement();
+
+ if (oldRet != null && oldRet.isExecutable()) {
+ cb.addServiceMethodStatement(oldRet.objName + ";");
+ }
+
+ cb.setFinalServiceMethodStatement(new ObjInfo(void.class, execString));
+
+ cb.addServiceMethodException("org.apache.bsf.BSFException");
+ }
+
+ public void declareBean(final BSFDeclaredBean bean) throws BSFException {
+ throw new BSFException(BSFException.REASON_UNSUPPORTED_FEATURE,
+ "language " + lang +
+ " does not support declareBean(...).");
+ }
+
+ /**
+ * Default impl of execute - calls eval and ignores the result.
+ */
+ public void exec(final String source, final int lineNo, final int columnNo, final Object script)
+ throws BSFException {
+ eval(source, lineNo, columnNo, script);
+ }
+
+ /**
+ * Default impl of interactive execution - calls eval and ignores the result.
+ */
+ public void iexec(final String source, final int lineNo, final int columnNo, final Object script)
+ throws BSFException {
+ eval(source, lineNo, columnNo, script);
+ }
+
+ /**
+ * initialize the engine; called right after construction by
+ * the manager. Declared beans are simply kept in a vector and
+ * that's it. Subclasses must do whatever they want with it.
+ */
+ public void initialize(final BSFManager mgr, final String lang, final Vector declaredBeans)
+ throws BSFException {
+
+ this.mgr = mgr;
+ this.lang = lang;
+ this.declaredBeans = declaredBeans;
+
+ // initialize my properties from those of the manager. It'll send
+ // propagate change events to me
+ this.classPath = mgr.getClassPath();
+ this.tempDir = mgr.getTempDir();
+ this.classLoader = mgr.getClassLoader();
+ }
+
+ /**
+ * Receive property change events from the manager and update my fields
+ * as needed.
+ *
+ * @param e PropertyChange event with the change data
+ */
+ public void propertyChange(final PropertyChangeEvent e) {
+ final String name = e.getPropertyName();
+ final Object value = e.getNewValue();
+
+ if (name.equals("classPath")) {
+ classPath = (String) value;
+ }
+ else if (name.equals("tempDir")) {
+ tempDir = (String) value;
+ }
+ else if (name.equals("classLoader")) {
+ classLoader = (ClassLoader) value;
+ }
+ }
+
+ public void terminate() {
+ mgr = null;
+ declaredBeans = null;
+ classLoader = null;
+ }
+
+ public void undeclareBean(final BSFDeclaredBean bean) throws BSFException {
+ throw new BSFException(BSFException.REASON_UNSUPPORTED_FEATURE,
+ "language " + lang +
+ " does not support undeclareBean(...).");
+ }
+}
diff --git a/src/main/java/org/apache/bsf/util/BSFEventProcessor.java b/src/main/java/org/apache/bsf/util/BSFEventProcessor.java
index 224f2f5..0d1cf0c 100644
--- a/src/main/java/org/apache/bsf/util/BSFEventProcessor.java
+++ b/src/main/java/org/apache/bsf/util/BSFEventProcessor.java
@@ -1,118 +1,116 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- *
- * 2012-01-15, Rony G. Flatscher
- * - make event name comparisons case independent, Jira issue [BSF-19]
- */
-
-package org.apache.bsf.util;
-
-import org.apache.bsf.BSFEngine;
-import org.apache.bsf.BSFException;
-import org.apache.bsf.BSFManager;
-import org.apache.bsf.util.event.EventProcessor;
-
-/**
- * This is used to support binding scripts to be run when an event
- * occurs.
- *
- * @author Sanjiva Weerawarana
- */
-public class BSFEventProcessor implements EventProcessor {
- BSFEngine engine;
- BSFManager manager;
- String filter;
- String source;
- int lineNo;
- int columnNo;
- Object script;
-
- /**
- * Package-protected constructor makes this class unavailable for
- * public use.
- */
- BSFEventProcessor (final BSFEngine engine, final BSFManager manager, final String filter,
- final String source, final int lineNo, final int columnNo, final Object script)
- throws BSFException {
- this.engine = engine;
- this.manager = manager;
- this.filter = filter;
- this.source = source;
- this.lineNo = lineNo;
- this.columnNo = columnNo;
- this.script = script;
- }
- //////////////////////////////////////////////////////////////////////////
- //
- // event is delegated to me by the adapters using this. inFilter is
- // in general the name of the method via which the event was received
- // at the adapter. For prop/veto change events, inFilter is the name
- // of the property. In any case, in the event processor, I only forward
- // those events if for which the filters match (if one is specified).
-
- public void processEvent (final String inFilter, final Object[] evtInfo) {
- try {
- processExceptionableEvent (inFilter, evtInfo);
- } catch (final RuntimeException re) {
- // rethrow this .. I don't want to intercept run-time stuff
- // that can in fact occur legit
- throw re;
- } catch (final Exception e) {
- // should not occur
- System.err.println ("BSFError: non-exceptionable event delivery " +
- "threw exception (that's not nice): " + e);
- e.printStackTrace ();
- }
- }
- //////////////////////////////////////////////////////////////////////////
- //
- // same as above, but used when the method event method may generate
- // an exception which must go all the way back to the source (as in
- // the vetoableChange case)
-
- public void processExceptionableEvent (final String inFilter, final Object[] evtInfo) throws Exception
- {
- if ((filter != null) && !isFilteredEvent(filter, inFilter)) {
- // ignore this event
- return;
- }
-
- // run the script
- engine.exec (source, lineNo, columnNo, script);
-// System.err.println("returned from engine.exec.");
- }
-
-
- private static boolean isFilteredEvent(final String filter, final String inFilter)
- {
- boolean bRes=filter.equalsIgnoreCase(inFilter);
- if (bRes)
- {
- return bRes;
- }
-
- final String chunks[]=filter.replace('+',' ').split(" ");
- for (int i=0;i<chunks.length;i++)
- {
- bRes=chunks[i].equalsIgnoreCase(inFilter);
- if (bRes)
- {
- return bRes;
- }
- }
- return bRes;
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ *
+ * 2012-01-15, Rony G. Flatscher
+ * - make event name comparisons case independent, Jira issue [BSF-19]
+ */
+
+package org.apache.bsf.util;
+
+import org.apache.bsf.BSFEngine;
+import org.apache.bsf.BSFException;
+import org.apache.bsf.BSFManager;
+import org.apache.bsf.util.event.EventProcessor;
+
+/**
+ * This is used to support binding scripts to be run when an event
+ * occurs.
+ */
+public class BSFEventProcessor implements EventProcessor {
+ BSFEngine engine;
+ BSFManager manager;
+ String filter;
+ String source;
+ int lineNo;
+ int columnNo;
+ Object script;
+
+ /**
+ * Package-protected constructor makes this class unavailable for
+ * public use.
+ */
+ BSFEventProcessor (final BSFEngine engine, final BSFManager manager, final String filter,
+ final String source, final int lineNo, final int columnNo, final Object script)
+ throws BSFException {
+ this.engine = engine;
+ this.manager = manager;
+ this.filter = filter;
+ this.source = source;
+ this.lineNo = lineNo;
+ this.columnNo = columnNo;
+ this.script = script;
+ }
+ //////////////////////////////////////////////////////////////////////////
+ //
+ // event is delegated to me by the adapters using this. inFilter is
+ // in general the name of the method via which the event was received
+ // at the adapter. For prop/veto change events, inFilter is the name
+ // of the property. In any case, in the event processor, I only forward
+ // those events if for which the filters match (if one is specified).
+
+ public void processEvent (final String inFilter, final Object[] evtInfo) {
+ try {
+ processExceptionableEvent (inFilter, evtInfo);
+ } catch (final RuntimeException re) {
+ // rethrow this .. I don't want to intercept run-time stuff
+ // that can in fact occur legit
+ throw re;
+ } catch (final Exception e) {
+ // should not occur
+ System.err.println ("BSFError: non-exceptionable event delivery " +
+ "threw exception (that's not nice): " + e);
+ e.printStackTrace ();
+ }
+ }
+ //////////////////////////////////////////////////////////////////////////
+ //
+ // same as above, but used when the method event method may generate
+ // an exception which must go all the way back to the source (as in
+ // the vetoableChange case)
+
+ public void processExceptionableEvent (final String inFilter, final Object[] evtInfo) throws Exception
+ {
+ if ((filter != null) && !isFilteredEvent(filter, inFilter)) {
+ // ignore this event
+ return;
+ }
+
+ // run the script
+ engine.exec (source, lineNo, columnNo, script);
+// System.err.println("returned from engine.exec.");
+ }
+
+
+ private static boolean isFilteredEvent(final String filter, final String inFilter)
+ {
+ boolean bRes=filter.equalsIgnoreCase(inFilter);
+ if (bRes)
+ {
+ return bRes;
+ }
+
+ final String chunks[]=filter.replace('+',' ').split(" ");
+ for (int i=0;i<chunks.length;i++)
+ {
+ bRes=chunks[i].equalsIgnoreCase(inFilter);
+ if (bRes)
+ {
+ return bRes;
+ }
+ }
+ return bRes;
+ }
+}
diff --git a/src/main/java/org/apache/bsf/util/BSFEventProcessorReturningEventInfos.java b/src/main/java/org/apache/bsf/util/BSFEventProcessorReturningEventInfos.java
index c67bfa6..a8ac744 100644
--- a/src/main/java/org/apache/bsf/util/BSFEventProcessorReturningEventInfos.java
+++ b/src/main/java/org/apache/bsf/util/BSFEventProcessorReturningEventInfos.java
@@ -1,190 +1,187 @@
-/*
- * This software consists of voluntary contributions made by many individuals
- * on behalf of the Apache Software Foundation and was originally created by
- * Sanjiva Weerawarana and others at International Business Machines
- * Corporation. For more information on the Apache Software Foundation,
- * please see <http://www.apache.org/>.
- *
- * 2012-01-15, Rony G. Flatscher
- * - make event name comparisons case independent, Jira issue [BSF-19]
- */
-
-package org.apache.bsf.util;
-
-import java.util.Vector;
-
-import org.apache.bsf.BSFEngine;
-import org.apache.bsf.BSFException;
-import org.apache.bsf.BSFManager;
-import org.apache.bsf.util.event.EventProcessor;
-
-/*
- * Copyright (C) 2001-2006 Rony G. Flatscher
- *
- * 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
- *
- * <a
- * href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
- *
- * 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.
- *
- */
-
-/**
- *
- * This is used to support binding scripts to be run when an event occurs,
- * forwarding the arguments supplied to the event listener. It is an adapted
- * version of org.apache.bsf.util.BSFEventProcessor.
- *
- * @author Rony G. Flatscher, but most of the code copied from
- * org.apache.bsf.util.BSFEventProcessor by Sanjiva Weerawarana
- */
-public class BSFEventProcessorReturningEventInfos implements EventProcessor {
- BSFEngine engine;
-
- BSFManager manager;
-
- String filter;
-
- String source;
-
- int lineNo;
-
- int columnNo;
-
- Object script;
-
- Object dataFromScriptingEngine; // ---rgf, 2006-02-24: data coming from the
- // script engine, could be
-
- // e.g. an object reference to forward event with received arguments to
-
- /**
- * Package-protected constructor makes this class unavailable for public
- * use.
- *
- * @param dataFromScriptingEngine
- * this contains any object supplied by the scripting engine and
- * gets sent back with the supplied script. This could be used
- * e.g. for indicating which scripting engine object should be
- * ultimately informed of the event occurrence.
- */
- BSFEventProcessorReturningEventInfos(final BSFEngine engine, final BSFManager manager,
- final String filter, final String source, final int lineNo, final int columnNo,
- final Object script, final Object dataFromScriptingEngine) throws BSFException {
- this.engine = engine;
- this.manager = manager;
- this.filter = filter;
- this.source = source;
- this.lineNo = lineNo;
- this.columnNo = columnNo;
- this.script = script;
- this.dataFromScriptingEngine = dataFromScriptingEngine;
- }
-
- // ////////////////////////////////////////////////////////////////////////
- //
- // event is delegated to me by the adapters using this. inFilter is
- // in general the name of the method via which the event was received
- // at the adapter. For prop/veto change events, inFilter is the name
- // of the property. In any case, in the event processor, I only forward
- // those events if for which the filters match (if one is specified).
-
- public void processEvent(final String inFilter, final Object[] evtInfo) {
- try {
- processExceptionableEvent(inFilter, evtInfo);
- } catch (final RuntimeException re) {
- // rethrow this .. I don't want to intercept run-time stuff
- // that can in fact occur legit
- throw re;
- } catch (final Exception e) {
- // should not occur
- System.err.println("BSFError: non-exceptionable event delivery "
- + "threw exception (that's not nice): " + e);
- e.printStackTrace();
- }
- }
-
- // ////////////////////////////////////////////////////////////////////////
- //
- // same as above, but used when the method event method may generate
- // an exception which must go all the way back to the source (as in
- // the vetoableChange case)
-
- public void processExceptionableEvent(final String inFilter, final Object[] evtInfo)
- throws Exception {
-
- // System.err.println(this+": inFilter=["+inFilter+"],
- // filter=["+filter+"]");
- if ((filter != null) && !isFilteredEvent(filter, inFilter)) {
- // ignore this event
- return;
- }
-
- // run the script
- // engine.exec (source, lineNo, columnNo, script);
-
- // create the parameter vectors for engine.apply()
- final Vector paramNames = new Vector(), paramValues = new Vector();
-
- // parameter # 1
- // supply the parameters as an array object as sent to the event object
- // listener
- // (usually the first entry is the sent event object)
- paramNames.add("eventParameters");
- paramValues.add(evtInfo);
-
- // parameter # 2
- // supply the data object received from the scripting engine to be sent
- // with the event
- paramNames.add("dataFromScriptingEngine");
- paramValues.add(this.dataFromScriptingEngine); // can be null as well
-
- // parameter # 3
- // event filter in place
- paramNames.add("inFilter");
- paramValues.add(inFilter); // event name that has occurred
-
- // parameter # 4
- // event filter in place
- paramNames.add("eventFilter");
- paramValues.add(this.filter); // can be null as well
-
- // parameter # 5
- // BSF manager instance (e.g. allows access to its registry)
- paramNames.add("BSFManager");
- paramValues.add(this.manager);
-
- engine.apply(source, lineNo, columnNo, this.script, paramNames,
- paramValues);
-// System.err.println("returned from engine.exec.");
-
- }
-
-
- private static boolean isFilteredEvent(final String filter, final String inFilter)
- {
- boolean bRes=filter.equalsIgnoreCase(inFilter);
- if (bRes)
- {
- return bRes;
- }
-
- final String chunks[]=filter.replace('+',' ').split(" ");
- for (int i=0;i<chunks.length;i++)
- {
- bRes=chunks[i].equalsIgnoreCase(inFilter);
- if (bRes)
- {
- return bRes;
- }
- }
- return bRes;
- }
-}
+/*
+ * This software consists of voluntary contributions made by many individuals
+ * on behalf of the Apache Software Foundation and was originally created by
+ * Sanjiva Weerawarana and others at International Business Machines
+ * Corporation. For more information on the Apache Software Foundation,
+ * please see <http://www.apache.org/>.
+ *
+ * 2012-01-15, Rony G. Flatscher
+ * - make event name comparisons case independent, Jira issue [BSF-19]
+ */
+
+package org.apache.bsf.util;
+
+import java.util.Vector;
+
+import org.apache.bsf.BSFEngine;
+import org.apache.bsf.BSFException;
+import org.apache.bsf.BSFManager;
+import org.apache.bsf.util.event.EventProcessor;
+
+/*
+ * Copyright (C) 2001-2006 Rony G. Flatscher
+ *
+ * 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
+ *
+ * <a
+ * href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
+ *
+ * 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.
+ *
+ */
+
+/**
+ *
+ * This is used to support binding scripts to be run when an event occurs,
+ * forwarding the arguments supplied to the event listener. It is an adapted
+ * version of org.apache.bsf.util.BSFEventProcessor.
+ */
+public class BSFEventProcessorReturningEventInfos implements EventProcessor {
+ BSFEngine engine;
+
+ BSFManager manager;
+
+ String filter;
+
+ String source;
+
+ int lineNo;
+
+ int columnNo;
+
+ Object script;
+
+ Object dataFromScriptingEngine; // ---rgf, 2006-02-24: data coming from the
+ // script engine, could be
+
+ // e.g. an object reference to forward event with received arguments to
+
+ /**
+ * Package-protected constructor makes this class unavailable for public
+ * use.
+ *
+ * @param dataFromScriptingEngine
+ * this contains any object supplied by the scripting engine and
+ * gets sent back with the supplied script. This could be used
+ * e.g. for indicating which scripting engine object should be
+ * ultimately informed of the event occurrence.
+ */
+ BSFEventProcessorReturningEventInfos(final BSFEngine engine, final BSFManager manager,
+ final String filter, final String source, final int lineNo, final int columnNo,
+ final Object script, final Object dataFromScriptingEngine) throws BSFException {
+ this.engine = engine;
+ this.manager = manager;
+ this.filter = filter;
+ this.source = source;
+ this.lineNo = lineNo;
+ this.columnNo = columnNo;
+ this.script = script;
+ this.dataFromScriptingEngine = dataFromScriptingEngine;
+ }
+
+ // ////////////////////////////////////////////////////////////////////////
+ //
+ // event is delegated to me by the adapters using this. inFilter is
+ // in general the name of the method via which the event was received
+ // at the adapter. For prop/veto change events, inFilter is the name
+ // of the property. In any case, in the event processor, I only forward
+ // those events if for which the filters match (if one is specified).
+
+ public void processEvent(final String inFilter, final Object[] evtInfo) {
+ try {
+ processExceptionableEvent(inFilter, evtInfo);
+ } catch (final RuntimeException re) {
+ // rethrow this .. I don't want to intercept run-time stuff
+ // that can in fact occur legit
+ throw re;
+ } catch (final Exception e) {
+ // should not occur
+ System.err.println("BSFError: non-exceptionable event delivery "
+ + "threw exception (that's not nice): " + e);
+ e.printStackTrace();
+ }
+ }
+
+ // ////////////////////////////////////////////////////////////////////////
+ //
+ // same as above, but used when the method event method may generate
+ // an exception which must go all the way back to the source (as in
+ // the vetoableChange case)
+
+ public void processExceptionableEvent(final String inFilter, final Object[] evtInfo)
+ throws Exception {
+
+ // System.err.println(this+": inFilter=["+inFilter+"],
+ // filter=["+filter+"]");
+ if ((filter != null) && !isFilteredEvent(filter, inFilter)) {
+ // ignore this event
+ return;
+ }
+
+ // run the script
+ // engine.exec (source, lineNo, columnNo, script);
+
+ // create the parameter vectors for engine.apply()
+ final Vector paramNames = new Vector(), paramValues = new Vector();
+
+ // parameter # 1
+ // supply the parameters as an array object as sent to the event object
+ // listener
+ // (usually the first entry is the sent event object)
+ paramNames.add("eventParameters");
+ paramValues.add(evtInfo);
+
+ // parameter # 2
+ // supply the data object received from the scripting engine to be sent
+ // with the event
+ paramNames.add("dataFromScriptingEngine");
+ paramValues.add(this.dataFromScriptingEngine); // can be null as well
+
+ // parameter # 3
+ // event filter in place
+ paramNames.add("inFilter");
+ paramValues.add(inFilter); // event name that has occurred
+
+ // parameter # 4
+ // event filter in place
+ paramNames.add("eventFilter");
+ paramValues.add(this.filter); // can be null as well
+
+ // parameter # 5
+ // BSF manager instance (e.g. allows access to its registry)
+ paramNames.add("BSFManager");
+ paramValues.add(this.manager);
+
+ engine.apply(source, lineNo, columnNo, this.script, paramNames,
+ paramValues);
+// System.err.println("returned from engine.exec.");
+
+ }
+
+
+ private static boolean isFilteredEvent(final String filter, final String inFilter)
+ {
+ boolean bRes=filter.equalsIgnoreCase(inFilter);
+ if (bRes)
+ {
+ return bRes;
+ }
+
+ final String chunks[]=filter.replace('+',' ').split(" ");
+ for (int i=0;i<chunks.length;i++)
+ {
+ bRes=chunks[i].equalsIgnoreCase(inFilter);
+ if (bRes)
+ {
+ return bRes;
+ }
+ }
+ return bRes;
+ }
+}
diff --git a/src/main/java/org/apache/bsf/util/BSFFunctions.java b/src/main/java/org/apache/bsf/util/BSFFunctions.java
index f7ac89c..83898b4 100644
--- a/src/main/java/org/apache/bsf/util/BSFFunctions.java
+++ b/src/main/java/org/apache/bsf/util/BSFFunctions.java
@@ -1,55 +1,53 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.util;
-
-import org.apache.bsf.BSFEngine;
-import org.apache.bsf.BSFException;
-import org.apache.bsf.BSFManager;
-
-/**
- * This is a utility that engine implementors may use as the Java
- * object they expose in the scripting language as "bsf". This has
- * essentially a subset of the methods in BSFManager plus some
- * stuff from the utils. Currently used by Javascript (Rhino) & BML.
- *
- * @author Sanjiva Weerawarana
- */
-public class BSFFunctions {
- BSFManager mgr;
- BSFEngine engine;
-
- public BSFFunctions (final BSFManager mgr, final BSFEngine engine) {
- this.mgr = mgr;
- this.engine = engine;
- }
- public void addEventListener (final Object src, final String eventSetName,
- final String filter, final Object script)
- throws BSFException {
- EngineUtils.addEventListener (src, eventSetName, filter, engine,
- mgr, "<event-binding>", 0, 0, script);
- }
- public Object lookupBean (final String name) {
- return mgr.lookupBean (name);
- }
- public void registerBean (final String name, final Object bean) {
- mgr.registerBean (name, bean);
- }
- public void unregisterBean (final String name) {
- mgr.unregisterBean (name);
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.util;
+
+import org.apache.bsf.BSFEngine;
+import org.apache.bsf.BSFException;
+import org.apache.bsf.BSFManager;
+
+/**
+ * This is a utility that engine implementors may use as the Java
+ * object they expose in the scripting language as "bsf". This has
+ * essentially a subset of the methods in BSFManager plus some
+ * stuff from the utils. Currently used by Javascript (Rhino) & BML.
+ */
+public class BSFFunctions {
+ BSFManager mgr;
+ BSFEngine engine;
+
+ public BSFFunctions (final BSFManager mgr, final BSFEngine engine) {
+ this.mgr = mgr;
+ this.engine = engine;
+ }
+ public void addEventListener (final Object src, final String eventSetName,
+ final String filter, final Object script)
+ throws BSFException {
+ EngineUtils.addEventListener (src, eventSetName, filter, engine,
+ mgr, "<event-binding>", 0, 0, script);
+ }
+ public Object lookupBean (final String name) {
+ return mgr.lookupBean (name);
+ }
+ public void registerBean (final String name, final Object bean) {
+ mgr.registerBean (name, bean);
+ }
+ public void unregisterBean (final String name) {
+ mgr.unregisterBean (name);
+ }
+}
diff --git a/src/main/java/org/apache/bsf/util/Bean.java b/src/main/java/org/apache/bsf/util/Bean.java
index bff1f1a..6e1ff95 100644
--- a/src/main/java/org/apache/bsf/util/Bean.java
+++ b/src/main/java/org/apache/bsf/util/Bean.java
@@ -1,39 +1,37 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.util;
-
-/**
- * A <em>Bean</em> is the class used to represent a bean: it holds a
- * type and a value. This is needed because otherwise we can't represent
- * the types of null-valued beans (or primitives) correctly. This was
- * originally in the BML player.
- *
- * @author Sanjiva Weerawarana
- */
-public class Bean {
- // type of this bean
- public Class type;
-
- // its current value (mebbe null)
- public Object value;
-
- public Bean (final Class type, final Object value) {
- this.type = type;
- this.value = value;
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.util;
+
+/**
+ * A <em>Bean</em> is the class used to represent a bean: it holds a
+ * type and a value. This is needed because otherwise we can't represent
+ * the types of null-valued beans (or primitives) correctly. This was
+ * originally in the BML player.
+ */
+public class Bean {
+ // type of this bean
+ public Class type;
+
+ // its current value (mebbe null)
+ public Object value;
+
+ public Bean (final Class type, final Object value) {
+ this.type = type;
+ this.value = value;
+ }
+}
diff --git a/src/main/java/org/apache/bsf/util/CodeBuffer.java b/src/main/java/org/apache/bsf/util/CodeBuffer.java
index b3e88c3..fcbe6c0 100644
--- a/src/main/java/org/apache/bsf/util/CodeBuffer.java
+++ b/src/main/java/org/apache/bsf/util/CodeBuffer.java
@@ -1,481 +1,479 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.util;
-
-import java.io.PrintWriter;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.Hashtable;
-import java.util.Stack;
-import java.util.Vector;
-
-import org.apache.bsf.util.cf.CodeFormatter;
-
-/**
- * A <code>CodeBuffer</code> object is used as a code repository for generated Java code.
- * It provides buffers which correspond to the various sections of a Java class.
- *
- * @author Matthew J. Duftler
- */
-public class CodeBuffer
-{
- private final StringWriter fieldDeclSW = new StringWriter(),
- methodDeclSW = new StringWriter(),
- initializerSW = new StringWriter(),
- constructorSW = new StringWriter(),
- serviceMethodSW = new StringWriter();
-
- private final PrintWriter fieldDeclPW = new PrintWriter(fieldDeclSW),
- methodDeclPW = new PrintWriter(methodDeclSW),
- initializerPW = new PrintWriter(initializerSW),
- constructorPW = new PrintWriter(constructorSW),
- serviceMethodPW = new PrintWriter(serviceMethodSW);
-
- private Stack symbolTableStack = new Stack();
- private Hashtable symbolTable = new Hashtable(),
- usedSymbolIndices = new Hashtable();
-
- private ObjInfo finalStatementInfo;
- private CodeBuffer parent;
-
-
- {
- symbolTableStack.push(symbolTable);
- }
-
- // New stuff...
- private final Vector imports = new Vector(),
- constructorArguments = new Vector(),
- constructorExceptions = new Vector(),
- serviceMethodExceptions = new Vector(),
- implementsVector = new Vector();
- private String packageName = null,
- className = "Test",
- serviceMethodName = "exec",
- extendsName = null;
- private Class serviceMethodReturnType = void.class;
-
- public CodeBuffer()
- {
- }
- public CodeBuffer(final CodeBuffer parent)
- {
- this.parent = parent;
- }
- public void addConstructorArgument(final ObjInfo arg)
- {
- constructorArguments.addElement(arg);
- }
- public void addConstructorException(final String exceptionName)
- {
- if (!constructorExceptions.contains(exceptionName))
- {
- constructorExceptions.addElement(exceptionName);
- }
- }
- public void addConstructorStatement(final String statement)
- {
- constructorPW.println(statement);
- }
- public void addFieldDeclaration(final String statement)
- {
- fieldDeclPW.println(statement);
- }
- public void addImplements(final String importName)
- {
- if (!implementsVector.contains(importName))
- {
- implementsVector.addElement(importName);
- }
- }
- public void addImport(final String importName)
- {
- if (!imports.contains(importName))
- {
- imports.addElement(importName);
- }
- }
- public void addInitializerStatement(final String statement)
- {
- initializerPW.println(statement);
- }
- public void addMethodDeclaration(final String statement)
- {
- methodDeclPW.println(statement);
- }
- public void addServiceMethodException(final String exceptionName)
- {
- if (!serviceMethodExceptions.contains(exceptionName))
- {
- serviceMethodExceptions.addElement(exceptionName);
- }
- }
- public void addServiceMethodStatement(final String statement)
- {
- serviceMethodPW.println(statement);
- }
- // Used internally by merge(...).
- private void appendIfNecessary(final PrintWriter pw, final StringBuffer buf)
- {
- if (buf.length() > 0)
- {
- pw.print(buf.toString());
- }
- }
- public String buildNewSymbol(final String prefix)
- {
- Integer nextNum = getSymbolIndex(prefix);
-
- if (nextNum == null)
- {
- nextNum = new Integer(0);
- }
-
- int iNextNum = nextNum.intValue();
- String symbol = prefix + "_" + iNextNum;
-
- while (getSymbol(symbol) != null)
- {
- iNextNum++;
- symbol = prefix + "_" + iNextNum;
- }
-
- putSymbolIndex(prefix, new Integer(iNextNum + 1));
-
- return symbol;
- }
- public void clearSymbolTable()
- {
- symbolTable = new Hashtable();
- symbolTableStack = new Stack();
- symbolTableStack.push(symbolTable);
-
- usedSymbolIndices = new Hashtable();
- }
- public String getClassName()
- {
- return className;
- }
- public Vector getConstructorArguments()
- {
- return constructorArguments;
- }
- public StringBuffer getConstructorBuffer()
- {
- constructorPW.flush();
-
- return constructorSW.getBuffer();
- }
- public Vector getConstructorExceptions()
- {
- return constructorExceptions;
- }
- public String getExtends()
- {
- return extendsName;
- }
- public StringBuffer getFieldBuffer()
- {
- fieldDeclPW.flush();
-
- return fieldDeclSW.getBuffer();
- }
- public ObjInfo getFinalServiceMethodStatement()
- {
- return finalStatementInfo;
- }
- public Vector getImplements()
- {
- return implementsVector;
- }
- public Vector getImports()
- {
- return imports;
- }
- public StringBuffer getInitializerBuffer()
- {
- initializerPW.flush();
-
- return initializerSW.getBuffer();
- }
- public StringBuffer getMethodBuffer()
- {
- methodDeclPW.flush();
-
- return methodDeclSW.getBuffer();
- }
- public String getPackageName()
- {
- return packageName;
- }
- public StringBuffer getServiceMethodBuffer()
- {
- serviceMethodPW.flush();
-
- return serviceMethodSW.getBuffer();
- }
- public Vector getServiceMethodExceptions()
- {
- return serviceMethodExceptions;
- }
- public String getServiceMethodName()
- {
- return serviceMethodName;
- }
- public Class getServiceMethodReturnType()
- {
- if (finalStatementInfo != null)
- {
- return finalStatementInfo.objClass;
- }
- else if (serviceMethodReturnType != null)
- {
- return serviceMethodReturnType;
- }
- else
- {
- return void.class;
- }
- }
- public ObjInfo getSymbol(final String symbol)
- {
- ObjInfo ret = (ObjInfo)symbolTable.get(symbol);
-
- if (ret == null && parent != null) {
- ret = parent.getSymbol(symbol);
- }
-
- return ret;
- }
- Integer getSymbolIndex(final String prefix)
- {
- if (parent != null)
- {
- return parent.getSymbolIndex(prefix);
- }
- else
- {
- return (Integer)usedSymbolIndices.get(prefix);
- }
- }
- public Hashtable getSymbolTable()
- {
- return symbolTable;
- }
- public void merge(final CodeBuffer otherCB)
- {
- final Vector otherImports = otherCB.getImports();
-
- for (int i = 0; i < otherImports.size(); i++)
- {
- addImport((String)otherImports.elementAt(i));
- }
-
- appendIfNecessary(fieldDeclPW, otherCB.getFieldBuffer());
- appendIfNecessary(methodDeclPW, otherCB.getMethodBuffer());
- appendIfNecessary(initializerPW, otherCB.getInitializerBuffer());
- appendIfNecessary(constructorPW, otherCB.getConstructorBuffer());
- appendIfNecessary(serviceMethodPW, otherCB.getServiceMethodBuffer());
-
- final ObjInfo oldRet = getFinalServiceMethodStatement();
-
- if (oldRet != null && oldRet.isExecutable())
- {
- addServiceMethodStatement(oldRet.objName + ";");
- }
-
- setFinalServiceMethodStatement(otherCB.getFinalServiceMethodStatement());
- }
- public void popSymbolTable()
- {
- symbolTableStack.pop();
- symbolTable = (Hashtable)symbolTableStack.peek();
- }
- public void print(final PrintWriter out, final boolean formatOutput)
- {
- if (formatOutput)
- {
- new CodeFormatter().formatCode(new StringReader(toString()), out);
- }
- else
- {
- out.print(toString());
- }
-
- out.flush();
- }
- public void pushSymbolTable()
- {
- symbolTable = (Hashtable)symbolTableStack.push(new ScriptSymbolTable(symbolTable));
- }
- public void putSymbol(final String symbol, final ObjInfo obj)
- {
- symbolTable.put(symbol, obj);
- }
- void putSymbolIndex(final String prefix, final Integer index)
- {
- if (parent != null)
- {
- parent.putSymbolIndex(prefix, index);
- }
- else
- {
- usedSymbolIndices.put(prefix, index);
- }
- }
- public void setClassName(final String className)
- {
- this.className = className;
- }
- public void setExtends(final String extendsName)
- {
- this.extendsName = extendsName;
- }
- public void setFinalServiceMethodStatement(final ObjInfo finalStatementInfo)
- {
- this.finalStatementInfo = finalStatementInfo;
- }
- public void setPackageName(final String packageName)
- {
- this.packageName = packageName;
- }
- public void setServiceMethodName(final String serviceMethodName)
- {
- this.serviceMethodName = serviceMethodName;
- }
- public void setServiceMethodReturnType(final Class serviceMethodReturnType)
- {
- this.serviceMethodReturnType = serviceMethodReturnType;
- }
- public void setSymbolTable(final Hashtable symbolTable)
- {
- this.symbolTable = symbolTable;
- }
- public boolean symbolTableIsStacked()
- {
- return (symbolTable instanceof ScriptSymbolTable);
- }
- public String toString()
- {
- final StringWriter sw = new StringWriter();
- final PrintWriter pw = new PrintWriter(sw);
- final ObjInfo ret = finalStatementInfo;
-
- if (packageName != null && !packageName.equals(""))
- {
- pw.println("package " + packageName + ";");
- pw.println();
- }
-
- if (imports.size() > 0)
- {
- for (int i = 0; i < imports.size(); i++)
- {
- pw.println("import " + imports.elementAt(i) + ";");
- }
-
- pw.println();
- }
-
- pw.println("public class " + className +
- (extendsName != null && !extendsName.equals("")
- ? " extends " + extendsName
- : "") +
- (implementsVector.size() > 0
- ? " implements " +
- StringUtils.getCommaListFromVector(implementsVector)
- : "")
- );
- pw.println("{");
-
- pw.print(getFieldBuffer().toString());
-
- StringBuffer buf = getInitializerBuffer();
-
- if (buf.length() > 0)
- {
- pw.println();
- pw.println("{");
- pw.print(buf.toString());
- pw.println("}");
- }
-
- buf = getConstructorBuffer();
-
- if (buf.length() > 0)
- {
- pw.println();
- pw.println("public " + className + "(" +
- (constructorArguments.size() > 0
- ? StringUtils.getCommaListFromVector(constructorArguments)
- : ""
- ) + ")" +
- (constructorExceptions.size() > 0
- ? " throws " +
- StringUtils.getCommaListFromVector(constructorExceptions)
- : ""
- )
- );
- pw.println("{");
- pw.print(buf.toString());
- pw.println("}");
- }
-
- buf = getServiceMethodBuffer();
-
- if (buf.length() > 0 || ret != null)
- {
- pw.println();
- pw.println("public " +
- StringUtils.getClassName(getServiceMethodReturnType()) + " " +
- serviceMethodName + "()" +
- (serviceMethodExceptions.size() > 0
- ? " throws " +
- StringUtils.getCommaListFromVector(serviceMethodExceptions)
- : ""
- )
- );
- pw.println("{");
-
- pw.print(buf.toString());
-
- if (ret != null)
- {
- if (ret.isValueReturning())
- {
- pw.println();
- pw.println("return " + ret.objName + ";");
- }
- else if (ret.isExecutable())
- {
- pw.println(ret.objName + ";");
- }
- }
-
- pw.println("}");
- }
-
- pw.print(getMethodBuffer().toString());
-
- pw.println("}");
-
- pw.flush();
-
- return sw.toString();
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.util;
+
+import java.io.PrintWriter;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.Hashtable;
+import java.util.Stack;
+import java.util.Vector;
+
+import org.apache.bsf.util.cf.CodeFormatter;
+
+/**
+ * A <code>CodeBuffer</code> object is used as a code repository for generated Java code.
+ * It provides buffers which correspond to the various sections of a Java class.
+ */
+public class CodeBuffer
+{
+ private final StringWriter fieldDeclSW = new StringWriter(),
+ methodDeclSW = new StringWriter(),
+ initializerSW = new StringWriter(),
+ constructorSW = new StringWriter(),
+ serviceMethodSW = new StringWriter();
+
+ private final PrintWriter fieldDeclPW = new PrintWriter(fieldDeclSW),
+ methodDeclPW = new PrintWriter(methodDeclSW),
+ initializerPW = new PrintWriter(initializerSW),
+ constructorPW = new PrintWriter(constructorSW),
+ serviceMethodPW = new PrintWriter(serviceMethodSW);
+
+ private Stack symbolTableStack = new Stack();
+ private Hashtable symbolTable = new Hashtable(),
+ usedSymbolIndices = new Hashtable();
+
+ private ObjInfo finalStatementInfo;
+ private CodeBuffer parent;
+
+
+ {
+ symbolTableStack.push(symbolTable);
+ }
+
+ // New stuff...
+ private final Vector imports = new Vector(),
+ constructorArguments = new Vector(),
+ constructorExceptions = new Vector(),
+ serviceMethodExceptions = new Vector(),
+ implementsVector = new Vector();
+ private String packageName = null,
+ className = "Test",
+ serviceMethodName = "exec",
+ extendsName = null;
+ private Class serviceMethodReturnType = void.class;
+
+ public CodeBuffer()
+ {
+ }
+ public CodeBuffer(final CodeBuffer parent)
+ {
+ this.parent = parent;
+ }
+ public void addConstructorArgument(final ObjInfo arg)
+ {
+ constructorArguments.addElement(arg);
+ }
+ public void addConstructorException(final String exceptionName)
+ {
+ if (!constructorExceptions.contains(exceptionName))
+ {
+ constructorExceptions.addElement(exceptionName);
+ }
+ }
+ public void addConstructorStatement(final String statement)
+ {
+ constructorPW.println(statement);
+ }
+ public void addFieldDeclaration(final String statement)
+ {
+ fieldDeclPW.println(statement);
+ }
+ public void addImplements(final String importName)
+ {
+ if (!implementsVector.contains(importName))
+ {
+ implementsVector.addElement(importName);
+ }
+ }
+ public void addImport(final String importName)
+ {
+ if (!imports.contains(importName))
+ {
+ imports.addElement(importName);
+ }
+ }
+ public void addInitializerStatement(final String statement)
+ {
+ initializerPW.println(statement);
+ }
+ public void addMethodDeclaration(final String statement)
+ {
+ methodDeclPW.println(statement);
+ }
+ public void addServiceMethodException(final String exceptionName)
+ {
+ if (!serviceMethodExceptions.contains(exceptionName))
+ {
+ serviceMethodExceptions.addElement(exceptionName);
+ }
+ }
+ public void addServiceMethodStatement(final String statement)
+ {
+ serviceMethodPW.println(statement);
+ }
+ // Used internally by merge(...).
+ private void appendIfNecessary(final PrintWriter pw, final StringBuffer buf)
+ {
+ if (buf.length() > 0)
+ {
+ pw.print(buf.toString());
+ }
+ }
+ public String buildNewSymbol(final String prefix)
+ {
+ Integer nextNum = getSymbolIndex(prefix);
+
+ if (nextNum == null)
+ {
+ nextNum = new Integer(0);
+ }
+
+ int iNextNum = nextNum.intValue();
+ String symbol = prefix + "_" + iNextNum;
+
+ while (getSymbol(symbol) != null)
+ {
+ iNextNum++;
+ symbol = prefix + "_" + iNextNum;
+ }
+
+ putSymbolIndex(prefix, new Integer(iNextNum + 1));
+
+ return symbol;
+ }
+ public void clearSymbolTable()
+ {
+ symbolTable = new Hashtable();
+ symbolTableStack = new Stack();
+ symbolTableStack.push(symbolTable);
+
+ usedSymbolIndices = new Hashtable();
+ }
+ public String getClassName()
+ {
+ return className;
+ }
+ public Vector getConstructorArguments()
+ {
+ return constructorArguments;
+ }
+ public StringBuffer getConstructorBuffer()
+ {
+ constructorPW.flush();
+
+ return constructorSW.getBuffer();
+ }
+ public Vector getConstructorExceptions()
+ {
+ return constructorExceptions;
+ }
+ public String getExtends()
+ {
+ return extendsName;
+ }
+ public StringBuffer getFieldBuffer()
+ {
+ fieldDeclPW.flush();
+
+ return fieldDeclSW.getBuffer();
+ }
+ public ObjInfo getFinalServiceMethodStatement()
... 11511 lines suppressed ...