Author: cbrisson
Date: Fri Jul 15 22:30:59 2016
New Revision: 1752882
URL: http://svn.apache.org/viewvc?rev=1752882&view=rev
Log:
review (ahem... rewrite using Sun provided example) scripting interface
Added:
velocity/engine/trunk/velocity-engine-scripting/src/test/resources/
velocity/engine/trunk/velocity-engine-scripting/src/test/resources/velocity.properties
- copied unchanged from r1752841,
velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/resources/velocity.properties
Removed:
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityBindings.java
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityCompilable.java
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityCompiledScript.java
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityInvocable.java
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptContext.java
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptException.java
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/util/
velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/ScriptEngineFactoryTest.java
velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/resources/velocity.properties
Modified:
velocity/engine/trunk/velocity-engine-scripting/pom.xml
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptEngine.java
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptEngineFactory.java
velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/ScriptEngineTest.java
velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/VelocityScriptContextTest.java
Modified: velocity/engine/trunk/velocity-engine-scripting/pom.xml
URL:
http://svn.apache.org/viewvc/velocity/engine/trunk/velocity-engine-scripting/pom.xml?rev=1752882&r1=1752881&r2=1752882&view=diff
==============================================================================
--- velocity/engine/trunk/velocity-engine-scripting/pom.xml (original)
+++ velocity/engine/trunk/velocity-engine-scripting/pom.xml Fri Jul 15 22:30:59
2016
@@ -21,26 +21,60 @@
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.velocity</groupId>
- <artifactId>velocity-engine-parent</artifactId>
- <version>2.0.0-SNAPSHOT</version>
- </parent>
- <artifactId>velocity-engine-scripting</artifactId>
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.velocity</groupId>
+ <artifactId>velocity-engine-parent</artifactId>
<version>2.0.0-SNAPSHOT</version>
- <name>Apache Velocity - JSR 223 Scripting</name>
- <dependencies>
- <dependency>
- <groupId>org.apache.velocity</groupId>
- <artifactId>velocity-engine-core</artifactId>
- <version>2.0.0-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.8.2</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
+ </parent>
+ <artifactId>velocity-engine-scripting</artifactId>
+ <version>2.0.0-SNAPSHOT</version>
+ <name>Apache Velocity - JSR 223 Scripting</name>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.velocity</groupId>
+ <artifactId>velocity-engine-core</artifactId>
+ <version>2.0.0-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.8.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <version>1.7.12</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <systemProperties>
+ <property>
+ <name>test.resources.dir</name>
+ <value>${project.build.directory}</value>
+ </property>
+ </systemProperties>
+ </configuration>
+ <executions>
+ <execution>
+ <id>integration-test</id>
+ <phase>integration-test</phase>
+ <goals>
+ <goal>test</goal>
+ </goals>
+ <configuration>
+ <skip>false</skip>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
</project>
Modified:
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptEngine.java
URL:
http://svn.apache.org/viewvc/velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptEngine.java?rev=1752882&r1=1752881&r2=1752882&view=diff
==============================================================================
---
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptEngine.java
(original)
+++
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptEngine.java
Fri Jul 15 22:30:59 2016
@@ -1,5 +1,7 @@
package org.apache.velocity.script;
+/* dual licencing... */
+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -19,471 +21,227 @@ package org.apache.velocity.script;
* under the License.
*/
-import org.apache.velocity.Template;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.app.VelocityEngine;
-import org.apache.velocity.exception.ResourceNotFoundException;
-import org.apache.velocity.script.util.ScriptResourceHolder;
-import org.apache.velocity.script.util.ScriptUtil;
-
-import javax.script.*;
-import java.io.*;
-import java.util.Properties;
-
-/**
- * VelocityScriptEngine is the fundamental class whose methods inherited from
.javax.script.ScriptEngine interface
- * These methods provide basic scripting functionality. This includes methods
that execute scripts, and ones that set and get values.
- * The values are key/value pairs of two types.
- * This Provides a standard implementation for several of the variants of the
eval method.
- * eval(Reader)
- * eval(String)
- * eval(String, Bindings)
- * eval(Reader, Bindings)
+/*
+ * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
+ * Use is subject to license terms.
*
- * There are two ways to instantiate VelocityScriptEngine. One is directly
using the script engine factory which was used to create this
- * engine. Other one is by passing the factory and the pre defined bindings
required for the engine.
+ * Redistribution and use in source and binary forms, with or without
modification, are
+ * permitted provided that the following conditions are met: Redistributions
of source code
+ * must retain the above copyright notice, this list of conditions and the
following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
this list of
+ * conditions and the following disclaimer in the documentation and/or other
materials
+ * provided with the distribution. Neither the name of the Sun Microsystems
nor the names of
+ * is contributors may be used to endorse or promote products derived from
this software
+ * without specific prior written permission.
+
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER
+ * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
*/
-public class VelocityScriptEngine implements ScriptEngine {
-
- /**
- * ScriptEngineFactory reference from whom this engine got created
- */
- private ScriptEngineFactory scriptEngineFactory;
-
-
- /**
- * Velocity core engine reference
- */
- private VelocityEngine velocityEngine;
-
-
- /**
- * unmodifiable property name which is ued to obtain properties from
context as well as from system to initialize velocity core engine
- */
- public static final String VELOCITY_PROPERTIES =
"org.apache.velocity.engine.properties";
-
-
- /**
- * Default velocity log tag
- */
- public static final String DEFAULT_LOG_TAG = "default_log_tag";
-
-
- /**
- * script context reference which belongs to this engine instance
- */
- private ScriptContext scriptContext;
-
-
- /**
- * Constructor which gets created engine factory reference as input
- *
- * @param scriptEngineFactory ScriptEngineFactory reference from whom this
engine got created
- */
- public VelocityScriptEngine(ScriptEngineFactory scriptEngineFactory) {
- this.scriptEngineFactory = scriptEngineFactory;
- this.scriptContext = new VelocityScriptContext();
- ScriptUtil.setScriptContext(scriptContext);
- }
-
- /**
- * @param scriptEngineFactory ScriptEngineFactory reference from whom this
engine got created
- * @param bindings required binding needs to initialize this
engine, unless it defaults to engine scope
- */
- public VelocityScriptEngine(ScriptEngineFactory scriptEngineFactory,
Bindings bindings) {
- this.scriptEngineFactory = scriptEngineFactory;
- this.scriptContext = new VelocityScriptContext();
- ScriptUtil.setScriptContext(scriptContext);
- if (bindings != null) {
- this.scriptContext.setBindings(bindings,
ScriptContext.ENGINE_SCOPE);
- } else {
- ScriptUtil.addExceptionToErrorWriter(new NullPointerException("Bindings
cannot be null"));
- throw new NullPointerException("Bindings cannot be null");
- }
- }
-
-
- /**
- * @return script engine factory who created this engine
- */
- public ScriptEngineFactory getFactory() {
-
- // if null return a newly created one
- if (scriptEngineFactory == null) {
- createNewFactory();
- }
- return scriptEngineFactory;
- }
- private void createNewFactory() {
-// Added creation inside sync block to avoid creating two factories
from a engine by two parallel threads at the same time.
-// Also the additional null check out from sync block is to avoid
every thread to get blocked inside it even there is an already created factory.
- synchronized (this) {
- if (scriptEngineFactory == null) {
- scriptEngineFactory = new VelocityScriptEngineFactory();
- }
- }
- }
-
- /**
- * Creates the velocity core engine by initializing it from reading
property file/system properties
- *
- * @param context
- */
- private void constructVelocityEngine(ScriptContext context) {
-
- Properties props = getPropertiesFromContext(context);
- //Check if property exists in context
- if (props != null) {
- initVelocityEngine(props);
- return;
- } else {
- props = getPropertiesFromSystem();
- //Check if properties exists in System
- if (props != null) {
- initVelocityEngine(props);
- return;
- }
- }
- //Init velocity engine with default settings
- initVelocityEngine();
- }
-
- /**
- * Init velocity engine without properties.
- */
- private void initVelocityEngine() {
-
- if (velocityEngine != null) {
-
-// Add sync block from a parallel thread creating two velocity
engine instances
- synchronized (this) {
- velocityEngine = new VelocityEngine();
- velocityEngine.init();
- }
- }
- }
+/*
+ * Main class for the Velocity script engine. Please refer to the
+ * javax.script.ScriptEngine documentation for details.
+ *
+ * @author A. Sundararajan
+ * @author <a href="mailto:claude.bris...@gmail.com">Claude Brisson</a>
+ * @version $Id: VelocityScriptEngine.java$
+ */
- /**
- * Initializes the velocity engine with pre defined properties
- *
- * @param props
- */
- private void initVelocityEngine(Properties props) {
- if (velocityEngine == null) {
- synchronized (this) {
- velocityEngine = new VelocityEngine();
- velocityEngine.init(props);
- }
- }
- }
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.Properties;
+import org.apache.velocity.*;
+import org.apache.velocity.app.*;
- /**
- * Obtain properties from a property file which is taken from a system
property
- *
- * @return
- */
- private Properties getPropertiesFromSystem() {
- String propFileName = System.getProperty(VELOCITY_PROPERTIES);
- File propFile = new File(propFileName);
- if (propFile.exists()) {
- Properties properties = new Properties();
- try {
- properties.load(new FileInputStream(propFile));
- return properties;
- } catch (IOException e) {
- ScriptUtil.addExceptionToErrorWriter(e);
- return null;
- }
+import javax.script.AbstractScriptEngine;
+import javax.script.Bindings;
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptException;
+import javax.script.SimpleBindings;
+
+public class VelocityScriptEngine extends AbstractScriptEngine
+{
+
+ public static final String STRING_OUTPUT_MODE_KEY =
"org.apache.velocity.stringOutput";
+ public static final String VELOCITY_PROPERTIES_KEY =
"org.apache.velocity.script.properties";
+
+ // my factory, may be null
+ private volatile ScriptEngineFactory factory;
+ private volatile VelocityEngine vengine;
+
+ public VelocityScriptEngine(ScriptEngineFactory factory)
+ {
+ this.factory = factory;
+ }
+
+ public VelocityScriptEngine()
+ {
+ this(null);
+ }
+
+ public VelocityEngine getVelocityEngine()
+ {
+ return vengine;
+ }
+
+ // ScriptEngine methods
+ public Object eval(String str, ScriptContext ctx)
+ throws ScriptException
+ {
+ return eval(new StringReader(str), ctx);
+ }
+
+ public Object eval(Reader reader, ScriptContext ctx)
+ throws ScriptException
+ {
+ initVelocityEngine(ctx);
+ String fileName = getFilename(ctx);
+ VelocityContext vctx = getVelocityContext(ctx);
+ boolean outputAsString = isStringOutputMode(ctx);
+ Writer out;
+ if (outputAsString)
+ {
+ out = new StringWriter();
+ }
+ else
+ {
+ out = ctx.getWriter();
+ }
+ try
+ {
+ vengine.evaluate(vctx, out, fileName, reader);
+ out.flush();
}
- //TODO log error msg saying no such property file
- return null;
- }
-
- private Properties getPropertiesFromContext(ScriptContext context) {
- Object props = context.getAttribute(VELOCITY_PROPERTIES);
- if (props instanceof Properties) {
- return (Properties) props;
- } else {
- return null;
+ catch (Exception exp)
+ {
+ throw new ScriptException(exp);
}
+ return outputAsString ? out.toString() : null;
}
-
- /**
- * Causes the immediate execution of the script whose source is the String
passed as the first argument. The script may be
- * re-parsed or recompiled before execution. State left in the engine from
previous executions, including variable values and
- * compiled procedures may be visible during this execution.
- *
- * @param s The script to be executed by the script engine.
- * @param scriptContext A ScriptContext exposing sets of attributes in
different scopes. The meanings of the
- * scopes ScriptContext.GLOBAL_SCOPE, and
ScriptContext.ENGINE_SCOPE are defined in the specification.
- * @return The value returned from the execution of the script.
- * @throws ScriptException
- */
- public Object eval(String s, ScriptContext scriptContext) throws
ScriptException {
- return eval(new StringReader(s),scriptContext);
- }
-
-
- /**
- * Same as eval(String, ScriptContext) where the source of the script is
read from a Reader.
- *
- * @param reader The source of the script to be executed by the
script engine.
- * @param scriptContext The ScriptContext passed to the script engine.
- * @return The value returned from the execution of the script.
- * @throws ScriptException if an error occurrs in script.
- * java.lang.NullPointerException - if either
argument is null.
- */
- public Object eval(Reader reader, ScriptContext scriptContext) throws
ScriptException {
-
- if (reader == null) {
- throw new NullPointerException("Reader passed cannot be null");
- }
- constructVelocityEngine(scriptContext);
- VelocityContext velocityContext = getVelocityContext(scriptContext);
-
- Writer outPut;
- if (scriptContext.getWriter() != null) {
- outPut = scriptContext.getWriter();
- } else {
- outPut = new StringWriter();
- }
- boolean result;
-
- try {
- //Check for velocity tools vm file
- if (scriptContext.getAttribute(VelocityScriptEngine.FILENAME) !=
null) {
- Template template = null;
- String fileName =
scriptContext.getAttribute(VelocityScriptEngine.FILENAME).toString();
- //Cache hit
- if (ScriptResourceHolder.hasTemplate(fileName)) {
- template = ScriptResourceHolder.getTemplate(fileName);
- } else {
- try {
- template = velocityEngine.getTemplate(fileName);
- ScriptResourceHolder.putTemplate(fileName,template);
- template.merge(velocityContext, outPut);
- } catch(ResourceNotFoundException e1){
+ public ScriptEngineFactory getFactory()
+ {
+ if (factory == null)
+ {
+ synchronized (this)
+ {
+ if (factory == null)
+ {
+ factory = new VelocityScriptEngineFactory();
+ }
+ }
+ }
+ return factory;
+ }
+
+ public Bindings createBindings()
+ {
+ return new SimpleBindings();
+ }
+
+ // internals only below this point
+ private void initVelocityEngine(ScriptContext ctx)
+ {
+ if (vengine == null)
+ {
+ synchronized (this)
+ {
+ if (vengine != null) return;
+
+ Properties props = getVelocityProperties(ctx);
+ VelocityEngine tmpEngine = new VelocityEngine();
+ try
+ {
+ if (props != null)
+ {
+ tmpEngine.init(props);
+ }
+ else
+ {
+ tmpEngine.init();
}
-
}
+ catch (RuntimeException rexp)
+ {
+ throw rexp;
+ }
+ catch (Exception exp)
+ {
+ throw new RuntimeException(exp);
+ }
+ vengine = tmpEngine;
}
-
- result = velocityEngine.evaluate(velocityContext, outPut,
VelocityScriptEngine.DEFAULT_LOG_TAG, reader);
-
- } catch (Exception exp) {
- ScriptUtil.addExceptionToErrorWriter(exp);
- throw new ScriptException(exp);
}
- return String.valueOf(result);
}
- /**
- * Executes the specified script. The default ScriptContext for the
ScriptEngine is used.
- *
- * @param s The script language source to be executed.
- * @return The value returned from the execution of the script.
- * @throws ScriptException - if error occurrs in script.
- * java.lang.NullPointerException - if either
argument is null.
- */
- public Object eval(String s) throws ScriptException {
- return eval(s, scriptContext);
- }
-
-
- /**
- * Same as eval(String) except that the source of the script is provided
as a Reader
- *
- * @param reader The source of the script.
- * @return The value returned by the script.
- * @throws ScriptException
- */
- public Object eval(Reader reader) throws ScriptException {
- return eval(reader, scriptContext);
- }
-
-
- /**
- * Executes the script using the Bindings argument as the ENGINE_SCOPE
Bindings of the ScriptEngine during the script
- * execution. The Reader, Writer and non-ENGINE_SCOPE Bindings of the
default ScriptContext are used.
- * The ENGINE_SCOPE Bindings of the ScriptEngine is not changed, and its
mappings are unaltered by the script execution.
- *
- * @param s The source for the script.
- * @param bindings The Bindings of attributes to be used for script
execution.
- * @return The value returned by the script.
- * @throws ScriptException
- */
- public Object eval(String s, Bindings bindings) throws ScriptException {
- ScriptContext scriptContext =
getGeneratedScriptContextFromBinding(bindings);
- return eval(new StringReader(s), scriptContext);
- }
-
-
- /**
- * Same as eval(String, Bindings) except that the source of the script is
provided as a Reader.
- *
- * @param reader The source of the script.
- * @param bindings The Bindings of attributes to be used for script
execution.
- * @return The value returned by the script.
- * @throws ScriptException
- */
- public Object eval(Reader reader, Bindings bindings) throws
ScriptException {
- ScriptContext scriptContext =
getGeneratedScriptContextFromBinding(bindings);
- return eval(reader, scriptContext);
- }
-
- private ScriptContext getGeneratedScriptContextFromBinding(Bindings
bindings) {
- ScriptContext tmpContext = new VelocityScriptContext();
- Bindings globalScope =
scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE);
-
- //Setting global and engine scopes to context
- if (globalScope != null) {
- tmpContext.setBindings(globalScope, ScriptContext.GLOBAL_SCOPE);
- }
-
- if (bindings != null) {
- tmpContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
- } else {
- ScriptUtil.addExceptionToErrorWriter(new NullPointerException("Engine
scope Bindings cannot be null."));
- throw new NullPointerException("Engine scope Bindings cannot be
null.");
- }
-
- tmpContext.setReader(scriptContext.getReader());
- tmpContext.setWriter(scriptContext.getWriter());
- tmpContext.setErrorWriter(scriptContext.getErrorWriter());
-
- return tmpContext;
- }
-
- /**
- * Sets a key/value pair in the state of the ScriptEngine that may either
create a Java Language Binding to be used in the
- * execution of scripts or be used in some other way, depending on whether
the key is reserved. Must have the same effect
- * as getBindings(ScriptContext.ENGINE_SCOPE).put.
- *
- * @param s The name of named value to add
- * @param o The value of named value to add.
- * Throws:
- * java.lang.NullPointerException - if key is null.
- * java.lang.IllegalArgumentException - if key is empty.
- */
- public void put(String s, Object o) {
-
- if (s == null) {
- ScriptUtil.addExceptionToErrorWriter(new NullPointerException("Name
cannot be null"));
- throw new NullPointerException("Name cannot be null");
- }
-
- if ("".equals(s)) {
- ScriptUtil.addExceptionToErrorWriter(new IllegalArgumentException("Name
cannot be empty"));
- throw new IllegalArgumentException("Name cannot be empty");
- }
-
- Bindings engineScope =
scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
- engineScope.put(s, o);
- }
-
-
- /**
- * Retrieves a value set in the state of this engine. The value might be
one which was set using setValue or some other value in
- * the state of the ScriptEngine, depending on the implementation. Must
have the same effect as getBindings
- * (ScriptContext.ENGINE_SCOPE).get
- *
- * @param s The key whose value is to be returned
- * @return the value for the given key
- * Throws:
- * java.lang.NullPointerException - if key is null.
- * java.lang.IllegalArgumentException - if key is empty.
- */
- public Object get(String s) {
-
- if (s == null) {
- ScriptUtil.addExceptionToErrorWriter(new NullPointerException("Name
cannot be null"));
- throw new NullPointerException("Name cannot be null");
- }
-
- if ("".equals(s)) {
- ScriptUtil.addExceptionToErrorWriter(new IllegalArgumentException("Name
cannot be empty"));
- throw new IllegalArgumentException("Name cannot be empty");
- }
-
- Bindings engineScope =
scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
- return engineScope.get(s);
- }
-
-
- /**
- * The Bindings instances that are returned must be identical to those
returned by the getBindings method of ScriptContext
- * called with corresponding arguments on the default ScriptContext of the
ScriptEngine.
- *
- * @param i scope
- * @return The Bindings with the specified scope.
- */
- public Bindings getBindings(int i) {
- return scriptContext.getBindings(i);
- }
-
-
- /**
- * Sets a scope of named values to be used by scripts. The possible scopes
are:
- * ScriptContext.ENGINE_SCOPE - The specified Bindings replaces the engine
scope of the ScriptEngine.
- * ScriptContext.GLOBAL_SCOPE - The specified Bindings must be visible as
the GLOBAL_SCOPE.
- * Any other value of scope defined in the default ScriptContext of the
ScriptEngine.
- *
- * @param bindings The Bindings for the specified scope.
- * @param i The specified scope. Either ScriptContext.ENGINE_SCOPE,
ScriptContext.GLOBAL_SCOPE, or any other valid value of scope.
- */
- public void setBindings(Bindings bindings, int i) {
- scriptContext.setBindings(bindings, i);
- }
-
-
- /**
- * @return A Bindings that can be used to replace the state of this
ScriptEngine.
- */
- public Bindings createBindings() {
- return new VelocityBindings();
- }
-
- /**
- * Returns the default ScriptContext of the ScriptEngine whose Bindings,
Reader and Writers are used for script executions when no ScriptContext is
specified.
- *
- * @return The default ScriptContext of the ScriptEngine.
- */
- public ScriptContext getContext() {
- return scriptContext;
- }
-
-
- /**
- * Sets the default ScriptContext of the ScriptEngine whose Bindings,
Reader and Writers are used for script executions when no ScriptContext is
specified.
- *
- * @param scriptContext A ScriptContext that will replace the default
ScriptContext in the ScriptEngine.
- * Throws: java.lang.NullPointerException - if
context is null.
- */
- public void setContext(ScriptContext scriptContext) {
- if (scriptContext == null) {
- throw new NullPointerException("script context cannot be null");
- }
-
- this.scriptContext = scriptContext;
- }
-
- private VelocityContext getVelocityContext(ScriptContext ctx) {
+ private static VelocityContext getVelocityContext(ScriptContext ctx)
+ {
+ ctx.setAttribute("context", ctx, ScriptContext.ENGINE_SCOPE);
+ Bindings globalScope = ctx.getBindings(ScriptContext.GLOBAL_SCOPE);
Bindings engineScope = ctx.getBindings(ScriptContext.ENGINE_SCOPE);
- if (ctx.getBindings(ScriptContext.GLOBAL_SCOPE) == null) {
+ if (globalScope != null)
+ {
+ return new VelocityContext(engineScope, new
VelocityContext(globalScope));
+ }
+ else
+ {
return new VelocityContext(engineScope);
- } else {
- return new VelocityContext(engineScope, new
VelocityContext(ctx.getBindings(ScriptContext.GLOBAL_SCOPE)));
}
}
- private String getTargetFilename(ScriptContext ctx) {
+ private static String getFilename(ScriptContext ctx)
+ {
Object fileName = ctx.getAttribute(ScriptEngine.FILENAME);
- if (fileName != null) {
- return fileName.toString();
- } else {
- return "No-Such-File";
+ return fileName != null? fileName.toString() : "<unknown>";
+ }
+
+ private static boolean isStringOutputMode(ScriptContext ctx)
+ {
+ Object flag = ctx.getAttribute(STRING_OUTPUT_MODE_KEY);
+ return Boolean.parseBoolean(String.valueOf(flag));
+ }
+
+ private static Properties getVelocityProperties(ScriptContext ctx)
+ {
+ try
+ {
+ Object props = ctx.getAttribute(VELOCITY_PROPERTIES_KEY);
+ if (props instanceof Properties)
+ {
+ return (Properties) props;
+ }
+ else
+ {
+ String propsName = System.getProperty(VELOCITY_PROPERTIES_KEY);
+ if (propsName != null)
+ {
+ File propsFile = new File(propsName);
+ if (propsFile.exists() && propsFile.canRead())
+ {
+ Properties p = new Properties();
+ p.load(new FileInputStream(propsFile));
+ return p;
+ }
+ }
+ }
}
+ catch (Exception exp)
+ {
+ System.err.println(exp);
+ }
+ return null;
}
}
Modified:
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptEngineFactory.java
URL:
http://svn.apache.org/viewvc/velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptEngineFactory.java?rev=1752882&r1=1752881&r2=1752882&view=diff
==============================================================================
---
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptEngineFactory.java
(original)
+++
velocity/engine/trunk/velocity-engine-scripting/src/main/java/org/apache/velocity/script/VelocityScriptEngineFactory.java
Fri Jul 15 22:30:59 2016
@@ -1,304 +1,184 @@
-package org.apache.velocity.script;
-/*
- * 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.
- */
-
-import javax.script.ScriptEngine;
-import javax.script.ScriptEngineFactory;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * VelocityScriptEngineFactory is used to describe and instantiate
ScriptEngines.
- * There are two fundamental ways to instantiate this.
- *
- * 1. Create a factory by providing only name and version and allows to
inherit default factory settings.
- * 2. Create a factory by providing all required attributes i.e List<String>
names, List<String> extensions
- * List<String> mimeTypes , String name,String version, String langName,
String langVersion
- */
-public class VelocityScriptEngineFactory implements ScriptEngineFactory {
-
- /**
- * names of the script engine
- */
- private List<String> names;
-
-
- /**
- * List of extensions for script engine
- */
- private List<String> extensions;
-
-
- /**
- * List of mime types for script engine
- */
- private List<String> mimeTypes;
-
- /**
- * Default name of the engine
- */
- private String name = "velocity";
-
-
- /**
- * Default version of the engine
- */
- private String version = "1.8";
-
-
- /**
- * Default script language name
- */
- private String langName = "velocity";
-
-
- /**
- * Default version of the script language
- */
- private String langVersion = "1.8";
-
-
- /**
- * Provides full capability to change default engine settings
- *
- * @param names Override default names for script engine
- * @param extensions Override default extensions for script engine
- * @param mimeTypes Override default mime types for script engine
- * @param name Override default name for script engine
- * @param version Override default version for script engine
- * @param langName Override default language names for script engine
- * @param langVersion Override default language version for script engine
- */
- public VelocityScriptEngineFactory(List<String> names, List<String>
extensions
- , List<String> mimeTypes
- , String name
- , String version
- , String langName
- , String langVersion
- ) {
- this.names = Collections.unmodifiableList(names);
- this.extensions = Collections.unmodifiableList(extensions);
- this.mimeTypes = Collections.unmodifiableList(mimeTypes);
- this.name = name;
- this.version = version;
- this.langName = langName;
- this.langVersion = langVersion;
- }
-
- /**
- * @param name Override default name for script engine
- * @param version Override default version for script engine
- */
- public VelocityScriptEngineFactory(String name, String version) {
- this.name = name;
- this.version = version;
- initDefaultSettings();
- }
-
- /**
- * Simple Factory with all default settings
- */
- public VelocityScriptEngineFactory() {
- initDefaultSettings();
- }
-
- private void initDefaultSettings() {
- names = new ArrayList<String>(1);
- names.add("Velocity");
- names = Collections.unmodifiableList(names);
- extensions = new ArrayList<String>(3);
- extensions.add("vm");
- extensions.add("vtl");
- extensions.add("vhtml");
- extensions = Collections.unmodifiableList(extensions);
- mimeTypes = new ArrayList<String>(1);
- mimeTypes.add("text/x-velocity");
- mimeTypes = Collections.unmodifiableList(mimeTypes);
- }
-
- /**
- * Returns the full name of the ScriptEngine.
- * @return
- */
- public String getEngineName() {
- return name;
- }
-
-
- /**
- * Returns the version of the ScriptEngine.
- * @return
- */
- public String getEngineVersion() {
- return version;
- }
-
-
- /**
- * Returns an immutable list of filename extensions, which generally
identify scripts written in the language
- * supported by this ScriptEngine.
- * @return
- */
- public List<String> getExtensions() {
- return extensions;
- }
-
-
- /**
- * Returns an immutable list of mimetypes, associated with scripts that
can be executed by the engine.
- * @return
- */
- public List<String> getMimeTypes() {
- return mimeTypes;
- }
-
-
- /**
- * Returns an immutable list of short names for the ScriptEngine, which
may be used to identify the ScriptEngine by the ScriptEngineManager.
- * @return
- */
- public List<String> getNames() {
- return names;
- }
-
-
- /**
- * Returns the name of the scripting langauge supported by this
ScriptEngine.
- * @return
- */
- public String getLanguageName() {
- return langName;
- }
-
-
- /**
- * Returns the version of the scripting language supported by this
ScriptEngine.
- * @return
- */
- public String getLanguageVersion() {
- return langVersion;
- }
-
-
-
- /**
- * Returns the value of an attribute whose meaning may be
implementation-specific.
- * @param s
- * @return
- */
- public Object getParameter(String s) {
- if (s.equals(ScriptEngine.ENGINE)) {
- return getEngineName();
- } else if (s.equals(ScriptEngine.NAME)) {
- return getNames().get(0);
- } else if (s.equals(ScriptEngine.LANGUAGE)) {
- return getLanguageName();
- } else if (s.equals(ScriptEngine.ENGINE_VERSION)) {
- return getEngineVersion();
- } else if (s.equals(ScriptEngine.LANGUAGE_VERSION)) {
- return getLanguageVersion();
- } else if (s.equals("THREADING")) {
- return "MULTITHREADED";
- } else {
- return null;
- }
- }
-
-
-
- /**
- *
- * @param s Name of the Object to whom the method belongs to
- * @param s1 Name of the method
- * @param strings method arguments to be passed
- * @return the method syntax for velocity script
- */
- public String getMethodCallSyntax(String s, String s1, String... strings) {
- StringBuilder syntax = new StringBuilder();
- syntax.append("$");
- syntax.append("{");
- syntax.append(s);
- syntax.append(".");
- syntax.append(s1);
- syntax.append("(");
- if (strings.length != 0) {
- int i = 0;
- for (; i < strings.length - 1; i++) {
- syntax.append("$" + strings[i]);
- syntax.append(", ");
- }
- syntax.append("$" + strings[i]);
- }
- syntax.append(")");
- syntax.append("}");
- return syntax.toString();
- }
-
-
-
- /**
- *
- * @param s String to display
- * @return //TODO
- */
- public String getOutputStatement(String s) {
- StringBuilder output = new StringBuilder();
- output.append("${context.getWriter().write(\"");
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
- switch (ch) {
- case '"':
- output.append("\\\"");
- break;
- case '\\':
- output.append("\\\\");
- break;
- default:
- output.append(ch);
- break;
- }
- }
- output.append("\")}");
- return output.toString();
- }
-
-
- /**
- * Returns A valid scripting language executable progam with given
statements.
- * @param strings scripting statements provided
- * @return the program from the statements given
- */
- public String getProgram(String... strings) {
- StringBuilder program = new StringBuilder();
- for (int i = 0; i < strings.length; i++) {
- program.append(strings[i]);
- program.append("\n");
- }
- return program.toString();
- }
-
- /**
- * Returns an instance of the ScriptEngine associated with this
ScriptEngineFactory
- * @return
- */
- public ScriptEngine getScriptEngine() {
- return new VelocityScriptEngine(this);
- }
-}
+package org.apache.velocity.script;
+
+/* dual licencing... */
+
+/*
+ * 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.
+ */
+
+/*
+ * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
+ * Use is subject to license terms.
+ *
+ * Redistribution and use in source and binary forms, with or without
modification, are
+ * permitted provided that the following conditions are met: Redistributions
of source code
+ * must retain the above copyright notice, this list of conditions and the
following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
this list of
+ * conditions and the following disclaimer in the documentation and/or other
materials
+ * provided with the distribution. Neither the name of the Sun Microsystems
nor the names of
+ * is contributors may be used to endorse or promote products derived from
this software
+ * without specific prior written permission.
+
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER
+ * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Factory class for the Velocity scripting interface. Please refer to the
+ * javax.script.ScriptEngineFactory documentation for details.
+ *
+ * @author A. Sundararajan
+ * @author <a href="mailto:claude.bris...@gmail.com">Claude Brisson</a>
+ * @version $Id: VelocityScriptEngineFactory.java$
+ */
+
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Properties;
+
+public class VelocityScriptEngineFactory implements ScriptEngineFactory
+{
+
+ private static final String VELOCITY_NAME = "Velocity";
+ private static final String VELOCITY_VERSION = "2.0";
+ private static final String VELOCITY_LANGUAGE = "VTL";
+
+ private static List<String> names;
+ private static List<String> extensions;
+ private static List<String> mimeTypes;
+
+ private static Properties parameters;
+
+ static
+ {
+ names = new ArrayList();
+ names.add("velocity");
+ names.add("Velocity");
+ names = Collections.unmodifiableList(names);
+ extensions = new ArrayList();
+ extensions.add("vm");
+ extensions.add("vtl");
+ extensions.add("vhtml");
+ extensions = Collections.unmodifiableList(extensions);
+ mimeTypes = new ArrayList();
+ mimeTypes.add("text/x-velocity");
+ mimeTypes = Collections.unmodifiableList(mimeTypes);
+ parameters = new Properties();
+ parameters.put(ScriptEngine.NAME, VELOCITY_NAME);
+ parameters.put(ScriptEngine.ENGINE_VERSION, VELOCITY_VERSION);
+ parameters.put(ScriptEngine.ENGINE, VELOCITY_NAME);
+ parameters.put(ScriptEngine.LANGUAGE, VELOCITY_LANGUAGE);
+ parameters.put(ScriptEngine.LANGUAGE_VERSION, VELOCITY_VERSION);
+ parameters.put("THREADING", "MULTITHREADED");
+ }
+
+ public String getEngineName()
+ {
+ return VELOCITY_NAME;
+ }
+
+ public String getEngineVersion()
+ {
+ return VELOCITY_VERSION;
+ }
+
+ public List<String> getExtensions()
+ {
+ return extensions;
+ }
+
+ public String getLanguageName()
+ {
+ return VELOCITY_NAME;
+ }
+
+ public String getLanguageVersion()
+ {
+ return VELOCITY_VERSION;
+ }
+
+ public String getMethodCallSyntax(String obj, String m, String... args)
+ {
+ StringBuilder buf = new StringBuilder();
+ buf.append("${");
+ buf.append(obj);
+ buf.append(".");
+ buf.append(m);
+ buf.append("(");
+ if (args.length != 0)
+ {
+ int i = 0;
+ for (; i < args.length - 1; i++)
+ {
+ buf.append("$" + args[i]);
+ buf.append(", ");
+ }
+ buf.append("$" + args[i]);
+ }
+ buf.append(")}");
+ return buf.toString();
+ }
+
+ public List<String> getMimeTypes()
+ {
+ return mimeTypes;
+ }
+
+ public List<String> getNames()
+ {
+ return names;
+ }
+
+ public String getOutputStatement(String toDisplay)
+ {
+ StringBuilder buf = new StringBuilder();
+ buf.append("#[[").append(toDisplay).append("]]#");
+ return buf.toString();
+ }
+
+ public String getParameter(String key)
+ {
+ return parameters.getProperty(key);
+ }
+
+ public String getProgram(String... statements)
+ {
+ StringBuilder buf = new StringBuilder();
+ for (int i = 0; i < statements.length; i++)
+ {
+ buf.append(statements[i]);
+ buf.append("\n");
+ }
+ return buf.toString();
+ }
+
+ public ScriptEngine getScriptEngine()
+ {
+ return new VelocityScriptEngine(this);
+ }
+}
Modified:
velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/ScriptEngineTest.java
URL:
http://svn.apache.org/viewvc/velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/ScriptEngineTest.java?rev=1752882&r1=1752881&r2=1752882&view=diff
==============================================================================
---
velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/ScriptEngineTest.java
(original)
+++
velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/ScriptEngineTest.java
Fri Jul 15 22:30:59 2016
@@ -65,29 +65,13 @@ public class ScriptEngineTest extends Ab
}
public void testEngineEvals() throws ScriptException {
- String path =
ScriptEngineTest.class.getProtectionDomain().getCodeSource().getLocation().getPath();
- String propertyFile =
path.substring(0,path.indexOf("target/test-classes")) +
-
"src/test/java/org/apache/velocity/script/test/resources/velocity.properties";
- System.setProperty(VelocityScriptEngine.VELOCITY_PROPERTIES,
propertyFile) ;
- //Comment test case
-
+ String path = System.getProperty("test.resources.dir");
Writer writer = new StringWriter();
engine.getContext().setWriter(writer);
- String script = "<html>\n" +
- "<body>\n" +
- "#set( $foo = \"Velocity\" )\n" +
- "Hello $foo World!\n" +
- "</body>\n" +
- "<html>";
-// String script = "## This is a comment ";
+ engine.getContext().setAttribute(VelocityScriptEngine.VELOCITY_PROPERTIES_KEY,
path + "/test-classes/velocity.properties", ScriptContext.ENGINE_SCOPE);
+ engine.getContext().setAttribute(VelocityScriptEngine.STRING_OUTPUT_MODE_KEY,
"true", ScriptContext.ENGINE_SCOPE);
+ String script = "<html><body>#set( $foo = 'Velocity' )Hello $foo
World!</body><html>";
Object result = engine.eval(script);
- assertTrue(Boolean.valueOf(result.toString()));
- System.out.println(">>>"+writer);
- //TODO add more engine script evaluation test cases
-
+ assertEquals(String.valueOf(result), "<html><body>Hello Velocity
World!</body><html>");
}
-
-
-
-
}
Modified:
velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/VelocityScriptContextTest.java
URL:
http://svn.apache.org/viewvc/velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/VelocityScriptContextTest.java?rev=1752882&r1=1752881&r2=1752882&view=diff
==============================================================================
---
velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/VelocityScriptContextTest.java
(original)
+++
velocity/engine/trunk/velocity-engine-scripting/src/test/java/org/apache/velocity/script/test/VelocityScriptContextTest.java
Fri Jul 15 22:30:59 2016
@@ -19,8 +19,9 @@ package org.apache.velocity.script.test;
* under the License.
*/
-import org.apache.velocity.script.VelocityBindings;
+import javax.script.Bindings;
import javax.script.ScriptContext;
+import javax.script.SimpleBindings;
import java.util.List;
@@ -41,7 +42,7 @@ public class VelocityScriptContextTest e
public void testScopes() {
- VelocityBindings velocityBindings = new VelocityBindings();
+ Bindings velocityBindings = new SimpleBindings();
engine.getContext().setBindings(velocityBindings,
ScriptContext.ENGINE_SCOPE);
assertNotNull(engine.getBindings(ScriptContext.ENGINE_SCOPE));
assertNotNull("Engines Registered through manager sets the global
scope", engine.getBindings(ScriptContext.GLOBAL_SCOPE));
@@ -88,7 +89,7 @@ public class VelocityScriptContextTest e
}
try {
- context.setBindings(new VelocityBindings(), invalidScope);
+ context.setBindings(new SimpleBindings(), invalidScope);
fail("Cannot pass invalid scope");
} catch (IllegalArgumentException n) {
//Success
@@ -156,5 +157,3 @@ public class VelocityScriptContextTest e
}
}
-
-