|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object org.apache.commons.jexl2.JexlEngine
public class JexlEngine
Creates and evaluates Expression and Script objects. Determines the behavior of Expressions & Scripts during their evaluation with respect to:
Uberspect
JexlArithmetic
The setSilent
and setLenient
methods allow to fine-tune an engine instance behavior
according to various error control needs. The lenient/strict flag tells the engine when and if null as operand is
considered an error, the silent/verbose flag tells the engine what to do with the error
(log as warning or throw exception).
0 & null should be indicators of "default" values so that even in an case of error, something meaningfull can still be inferred; may be convenient for configurations.
One should probably consider using null as an error case - ie, every object manipulated by JEXL should be valued; the ternary operator, especially the '?:' form can be used to workaround exceptional cases. Use case could be configuration with no implicit values or defaults.
The error control grain is roughly on par with JEXL 1.0
The finest error control grain is obtained; it is the closest to Java code - still augmented by "script" capabilities regarding automated conversions & type matching.
Note that methods that evaluate expressions may throw unchecked exceptions;
The JexlException
are thrown in "non-silent" mode but since these are
RuntimeException, user-code should catch them wherever most appropriate.
Nested Class Summary | |
---|---|
static class |
JexlEngine.Frame
A call frame, created from a scope, stores the arguments and local variables as "registers". |
static class |
JexlEngine.Scope
A script scope, stores the declaration of parameters and local variables. |
protected class |
JexlEngine.SoftCache<K,V>
A soft reference on cache. |
Field Summary | |
---|---|
protected JexlArithmetic |
arithmetic
The JexlArithmetic instance. |
protected JexlEngine.SoftCache<String,ASTJexlScript> |
cache
The expression cache. |
protected boolean |
debug
Whether error messages will carry debugging information. |
static JexlContext |
EMPTY_CONTEXT
An empty/static/non-mutable JexlContext used instead of null context. |
protected Map<String,Object> |
functions
The map of 'prefix:function' to object implementing the functions. |
protected org.apache.commons.logging.Log |
logger
The Log to which all JexlEngine messages will be logged. |
protected Parser |
parser
The singleton ExpressionFactory also holds a single instance of Parser . |
protected boolean |
silent
Whether expressions evaluated by this engine will throw exceptions (false) or return null (true) on errors. |
protected Uberspect |
uberspect
The Uberspect instance. |
Constructor Summary | |
---|---|
JexlEngine()
Creates an engine with default arguments. |
|
JexlEngine(Uberspect anUberspect,
JexlArithmetic anArithmetic,
Map<String,Object> theFunctions,
org.apache.commons.logging.Log log)
Creates a JEXL engine using the provided Uberspect , (@link JexlArithmetic),
a function map and logger. |
Method Summary | ||
---|---|---|
static String |
cleanExpression(CharSequence str)
Trims the expression from front & ending spaces. |
|
void |
clearCache()
Clears the expression cache. |
|
protected
|
createCache(int cacheSize)
Creates a cache. |
|
protected Expression |
createExpression(ASTJexlScript tree,
String text)
An overridable through covariant return Expression creator. |
|
Expression |
createExpression(String expression)
Creates an Expression from a String containing valid JEXL syntax. |
|
Expression |
createExpression(String expression,
JexlInfo info)
Creates an Expression from a String containing valid JEXL syntax. |
|
protected JexlInfo |
createInfo(String fn,
int l,
int c)
Creates a JexlInfo instance. |
|
protected Interpreter |
createInterpreter(JexlContext context)
Creates an interpreter. |
|
protected Interpreter |
createInterpreter(JexlContext context,
boolean strictFlag,
boolean silentFlag)
Creates an interpreter. |
|
protected Script |
createScript(ASTJexlScript tree,
String text)
An overridable through covariant return Script creator. |
|
Script |
createScript(File scriptFile)
Creates a Script from a File containing valid JEXL syntax. |
|
Script |
createScript(String scriptText)
Creates a Script from a String containing valid JEXL syntax. |
|
Script |
createScript(String scriptText,
JexlInfo info)
Deprecated. Use createScript(String, JexlInfo, String[]) |
|
Script |
createScript(String scriptText,
JexlInfo info,
String[] names)
Creates a Script from a String containing valid JEXL syntax. |
|
Script |
createScript(String scriptText,
String... names)
Creates a Script from a String containing valid JEXL syntax. |
|
Script |
createScript(URL scriptUrl)
Creates a Script from a URL containing valid JEXL syntax. |
|
protected JexlInfo |
debugInfo()
Creates and fills up debugging information. |
|
protected Object |
doCreateInstance(Object clazz,
Object... args)
Creates a new instance of an object using the most appropriate constructor based on the arguments. |
|
JexlArithmetic |
getArithmetic()
Gets this engine underlying arithmetic. |
|
Map<String,Object> |
getFunctions()
Retrieves the map of function namespaces. |
|
protected String[] |
getLocalVariables(Script script)
Gets the array of local variable from a script. |
|
protected String[] |
getParameters(Script script)
Gets the array of parameters from a script. |
|
Object |
getProperty(JexlContext context,
Object bean,
String expr)
Accesses properties of a bean using an expression. |
|
Object |
getProperty(Object bean,
String expr)
Accesses properties of a bean using an expression. |
|
Uberspect |
getUberspect()
Gets this engine underlying uberspect. |
|
static Uberspect |
getUberspect(org.apache.commons.logging.Log logger)
Gets the default instance of Uberspect. |
|
protected void |
getVariables(JexlNode node,
Set<List<String>> refs,
List<String> ref)
Fills up the list of variables accessed by a node. |
|
Set<List<String>> |
getVariables(Script script)
Gets the list of variables accessed by a script. |
|
Object |
invokeMethod(Object obj,
String meth,
Object... args)
Invokes an object's method by name and arguments. |
|
boolean |
isDebug()
Checks whether this engine is in debug mode. |
|
boolean |
isLenient()
Checks whether this engine considers unknown variables, methods and constructors as errors. |
|
boolean |
isSilent()
Checks whether this engine throws JexlException during evaluation. |
|
boolean |
isStrict()
Checks whether this engine behaves in strict or lenient mode. |
|
|
newInstance(Class<? extends T> clazz,
Object... args)
Creates a new instance of an object using the most appropriate constructor based on the arguments. |
|
Object |
newInstance(String clazz,
Object... args)
Creates a new instance of an object using the most appropriate constructor based on the arguments. |
|
protected ASTJexlScript |
parse(CharSequence expression,
JexlInfo info)
Deprecated. Use parse(CharSequence, JexlInfo, Scope) instead |
|
protected ASTJexlScript |
parse(CharSequence expression,
JexlInfo info,
JexlEngine.Scope frame)
Parses an expression. |
|
static String |
readerToString(Reader scriptReader)
Read from a reader into a local buffer and return a String with the contents of the reader. |
|
void |
setCache(int size)
Sets a cache for expressions of the defined size. |
|
void |
setClassLoader(ClassLoader loader)
Sets the class loader used to discover classes in 'new' expressions. |
|
void |
setDebug(boolean flag)
Sets whether this engine reports debugging information when error occurs. |
|
void |
setFunctions(Map<String,Object> funcs)
Sets the map of function namespaces. |
|
void |
setLenient(boolean flag)
Sets whether this engine considers unknown variables, methods and constructors as errors or evaluates them as null or zero. |
|
void |
setProperty(JexlContext context,
Object bean,
String expr,
Object value)
Assign properties of a bean using an expression. |
|
void |
setProperty(Object bean,
String expr,
Object value)
Assign properties of a bean using an expression. |
|
void |
setSilent(boolean flag)
Sets whether this engine throws JexlException during evaluation when an error is triggered. |
|
void |
setStrict(boolean flag)
Sets whether this engine behaves in strict or lenient mode. |
Methods inherited from class java.lang.Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Field Detail |
---|
public static final JexlContext EMPTY_CONTEXT
protected final Uberspect uberspect
protected final JexlArithmetic arithmetic
protected final org.apache.commons.logging.Log logger
protected final Parser parser
Parser
.
When parsing expressions, ExpressionFactory synchronizes on Parser.
protected volatile boolean silent
protected volatile boolean debug
protected Map<String,Object> functions
protected JexlEngine.SoftCache<String,ASTJexlScript> cache
Constructor Detail |
---|
public JexlEngine()
public JexlEngine(Uberspect anUberspect, JexlArithmetic anArithmetic, Map<String,Object> theFunctions, org.apache.commons.logging.Log log)
Uberspect
, (@link JexlArithmetic),
a function map and logger.
anUberspect
- to allow different introspection behaviouranArithmetic
- to allow different arithmetic behaviourtheFunctions
- an optional map of functions (@link setFunctions)log
- the logger for various messagesMethod Detail |
---|
public static Uberspect getUberspect(org.apache.commons.logging.Log logger)
This is lazily initialized to avoid building a default instance if there is no use for it. The main reason for not using the default Uberspect instance is to be able to use a (low level) introspector created with a given logger instead of the default one.
logger
- the logger to use for the underlying Uberspect
public Uberspect getUberspect()
public JexlArithmetic getArithmetic()
public void setDebug(boolean flag)
This method is not thread safe; it should be called as an optional step of the JexlEngine initialization code before expression creation & evaluation.
flag
- true implies debug is on, false implies debug is off.setSilent(boolean)
,
setLenient(boolean)
public boolean isDebug()
public void setSilent(boolean flag)
This method is not thread safe; it should be called as an optional step of the JexlEngine initialization code before expression creation & evaluation.
flag
- true means no JexlException will occur, false allows themsetDebug(boolean)
,
setLenient(boolean)
public boolean isSilent()
public void setLenient(boolean flag)
This method is not thread safe; it should be called as an optional step of the JexlEngine initialization code before expression creation & evaluation.
As of 2.1, you can use a JexlThreadedArithmetic instance to allow the JexlArithmetic leniency behavior to be independently specified per thread, whilst still using a single engine.
flag
- true means no JexlException will occur, false allows themsetSilent(boolean)
,
setDebug(boolean)
public boolean isLenient()
public final void setStrict(boolean flag)
This method is not thread safe; it should be called as an optional step of the JexlEngine initialization code before expression creation & evaluation.
flag
- true for strict, false for lenientpublic final boolean isStrict()
public void setClassLoader(ClassLoader loader)
This method should be called as an optional step of the JexlEngine initialization code before expression creation & evaluation.
loader
- the class loader to usepublic void setCache(int size)
The cache will contain at most size
expressions. Note that
all JEXL caches are held through SoftReferences and may be garbage-collected.
size
- if not strictly positive, no cache is used.public void setFunctions(Map<String,Object> funcs)
This method is not thread safe; it should be called as an optional step of the JexlEngine initialization code before expression creation & evaluation.
Each entry key is used as a prefix, each entry value used as a bean implementing methods; an expression like 'nsx:method(123)' will thus be solved by looking at a registered bean named 'nsx' that implements method 'method' in that map. If all methods are static, you may use the bean class instead of an instance as value.
If the entry value is a class that has one contructor taking a JexlContext as argument, an instance of the namespace will be created at evaluation time. It might be a good idea to derive a JexlContext to carry the information used by the namespace to avoid variable space pollution and strongly type the constructor with this specialized JexlContext.
The key or prefix allows to retrieve the bean that plays the role of the namespace. If the prefix is null, the namespace is the top-level namespace allowing to define top-level user defined functions ( ie: myfunc(...) )
Note that the JexlContext is also used to try to solve top-level functions. This allows ObjectContext derived instances to call methods on the wrapped object.
funcs
- the map of functions that should not mutate after the call; if null
is passed, the empty collection is used.public Map<String,Object> getFunctions()
protected Expression createExpression(ASTJexlScript tree, String text)
text
- the script texttree
- the parse AST tree
public Expression createExpression(String expression)
expression
- A String containing valid JEXL syntax
JexlException
- An exception can be thrown if there is a problem
parsing this expression, or if the expression is neither an
expression nor a reference.public Expression createExpression(String expression, JexlInfo info)
expression
- A String containing valid JEXL syntaxinfo
- An info structure to carry debugging information if needed
JexlException
- An exception can be thrown if there is a problem
parsing this expression, or if the expression is neither an
expression or a reference.public Script createScript(String scriptText)
scriptText
- A String containing valid JEXL syntax
Script
which can be executed using a JexlContext
.
JexlException
- if there is a problem parsing the script.@Deprecated public Script createScript(String scriptText, JexlInfo info)
createScript(String, JexlInfo, String[])
scriptText
- A String containing valid JEXL syntaxinfo
- An info structure to carry debugging information if needed
Script
which can be executed using a JexlContext
.
JexlException
- if there is a problem parsing the script.public Script createScript(String scriptText, String... names)
scriptText
- A String containing valid JEXL syntaxnames
- the script parameter names
Script
which can be executed using a JexlContext
.
JexlException
- if there is a problem parsing the script.public Script createScript(String scriptText, JexlInfo info, String[] names)
scriptText
- A String containing valid JEXL syntaxinfo
- An info structure to carry debugging information if needednames
- the script parameter names
Script
which can be executed using a JexlContext
.
JexlException
- if there is a problem parsing the script.protected Script createScript(ASTJexlScript tree, String text)
text
- the script texttree
- the parse AST tree
public Script createScript(File scriptFile) throws IOException
File
containing valid JEXL syntax.
This method parses the script and validates the syntax.
scriptFile
- A File
containing valid JEXL syntax.
Must not be null. Must be a readable file.
Script
which can be executed with a
JexlContext
.
IOException
- if there is a problem reading the script.
JexlException
- if there is a problem parsing the script.public Script createScript(URL scriptUrl) throws IOException
URL
containing valid JEXL syntax.
This method parses the script and validates the syntax.
scriptUrl
- A URL
containing valid JEXL syntax.
Must not be null. Must be a readable file.
Script
which can be executed with a
JexlContext
.
IOException
- if there is a problem reading the script.
JexlException
- if there is a problem parsing the script.public Object getProperty(Object bean, String expr)
jexl.get(myobject, "foo.bar"); should equate to myobject.getFoo().getBar(); (or myobject.getFoo().get("bar"))
If the JEXL engine is silent, errors will be logged through its logger as warning.
bean
- the bean to get properties fromexpr
- the property expression
JexlException
- if there is an error parsing the expression or during evaluationpublic Object getProperty(JexlContext context, Object bean, String expr)
If the JEXL engine is silent, errors will be logged through its logger as warning.
context
- the evaluation contextbean
- the bean to get properties fromexpr
- the property expression
JexlException
- if there is an error parsing the expression or during evaluationpublic void setProperty(Object bean, String expr, Object value)
jexl.set(myobject, "foo.bar", 10); should equate to myobject.getFoo().setBar(10); (or myobject.getFoo().put("bar", 10) )
If the JEXL engine is silent, errors will be logged through its logger as warning.
bean
- the bean to set properties inexpr
- the property expressionvalue
- the value of the property
JexlException
- if there is an error parsing the expression or during evaluationpublic void setProperty(JexlContext context, Object bean, String expr, Object value)
If the JEXL engine is silent, errors will be logged through its logger as warning.
context
- the evaluation contextbean
- the bean to set properties inexpr
- the property expressionvalue
- the value of the property
JexlException
- if there is an error parsing the expression or during evaluationpublic Object invokeMethod(Object obj, String meth, Object... args)
obj
- the method's invoker objectmeth
- the method's nameargs
- the method's arguments
JexlException
- if method could not be found or failed and engine is not silentpublic <T> T newInstance(Class<? extends T> clazz, Object... args)
T
- the type of objectclazz
- the class to instantiateargs
- the constructor arguments
public Object newInstance(String clazz, Object... args)
clazz
- the name of the class to instantiate resolved through this engine's class loaderargs
- the constructor arguments
protected Object doCreateInstance(Object clazz, Object... args)
clazz
- the class to instantiateargs
- the constructor arguments
protected Interpreter createInterpreter(JexlContext context)
context
- a JexlContext; if null, the EMPTY_CONTEXT is used instead.
protected Interpreter createInterpreter(JexlContext context, boolean strictFlag, boolean silentFlag)
context
- a JexlContext; if null, the EMPTY_CONTEXT is used instead.strictFlag
- whether the interpreter runs in strict modesilentFlag
- whether the interpreter runs in silent mode
protected <K,V> Map<K,V> createCache(int cacheSize)
K
- the key typeV
- the value typecacheSize
- the cache size, must be > 0
public void clearCache()
public Set<List<String>> getVariables(Script script)
This method will visit all nodes of a script and extract all variables whether they are written in 'dot' or 'bracketed' notation. (a.b is equivalent to a['b']).
script
- the script
protected void getVariables(JexlNode node, Set<List<String>> refs, List<String> ref)
node
- the noderefs
- the set of variable being filledref
- the current variable being filledprotected String[] getParameters(Script script)
script
- the script
protected String[] getLocalVariables(Script script)
script
- the script
@Deprecated protected ASTJexlScript parse(CharSequence expression, JexlInfo info)
parse(CharSequence, JexlInfo, Scope)
instead
expression
- the expression to parseinfo
- debug information structure
JexlException
- if any error occured during parsingprotected ASTJexlScript parse(CharSequence expression, JexlInfo info, JexlEngine.Scope frame)
expression
- the expression to parseinfo
- debug information structureframe
- the script frame to use
JexlException
- if any error occured during parsingprotected JexlInfo createInfo(String fn, int l, int c)
fn
- url/file namel
- line numberc
- column number
protected JexlInfo debugInfo()
This gathers the class, method and line number of the first calling method not owned by JexlEngine, UnifiedJEXL or {Script,Expression}Factory.
public static String cleanExpression(CharSequence str)
str
- expression to clean
public static String readerToString(Reader scriptReader) throws IOException
scriptReader
- to be read.
IOException
- on any error reading the reader.
|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |