You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cayenne.apache.org by nt...@apache.org on 2017/08/16 15:36:55 UTC

[03/13] cayenne git commit: Own template render implementation: first draft

Own template render implementation: first draft


Project: http://git-wip-us.apache.org/repos/asf/cayenne/repo
Commit: http://git-wip-us.apache.org/repos/asf/cayenne/commit/55e3c975
Tree: http://git-wip-us.apache.org/repos/asf/cayenne/tree/55e3c975
Diff: http://git-wip-us.apache.org/repos/asf/cayenne/diff/55e3c975

Branch: refs/heads/master
Commit: 55e3c975bfe3195f5bb87900a207c88878b799a5
Parents: a6c5efb
Author: Nikita Timofeev <st...@gmail.com>
Authored: Mon Aug 7 17:49:03 2017 +0300
Committer: Nikita Timofeev <st...@gmail.com>
Committed: Wed Aug 16 18:29:23 2017 +0300

----------------------------------------------------------------------
 .../template/CayenneSQLTemplateProcessor.java   |   69 +
 .../org/apache/cayenne/template/Context.java    |   80 +
 .../org/apache/cayenne/template/Directive.java  |   31 +
 .../apache/cayenne/template/directive/Bind.java |   56 +
 .../cayenne/template/parser/ASTBlock.java       |   44 +
 .../cayenne/template/parser/ASTBoolScalar.java  |   37 +
 .../cayenne/template/parser/ASTDirective.java   |   43 +
 .../cayenne/template/parser/ASTExpression.java  |   61 +
 .../cayenne/template/parser/ASTFloatScalar.java |   43 +
 .../cayenne/template/parser/ASTIfElse.java      |   46 +
 .../cayenne/template/parser/ASTIntScalar.java   |   48 +
 .../cayenne/template/parser/ASTMethod.java      |  100 ++
 .../template/parser/ASTStringScalar.java        |   32 +
 .../apache/cayenne/template/parser/ASTText.java |   31 +
 .../cayenne/template/parser/ASTVariable.java    |   73 +
 .../cayenne/template/parser/ExpressionNode.java |   37 +
 .../parser/JJTSQLTemplateParserState.java       |  123 ++
 .../cayenne/template/parser/JavaCharStream.java |  610 ++++++++
 .../apache/cayenne/template/parser/Node.java    |   70 +
 .../cayenne/template/parser/ParseException.java |  192 +++
 .../template/parser/SQLTemplateParser.java      |  634 ++++++++
 .../parser/SQLTemplateParserConstants.java      |  143 ++
 .../parser/SQLTemplateParserTokenManager.java   | 1440 ++++++++++++++++++
 .../parser/SQLTemplateParserTreeConstants.java  |   35 +
 .../cayenne/template/parser/ScalarNode.java     |   65 +
 .../cayenne/template/parser/SimpleNode.java     |   90 ++
 .../apache/cayenne/template/parser/Token.java   |  150 ++
 .../cayenne/template/parser/TokenMgrError.java  |  166 ++
 .../template/parser/SQLTemplateParser.jjt       |  327 ++++
 29 files changed, 4876 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/CayenneSQLTemplateProcessor.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/CayenneSQLTemplateProcessor.java b/cayenne-server/src/main/java/org/apache/cayenne/template/CayenneSQLTemplateProcessor.java
new file mode 100644
index 0000000..062f1c5
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/CayenneSQLTemplateProcessor.java
@@ -0,0 +1,69 @@
+/*****************************************************************
+ *   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.cayenne.template;
+
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.cayenne.CayenneRuntimeException;
+import org.apache.cayenne.access.jdbc.SQLStatement;
+import org.apache.cayenne.access.jdbc.SQLTemplateProcessor;
+import org.apache.cayenne.template.parser.ASTBlock;
+import org.apache.cayenne.template.parser.ParseException;
+import org.apache.cayenne.template.parser.SQLTemplateParser;
+
+
+/**
+ * @since 4.1
+ */
+public class CayenneSQLTemplateProcessor implements SQLTemplateProcessor {
+
+    @Override
+    public SQLStatement processTemplate(String template, Map<String, ?> parameters) {
+        Context context = new Context();
+        context.addParameters(parameters);
+        return process(template, context);
+    }
+
+    @Override
+    public SQLStatement processTemplate(String template, List<Object> positionalParameters) {
+        Context context = new Context();
+        Map<String, Object> parameters = new HashMap<>();
+        int i=0;
+        for(Object param : positionalParameters) {
+            parameters.put(String.valueOf(i++), param);
+        }
+        context.addParameters(parameters);
+        return process(template, context);
+    }
+
+    protected SQLStatement process(String template, Context context) {
+        SQLTemplateParser parser = new SQLTemplateParser(new StringReader(template));
+        try {
+            ASTBlock block = parser.template();
+            String sql = block.evaluate(context);
+            return new SQLStatement(sql, context.getColumnDescriptors(), context.getParameterBindings());
+        } catch (ParseException ex) {
+            throw new CayenneRuntimeException("Error parsing template '%s' : %s", template, ex.getMessage());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/Context.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/Context.java b/cayenne-server/src/main/java/org/apache/cayenne/template/Context.java
new file mode 100644
index 0000000..7ccb911
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/Context.java
@@ -0,0 +1,80 @@
+/*****************************************************************
+ *   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.cayenne.template;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.cayenne.access.jdbc.ColumnDescriptor;
+import org.apache.cayenne.access.translator.ParameterBinding;
+import org.apache.cayenne.template.directive.Bind;
+
+/**
+ * @since 4.1
+ */
+public class Context {
+
+    Map<String, Directive> directives = new HashMap<>();
+
+    Map<String, Object> objects = new HashMap<>();
+
+    List<ParameterBinding> parameterBindings = new ArrayList<>();
+
+    List<ColumnDescriptor> columnDescriptors = new ArrayList<>();
+
+    public Context() {
+        directives.put("bind", new Bind());
+    }
+
+    public Directive getDirective(String name) {
+        return directives.get(name);
+    }
+
+    public Object getObject(String name) {
+        return objects.get(name);
+    }
+
+    public void addParameters(Map<String, ?> parameters) {
+        objects.putAll(parameters);
+    }
+
+    public void addDirective(String name, Directive directive) {
+        directives.put(name, directive);
+    }
+
+    public void addParameterBinding(ParameterBinding binding) {
+        parameterBindings.add(binding);
+    }
+
+    public void addColumnDescriptor(ColumnDescriptor descriptor) {
+        columnDescriptors.add(descriptor);
+    }
+
+    public ColumnDescriptor[] getColumnDescriptors() {
+        return columnDescriptors.toArray(new ColumnDescriptor[0]);
+    }
+
+    public ParameterBinding[] getParameterBindings() {
+        return parameterBindings.toArray(new ParameterBinding[0]);
+    }
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/Directive.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/Directive.java b/cayenne-server/src/main/java/org/apache/cayenne/template/Directive.java
new file mode 100644
index 0000000..94c0818
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/Directive.java
@@ -0,0 +1,31 @@
+/*****************************************************************
+ *   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.cayenne.template;
+
+import org.apache.cayenne.template.parser.ASTExpression;
+
+/**
+ * @since 4.1
+ */
+public interface Directive {
+
+    String apply(Context context, ASTExpression... expressions);
+
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/directive/Bind.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/directive/Bind.java b/cayenne-server/src/main/java/org/apache/cayenne/template/directive/Bind.java
new file mode 100644
index 0000000..b867072
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/directive/Bind.java
@@ -0,0 +1,56 @@
+/*****************************************************************
+ *   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.cayenne.template.directive;
+
+import org.apache.cayenne.access.translator.ParameterBinding;
+import org.apache.cayenne.dba.TypesMapping;
+import org.apache.cayenne.template.Context;
+import org.apache.cayenne.template.Directive;
+import org.apache.cayenne.template.parser.ASTExpression;
+
+/**
+ * @since 4.1
+ */
+public class Bind implements Directive {
+
+    @Override
+    public String apply(Context context, ASTExpression... expressions) {
+        if(expressions.length < 2) {
+            throw new IllegalArgumentException();
+        }
+
+        Object value = expressions[0].evaluateAsObject(context);
+        String jdbcTypeName = expressions[1].evaluate(context);
+        int jdbcType;
+        if (jdbcTypeName != null) {
+            jdbcType = TypesMapping.getSqlTypeByName(jdbcTypeName);
+        } else if (value != null) {
+            jdbcType = TypesMapping.getSqlTypeByJava(value.getClass());
+        } else {
+            jdbcType = TypesMapping.getSqlTypeByName(TypesMapping.SQL_NULL);
+        }
+        int scale = expressions.length < 3 ? -1 : (int)expressions[2].evaluateAsLong(context);
+
+        ParameterBinding binding = new ParameterBinding(value, jdbcType, scale);
+        context.addParameterBinding(binding);
+
+        return "?";
+    }
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTBlock.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTBlock.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTBlock.java
new file mode 100644
index 0000000..743756f
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTBlock.java
@@ -0,0 +1,44 @@
+/*****************************************************************
+ *   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.cayenne.template.parser;
+
+import org.apache.cayenne.template.Context;
+
+/**
+ * This is a root node of parsed template.
+ * It can be nested inside #if .. #else .. #end directive.
+ *
+ * @since 4.1
+ */
+public class ASTBlock extends SimpleNode {
+
+    public ASTBlock(int id) {
+        super(id);
+    }
+
+    @Override
+    public String evaluate(Context context) {
+        StringBuilder builder = new StringBuilder();
+        for(Node node : children) {
+            builder.append(node.evaluate(context));
+        }
+        return builder.toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTBoolScalar.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTBoolScalar.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTBoolScalar.java
new file mode 100644
index 0000000..de279c0
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTBoolScalar.java
@@ -0,0 +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.cayenne.template.parser;
+
+import org.apache.cayenne.template.Context;
+
+/**
+ * @since 4.1
+ */
+public class ASTBoolScalar extends ScalarNode<Boolean> {
+
+    public ASTBoolScalar(int id) {
+        super(id);
+    }
+
+    @Override
+    public boolean evaluateAsBoolean(Context context) {
+        return value == null ? false : value;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTDirective.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTDirective.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTDirective.java
new file mode 100644
index 0000000..67f4f3c
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTDirective.java
@@ -0,0 +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.cayenne.template.parser;
+
+import org.apache.cayenne.template.Context;
+import org.apache.cayenne.template.Directive;
+
+/**
+ * @since 4.1
+ */
+public class ASTDirective extends IdentifierNode {
+
+    public ASTDirective(int id) {
+        super(id);
+    }
+
+    @Override
+    public String evaluate(Context context) {
+        Directive directive = context.getDirective(getIdentifier());
+        if(directive == null) {
+            return "";
+        }
+
+        return directive.apply(context, (ASTExpression[]) children);
+    }
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTExpression.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTExpression.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTExpression.java
new file mode 100644
index 0000000..0ade66b
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTExpression.java
@@ -0,0 +1,61 @@
+/*****************************************************************
+ *   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.cayenne.template.parser;
+
+import org.apache.cayenne.template.Context;
+
+/**
+ * @since 4.1
+ */
+public class ASTExpression extends SimpleNode implements ExpressionNode {
+
+    public ASTExpression(int id) {
+        super(id);
+    }
+
+    protected ExpressionNode getChildAsExpressionNode(int child) {
+        return (ExpressionNode)jjtGetChild(child);
+    }
+
+    @Override
+    public String evaluate(Context context) {
+        return jjtGetChild(0).evaluate(context);
+    }
+
+    @Override
+    public Object evaluateAsObject(Context context) {
+        return getChildAsExpressionNode(0).evaluateAsLong(context);
+    }
+
+    @Override
+    public long evaluateAsLong(Context context) {
+        return getChildAsExpressionNode(0).evaluateAsLong(context);
+    }
+
+    @Override
+    public double evaluateAsDouble(Context context) {
+        return getChildAsExpressionNode(0).evaluateAsDouble(context);
+    }
+
+    @Override
+    public boolean evaluateAsBoolean(Context context) {
+        return getChildAsExpressionNode(0).evaluateAsBoolean(context);
+    }
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTFloatScalar.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTFloatScalar.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTFloatScalar.java
new file mode 100644
index 0000000..a46db69
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTFloatScalar.java
@@ -0,0 +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.cayenne.template.parser;
+
+import org.apache.cayenne.template.Context;
+
+/**
+ * @since 4.1
+ */
+public class ASTFloatScalar extends ScalarNode<Double> {
+
+    public ASTFloatScalar(int id) {
+        super(id);
+    }
+
+    @Override
+    public boolean evaluateAsBoolean(Context context) {
+        return value != null && value > 0;
+    }
+
+    @Override
+    public double evaluateAsDouble(Context context) {
+        return value;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTIfElse.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTIfElse.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTIfElse.java
new file mode 100644
index 0000000..d117777
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTIfElse.java
@@ -0,0 +1,46 @@
+/*****************************************************************
+ *   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.cayenne.template.parser;
+
+import org.apache.cayenne.template.Context;
+
+/**
+ * @since 4.1
+ */
+public class ASTIfElse extends SimpleNode {
+
+    public ASTIfElse(int id) {
+        super(id);
+    }
+
+    @Override
+    public String evaluate(Context context) {
+        ASTExpression condition = (ASTExpression)jjtGetChild(0);
+        if (condition.evaluateAsBoolean(context)) {
+            return jjtGetChild(1).evaluate(context);
+        } else {
+            // else is optional
+            if(jjtGetNumChildren() > 2) {
+                return jjtGetChild(2).evaluate(context);
+            }
+            return "";
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTIntScalar.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTIntScalar.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTIntScalar.java
new file mode 100644
index 0000000..efd3c47
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTIntScalar.java
@@ -0,0 +1,48 @@
+/*****************************************************************
+ *   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.cayenne.template.parser;
+
+import org.apache.cayenne.template.Context;
+
+/**
+ * @since 4.1
+ */
+public class ASTIntScalar extends ScalarNode<Long> {
+
+    public ASTIntScalar(int id) {
+        super(id);
+    }
+
+    @Override
+    public boolean evaluateAsBoolean(Context context) {
+        return value != null && value > 0;
+    }
+
+    @Override
+    public long evaluateAsLong(Context context) {
+        return value;
+    }
+
+    @Override
+    public double evaluateAsDouble(Context context) {
+        return value;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTMethod.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTMethod.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTMethod.java
new file mode 100644
index 0000000..50961c6
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTMethod.java
@@ -0,0 +1,100 @@
+/*****************************************************************
+ *   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.cayenne.template.parser;
+
+import java.lang.reflect.Method;
+import java.util.Objects;
+
+import org.apache.cayenne.reflect.PropertyUtils;
+import org.apache.cayenne.template.Context;
+
+/**
+ * @since 4.1
+ */
+public class ASTMethod extends IdentifierNode {
+
+    protected Object parentObject;
+
+    public ASTMethod(int id) {
+        super(id);
+    }
+
+    protected void setParentObject(Object parentObject) {
+        this.parentObject = Objects.requireNonNull(parentObject);
+    }
+
+    /**
+     * Evaluate method call to an Object
+     */
+    public Object evaluateAsObject(Context context) {
+        if(parentObject == null) {
+            throw new IllegalStateException("To evaluate method node parent object should be set.");
+        }
+
+        try {
+            // first try default property resolution
+            return PropertyUtils.getProperty(parentObject, getIdentifier());
+        } catch (IllegalArgumentException ex) {
+            // if it fails, try direct method call
+            methodsLoop:
+            for(Method m : parentObject.getClass().getMethods()) {
+                if(m.getName().equals(getIdentifier())) {
+                    // check count of arguments
+                    if(m.getParameterTypes().length != jjtGetNumChildren()) {
+                        continue;
+                    }
+                    int i = 0;
+                    Object[] arguments = new Object[jjtGetNumChildren()];
+                    for(Class<?> parameterType : m.getParameterTypes()) {
+                        ASTExpression child = (ASTExpression)jjtGetChild(i);
+                        if(parameterType.isAssignableFrom(Double.class)) {
+                            arguments[i] = child.evaluateAsDouble(context);
+                        } else if(parameterType.isAssignableFrom(Long.class)) {
+                            arguments[i] = child.evaluateAsLong(context);
+                        } else if(parameterType.isAssignableFrom(Boolean.class)) {
+                            arguments[i] = child.evaluateAsBoolean(context);
+                        } else if(parameterType.isAssignableFrom(String.class)) {
+                            arguments[i] = child.evaluate(context);
+                        } else {
+                            continue methodsLoop;
+                        }
+                        i++;
+                    }
+
+                    try {
+                        return m.invoke(parentObject, arguments);
+                    } catch (Exception ignored) {
+                        // continue
+                    }
+                }
+            }
+        }
+
+        throw new IllegalArgumentException("Unable to resolve method " + getIdentifier() +
+                " with " + jjtGetNumChildren() + " args for object " + parentObject);
+    }
+
+    @Override
+    public String evaluate(Context context) {
+        Object object = evaluateAsObject(context);
+        return object == null ? "" : object.toString();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTStringScalar.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTStringScalar.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTStringScalar.java
new file mode 100644
index 0000000..b955f83
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTStringScalar.java
@@ -0,0 +1,32 @@
+/*****************************************************************
+ *   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.cayenne.template.parser;
+
+/**
+ * @since 4.1
+ */
+public class ASTStringScalar extends ScalarNode<String> {
+
+    public ASTStringScalar(int id) {
+        super(id);
+    }
+
+}
+

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTText.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTText.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTText.java
new file mode 100644
index 0000000..ead03cc
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTText.java
@@ -0,0 +1,31 @@
+/*****************************************************************
+ *   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.cayenne.template.parser;
+
+/**
+ * @since 4.1
+ */
+public class ASTText extends ScalarNode<String> {
+
+    public ASTText(int id) {
+        super(id);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTVariable.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTVariable.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTVariable.java
new file mode 100644
index 0000000..b72d59b
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ASTVariable.java
@@ -0,0 +1,73 @@
+/*****************************************************************
+ *   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.cayenne.template.parser;
+
+import java.util.Objects;
+
+import org.apache.cayenne.template.Context;
+
+/**
+ * @since 4.1
+ */
+public class ASTVariable extends IdentifierNode implements ExpressionNode {
+
+    public ASTVariable(int id) {
+        super(id);
+    }
+
+    public Object evaluateAsObject(Context context) {
+        Object object = context.getObject(getIdentifier());
+        if(object == null) {
+            return null;
+        }
+        for(int i=0; i<jjtGetNumChildren(); i++) {
+            ASTMethod method = (ASTMethod)jjtGetChild(i);
+            method.setParentObject(object);
+            object = method.evaluateAsObject(context);
+            if(object == null) {
+                return null;
+            }
+        }
+        return object;
+    }
+
+    @Override
+    public String evaluate(Context context) {
+        Object object = evaluateAsObject(context);
+        return object == null ? "" : object.toString();
+    }
+
+    @Override
+    public long evaluateAsLong(Context context) {
+        Number object = (Number) Objects.requireNonNull(evaluateAsObject(context));
+        return object.longValue();
+    }
+
+    @Override
+    public double evaluateAsDouble(Context context) {
+        Number object = (Number) Objects.requireNonNull(evaluateAsObject(context));
+        return object.doubleValue();
+    }
+
+    @Override
+    public boolean evaluateAsBoolean(Context context) {
+        return (Boolean) Objects.requireNonNull(evaluateAsObject(context));
+    }
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ExpressionNode.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ExpressionNode.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ExpressionNode.java
new file mode 100644
index 0000000..735badf
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ExpressionNode.java
@@ -0,0 +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.cayenne.template.parser;
+
+import org.apache.cayenne.template.Context;
+
+/**
+ * @since 4.1
+ */
+public interface ExpressionNode {
+
+    Object evaluateAsObject(Context context);
+
+    long evaluateAsLong(Context context);
+
+    double evaluateAsDouble(Context context);
+
+    boolean evaluateAsBoolean(Context context);
+
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/JJTSQLTemplateParserState.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/JJTSQLTemplateParserState.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/JJTSQLTemplateParserState.java
new file mode 100644
index 0000000..955cfcb
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/JJTSQLTemplateParserState.java
@@ -0,0 +1,123 @@
+/* Generated By:JavaCC: Do not edit this line. JJTSQLTemplateParserState.java Version 5.0 */
+package org.apache.cayenne.template.parser;
+
+public class JJTSQLTemplateParserState {
+  private java.util.List<Node> nodes;
+  private java.util.List<Integer> marks;
+
+  private int sp;        // number of nodes on stack
+  private int mk;        // current mark
+  private boolean node_created;
+
+  public JJTSQLTemplateParserState() {
+    nodes = new java.util.ArrayList<Node>();
+    marks = new java.util.ArrayList<Integer>();
+    sp = 0;
+    mk = 0;
+  }
+
+  /* Determines whether the current node was actually closed and
+     pushed.  This should only be called in the final user action of a
+     node scope.  */
+  public boolean nodeCreated() {
+    return node_created;
+  }
+
+  /* Call this to reinitialize the node stack.  It is called
+     automatically by the parser's ReInit() method. */
+  public void reset() {
+    nodes.clear();
+    marks.clear();
+    sp = 0;
+    mk = 0;
+  }
+
+  /* Returns the root node of the AST.  It only makes sense to call
+     this after a successful parse. */
+  public Node rootNode() {
+    return nodes.get(0);
+  }
+
+  /* Pushes a node on to the stack. */
+  public void pushNode(Node n) {
+    nodes.add(n);
+    ++sp;
+  }
+
+  /* Returns the node on the top of the stack, and remove it from the
+     stack.  */
+  public Node popNode() {
+    if (--sp < mk) {
+      mk = marks.remove(marks.size()-1);
+    }
+    return nodes.remove(nodes.size()-1);
+  }
+
+  /* Returns the node currently on the top of the stack. */
+  public Node peekNode() {
+    return nodes.get(nodes.size()-1);
+  }
+
+  /* Returns the number of children on the stack in the current node
+     scope. */
+  public int nodeArity() {
+    return sp - mk;
+  }
+
+
+  public void clearNodeScope(Node n) {
+    while (sp > mk) {
+      popNode();
+    }
+    mk = marks.remove(marks.size()-1);
+  }
+
+
+  public void openNodeScope(Node n) {
+    marks.add(mk);
+    mk = sp;
+    n.jjtOpen();
+  }
+
+
+  /* A definite node is constructed from a specified number of
+     children.  That number of nodes are popped from the stack and
+     made the children of the definite node.  Then the definite node
+     is pushed on to the stack. */
+  public void closeNodeScope(Node n, int num) {
+    mk = marks.remove(marks.size()-1);
+    while (num-- > 0) {
+      Node c = popNode();
+      c.jjtSetParent(n);
+      n.jjtAddChild(c, num);
+    }
+    n.jjtClose();
+    pushNode(n);
+    node_created = true;
+  }
+
+
+  /* A conditional node is constructed if its condition is true.  All
+     the nodes that have been pushed since the node was opened are
+     made children of the conditional node, which is then pushed
+     on to the stack.  If the condition is false the node is not
+     constructed and they are left on the stack. */
+  public void closeNodeScope(Node n, boolean condition) {
+    if (condition) {
+      int a = nodeArity();
+      mk = marks.remove(marks.size()-1);
+      while (a-- > 0) {
+        Node c = popNode();
+        c.jjtSetParent(n);
+        n.jjtAddChild(c, a);
+      }
+      n.jjtClose();
+      pushNode(n);
+      node_created = true;
+    } else {
+      mk = marks.remove(marks.size()-1);
+      node_created = false;
+    }
+  }
+}
+/* JavaCC - OriginalChecksum=1706cef4cf4b627318940a448e5ee9ea (do not edit this line) */

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/JavaCharStream.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/JavaCharStream.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/JavaCharStream.java
new file mode 100644
index 0000000..535ed3b
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/JavaCharStream.java
@@ -0,0 +1,610 @@
+/*****************************************************************
+ *   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.cayenne.template.parser;
+
+/**
+ * An implementation of interface CharStream, where the stream is assumed to
+ * contain only ASCII characters (with java-like unicode escape processing).
+ *
+ * @since 4.1
+ */
+public class JavaCharStream {
+
+    /**
+     * Whether parser is static.
+     */
+    public static final boolean staticFlag = false;
+
+    static int hexval(char c) throws java.io.IOException {
+        switch (c) {
+            case '0':
+                return 0;
+            case '1':
+                return 1;
+            case '2':
+                return 2;
+            case '3':
+                return 3;
+            case '4':
+                return 4;
+            case '5':
+                return 5;
+            case '6':
+                return 6;
+            case '7':
+                return 7;
+            case '8':
+                return 8;
+            case '9':
+                return 9;
+
+            case 'a':
+            case 'A':
+                return 10;
+            case 'b':
+            case 'B':
+                return 11;
+            case 'c':
+            case 'C':
+                return 12;
+            case 'd':
+            case 'D':
+                return 13;
+            case 'e':
+            case 'E':
+                return 14;
+            case 'f':
+            case 'F':
+                return 15;
+        }
+
+        throw new java.io.IOException(); // Should never come here
+    }
+
+    /**
+     * Position in buffer.
+     */
+    public int bufpos = -1;
+    int bufsize;
+    int available;
+    int tokenBegin;
+    protected int bufline[];
+    protected int bufcolumn[];
+
+    protected int column = 0;
+    protected int line = 1;
+
+    protected boolean prevCharIsCR = false;
+    protected boolean prevCharIsLF = false;
+
+    protected java.io.Reader inputStream;
+
+    protected char[] nextCharBuf;
+    protected char[] buffer;
+    protected int maxNextCharInd = 0;
+    protected int nextCharInd = -1;
+    protected int inBuf = 0;
+    protected int tabSize = 8;
+
+    protected void setTabSize(int i) {
+        tabSize = i;
+    }
+
+    protected int getTabSize(int i) {
+        return tabSize;
+    }
+
+    protected void ExpandBuff(boolean wrapAround) {
+        char[] newbuffer = new char[bufsize + 2048];
+        int newbufline[] = new int[bufsize + 2048];
+        int newbufcolumn[] = new int[bufsize + 2048];
+
+        try {
+            if (wrapAround) {
+                System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
+                System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);
+                buffer = newbuffer;
+
+                System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
+                System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
+                bufline = newbufline;
+
+                System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
+                System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
+                bufcolumn = newbufcolumn;
+
+                bufpos += (bufsize - tokenBegin);
+            } else {
+                System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
+                buffer = newbuffer;
+
+                System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
+                bufline = newbufline;
+
+                System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
+                bufcolumn = newbufcolumn;
+
+                bufpos -= tokenBegin;
+            }
+        } catch (Throwable t) {
+            throw new Error(t.getMessage());
+        }
+
+        available = (bufsize += 2048);
+        tokenBegin = 0;
+    }
+
+    protected void FillBuff() throws java.io.IOException {
+        int i;
+        if (maxNextCharInd == 4096)
+            maxNextCharInd = nextCharInd = 0;
+
+        try {
+            if ((i = inputStream.read(nextCharBuf, maxNextCharInd,
+                    4096 - maxNextCharInd)) == -1) {
+                inputStream.close();
+                throw new java.io.IOException();
+            } else
+                maxNextCharInd += i;
+        } catch (java.io.IOException e) {
+            if (bufpos != 0) {
+                --bufpos;
+                backup(0);
+            } else {
+                bufline[bufpos] = line;
+                bufcolumn[bufpos] = column;
+            }
+            throw e;
+        }
+    }
+
+    protected char ReadByte() throws java.io.IOException {
+        if (++nextCharInd >= maxNextCharInd)
+            FillBuff();
+
+        return nextCharBuf[nextCharInd];
+    }
+
+    /**
+     * @return starting character for token.
+     */
+    public char BeginToken() throws java.io.IOException {
+        if (inBuf > 0) {
+            --inBuf;
+
+            if (++bufpos == bufsize)
+                bufpos = 0;
+
+            tokenBegin = bufpos;
+            return buffer[bufpos];
+        }
+
+        tokenBegin = 0;
+        bufpos = -1;
+
+        return readChar();
+    }
+
+    protected void AdjustBuffSize() {
+        if (available == bufsize) {
+            if (tokenBegin > 2048) {
+                bufpos = 0;
+                available = tokenBegin;
+            } else
+                ExpandBuff(false);
+        } else if (available > tokenBegin)
+            available = bufsize;
+        else if ((tokenBegin - available) < 2048)
+            ExpandBuff(true);
+        else
+            available = tokenBegin;
+    }
+
+    protected void UpdateLineColumn(char c) {
+        column++;
+
+        if (prevCharIsLF) {
+            prevCharIsLF = false;
+            line += (column = 1);
+        } else if (prevCharIsCR) {
+            prevCharIsCR = false;
+            if (c == '\n') {
+                prevCharIsLF = true;
+            } else
+                line += (column = 1);
+        }
+
+        switch (c) {
+            case '\r':
+                prevCharIsCR = true;
+                break;
+            case '\n':
+                prevCharIsLF = true;
+                break;
+            case '\t':
+                column--;
+                column += (tabSize - (column % tabSize));
+                break;
+            default:
+                break;
+        }
+
+        bufline[bufpos] = line;
+        bufcolumn[bufpos] = column;
+    }
+
+    /**
+     * Read a character.
+     */
+    public char readChar() throws java.io.IOException {
+        if (inBuf > 0) {
+            --inBuf;
+
+            if (++bufpos == bufsize)
+                bufpos = 0;
+
+            return buffer[bufpos];
+        }
+
+        char c;
+
+        if (++bufpos == available)
+            AdjustBuffSize();
+
+        if ((buffer[bufpos] = c = ReadByte()) == '\\') {
+            UpdateLineColumn(c);
+
+            int backSlashCnt = 1;
+
+            for (; ; ) // Read all the backslashes
+            {
+                if (++bufpos == available)
+                    AdjustBuffSize();
+
+                try {
+                    if ((buffer[bufpos] = c = ReadByte()) != '\\') {
+                        UpdateLineColumn(c);
+                        // found a non-backslash char.
+                        if ((c == 'u') && ((backSlashCnt & 1) == 1)) {
+                            if (--bufpos < 0)
+                                bufpos = bufsize - 1;
+
+                            break;
+                        }
+
+                        backup(backSlashCnt);
+                        return '\\';
+                    }
+                } catch (java.io.IOException e) {
+                    // We are returning one backslash so we should only backup (count-1)
+                    if (backSlashCnt > 1)
+                        backup(backSlashCnt - 1);
+
+                    return '\\';
+                }
+
+                UpdateLineColumn(c);
+                backSlashCnt++;
+            }
+
+            // Here, we have seen an odd number of backslash's followed by a 'u'
+            try {
+                while ((c = ReadByte()) == 'u')
+                    ++column;
+
+                buffer[bufpos] = c = (char) (hexval(c) << 12 |
+                        hexval(ReadByte()) << 8 |
+                        hexval(ReadByte()) << 4 |
+                        hexval(ReadByte()));
+
+                column += 4;
+            } catch (java.io.IOException e) {
+                throw new Error("Invalid escape character at line " + line +
+                        " column " + column + ".");
+            }
+
+            if (backSlashCnt == 1)
+                return c;
+            else {
+                backup(backSlashCnt - 1);
+                return '\\';
+            }
+        } else {
+            UpdateLineColumn(c);
+            return c;
+        }
+    }
+
+    /**
+     * Get end column.
+     */
+    public int getEndColumn() {
+        return bufcolumn[bufpos];
+    }
+
+    /**
+     * Get end line.
+     */
+    public int getEndLine() {
+        return bufline[bufpos];
+    }
+
+    /**
+     * @return column of token start
+     */
+    public int getBeginColumn() {
+        return bufcolumn[tokenBegin];
+    }
+
+    /**
+     * @return line number of token start
+     */
+    public int getBeginLine() {
+        return bufline[tokenBegin];
+    }
+
+    /**
+     * Retreat.
+     */
+    public void backup(int amount) {
+
+        inBuf += amount;
+        if ((bufpos -= amount) < 0)
+            bufpos += bufsize;
+    }
+
+    /**
+     * Constructor.
+     */
+    public JavaCharStream(java.io.Reader dstream,
+                          int startline, int startcolumn, int buffersize) {
+        inputStream = dstream;
+        line = startline;
+        column = startcolumn - 1;
+
+        available = bufsize = buffersize;
+        buffer = new char[buffersize];
+        bufline = new int[buffersize];
+        bufcolumn = new int[buffersize];
+        nextCharBuf = new char[4096];
+    }
+
+    /**
+     * Constructor.
+     */
+    public JavaCharStream(java.io.Reader dstream,
+                          int startline, int startcolumn) {
+        this(dstream, startline, startcolumn, 4096);
+    }
+
+    /**
+     * Constructor.
+     */
+    public JavaCharStream(java.io.Reader dstream) {
+        this(dstream, 1, 1, 4096);
+    }
+
+    /**
+     * Reinitialise.
+     */
+    public void ReInit(java.io.Reader dstream,
+                       int startline, int startcolumn, int buffersize) {
+        inputStream = dstream;
+        line = startline;
+        column = startcolumn - 1;
+
+        if (buffer == null || buffersize != buffer.length) {
+            available = bufsize = buffersize;
+            buffer = new char[buffersize];
+            bufline = new int[buffersize];
+            bufcolumn = new int[buffersize];
+            nextCharBuf = new char[4096];
+        }
+        prevCharIsLF = prevCharIsCR = false;
+        tokenBegin = inBuf = maxNextCharInd = 0;
+        nextCharInd = bufpos = -1;
+    }
+
+    /**
+     * Reinitialise.
+     */
+    public void ReInit(java.io.Reader dstream,
+                       int startline, int startcolumn) {
+        ReInit(dstream, startline, startcolumn, 4096);
+    }
+
+    /**
+     * Reinitialise.
+     */
+    public void ReInit(java.io.Reader dstream) {
+        ReInit(dstream, 1, 1, 4096);
+    }
+
+    /**
+     * Constructor.
+     */
+    public JavaCharStream(java.io.InputStream dstream, String encoding, int startline,
+                          int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException {
+        this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
+    }
+
+    /**
+     * Constructor.
+     */
+    public JavaCharStream(java.io.InputStream dstream, int startline,
+                          int startcolumn, int buffersize) {
+        this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096);
+    }
+
+    /**
+     * Constructor.
+     */
+    public JavaCharStream(java.io.InputStream dstream, String encoding, int startline,
+                          int startcolumn) throws java.io.UnsupportedEncodingException {
+        this(dstream, encoding, startline, startcolumn, 4096);
+    }
+
+    /**
+     * Constructor.
+     */
+    public JavaCharStream(java.io.InputStream dstream, int startline,
+                          int startcolumn) {
+        this(dstream, startline, startcolumn, 4096);
+    }
+
+    /**
+     * Constructor.
+     */
+    public JavaCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException {
+        this(dstream, encoding, 1, 1, 4096);
+    }
+
+    /**
+     * Constructor.
+     */
+    public JavaCharStream(java.io.InputStream dstream) {
+        this(dstream, 1, 1, 4096);
+    }
+
+    /**
+     * Reinitialise.
+     */
+    public void ReInit(java.io.InputStream dstream, String encoding, int startline,
+                       int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException {
+        ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
+    }
+
+    /**
+     * Reinitialise.
+     */
+    public void ReInit(java.io.InputStream dstream, int startline,
+                       int startcolumn, int buffersize) {
+        ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
+    }
+
+    /**
+     * Reinitialise.
+     */
+    public void ReInit(java.io.InputStream dstream, String encoding, int startline,
+                       int startcolumn) throws java.io.UnsupportedEncodingException {
+        ReInit(dstream, encoding, startline, startcolumn, 4096);
+    }
+
+    /**
+     * Reinitialise.
+     */
+    public void ReInit(java.io.InputStream dstream, int startline,
+                       int startcolumn) {
+        ReInit(dstream, startline, startcolumn, 4096);
+    }
+
+    /**
+     * Reinitialise.
+     */
+    public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException {
+        ReInit(dstream, encoding, 1, 1, 4096);
+    }
+
+    /**
+     * Reinitialise.
+     */
+    public void ReInit(java.io.InputStream dstream) {
+        ReInit(dstream, 1, 1, 4096);
+    }
+
+    /**
+     * @return token image as String
+     */
+    public String GetImage() {
+        if (bufpos >= tokenBegin)
+            return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
+        else
+            return new String(buffer, tokenBegin, bufsize - tokenBegin) +
+                    new String(buffer, 0, bufpos + 1);
+    }
+
+    /**
+     * @return suffix
+     */
+    public char[] GetSuffix(int len) {
+        char[] ret = new char[len];
+
+        if ((bufpos + 1) >= len)
+            System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
+        else {
+            System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
+                    len - bufpos - 1);
+            System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
+        }
+
+        return ret;
+    }
+
+    /**
+     * Set buffers back to null when finished.
+     */
+    public void Done() {
+        nextCharBuf = null;
+        buffer = null;
+        bufline = null;
+        bufcolumn = null;
+    }
+
+    /**
+     * Method to adjust line and column numbers for the start of a token.
+     */
+    public void adjustBeginLineColumn(int newLine, int newCol) {
+        int start = tokenBegin;
+        int len;
+
+        if (bufpos >= tokenBegin) {
+            len = bufpos - tokenBegin + inBuf + 1;
+        } else {
+            len = bufsize - tokenBegin + bufpos + 1 + inBuf;
+        }
+
+        int i = 0, j = 0, k = 0;
+        int nextColDiff = 0, columnDiff = 0;
+
+        while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) {
+            bufline[j] = newLine;
+            nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
+            bufcolumn[j] = newCol + columnDiff;
+            columnDiff = nextColDiff;
+            i++;
+        }
+
+        if (i < len) {
+            bufline[j] = newLine++;
+            bufcolumn[j] = newCol + columnDiff;
+
+            while (i++ < len) {
+                if (bufline[j = start % bufsize] != bufline[++start % bufsize])
+                    bufline[j] = newLine++;
+                else
+                    bufline[j] = newLine;
+            }
+        }
+
+        line = bufline[j];
+        column = bufcolumn[j];
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/Node.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/Node.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/Node.java
new file mode 100644
index 0000000..15d5b1a
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/Node.java
@@ -0,0 +1,70 @@
+/*****************************************************************
+ *   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.cayenne.template.parser;
+
+import org.apache.cayenne.template.Context;
+
+/**
+ * All AST nodes must implement this interface.  It provides basic
+ * machinery for constructing the parent and child relationships
+ * between nodes.
+ * @since 4.1
+ */
+public interface Node {
+
+    /**
+     * This method is called after the node has been made the current
+     * node.  It indicates that child nodes can now be added to it.
+     */
+    void jjtOpen();
+
+    /**
+     * This method is called after all the child nodes have been
+     * added.
+     */
+    void jjtClose();
+
+    /**
+     * This pair of methods are used to inform the node of its
+     * parent.
+     */
+    void jjtSetParent(Node n);
+
+    Node jjtGetParent();
+
+    /**
+     * This method tells the node to add its argument to the node's
+     * list of children.
+     */
+    void jjtAddChild(Node n, int i);
+
+    /**
+     * This method returns a child node.  The children are numbered
+     * from zero, left to right.
+     */
+    Node jjtGetChild(int i);
+
+    /**
+     * Return the number of children the node has.
+     */
+    int jjtGetNumChildren();
+
+    String evaluate(Context context);
+}

http://git-wip-us.apache.org/repos/asf/cayenne/blob/55e3c975/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ParseException.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ParseException.java b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ParseException.java
new file mode 100644
index 0000000..a838ddd
--- /dev/null
+++ b/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ParseException.java
@@ -0,0 +1,192 @@
+/*****************************************************************
+ *   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.cayenne.template.parser;
+
+/**
+ * This exception is thrown when parse errors are encountered.
+ * You can explicitly create objects of this exception type by
+ * calling the method generateParseException in the generated
+ * parser.
+ * <p>
+ * You can modify this class to customize your error reporting
+ * mechanisms so long as you retain the public fields.
+ *
+ * @since 4.1
+ */
+public class ParseException extends Exception {
+
+    /**
+     * The version identifier for this Serializable class.
+     * Increment only if the <i>serialized</i> form of the
+     * class changes.
+     */
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * This is the last token that has been consumed successfully.  If
+     * this object has been created due to a parse error, the token
+     * following this token will (therefore) be the first error token.
+     */
+    public Token currentToken;
+
+    /**
+     * Each entry in this array is an array of integers.  Each array
+     * of integers represents a sequence of tokens (by their ordinal
+     * values) that is expected at this point of the parse.
+     */
+    public int[][] expectedTokenSequences;
+
+    /**
+     * This is a reference to the "tokenImage" array of the generated
+     * parser within which the parse error occurred.  This array is
+     * defined in the generated ...Constants interface.
+     */
+    public String[] tokenImage;
+
+    /**
+     * This constructor is used by the method "generateParseException"
+     * in the generated parser.  Calling this constructor generates
+     * a new object of this type with the fields "currentToken",
+     * "expectedTokenSequences", and "tokenImage" set.
+     */
+    public ParseException(Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal) {
+        super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));
+        currentToken = currentTokenVal;
+        expectedTokenSequences = expectedTokenSequencesVal;
+        tokenImage = tokenImageVal;
+    }
+
+    /**
+     * The following constructors are for use by you for whatever
+     * purpose you can think of.  Constructing the exception in this
+     * manner makes the exception behave in the normal way - i.e., as
+     * documented in the class "Throwable".  The fields "errorToken",
+     * "expectedTokenSequences", and "tokenImage" do not contain
+     * relevant information.  The JavaCC generated code does not use
+     * these constructors.
+     */
+
+    public ParseException() {
+        super();
+    }
+
+    /**
+     * Constructor with message.
+     */
+    public ParseException(String message) {
+        super(message);
+    }
+
+    /**
+     * It uses "currentToken" and "expectedTokenSequences" to generate a parse
+     * error message and returns it.  If this object has been created
+     * due to a parse error, and you do not catch it (it gets thrown
+     * from the parser) the correct error message
+     * gets displayed.
+     */
+    private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) {
+        String eol = System.getProperty("line.separator", "\n");
+        StringBuilder expected = new StringBuilder();
+        int maxSize = 0;
+        for (int[] expectedTokenSequence : expectedTokenSequences) {
+            if (maxSize < expectedTokenSequence.length) {
+                maxSize = expectedTokenSequence.length;
+            }
+            for (int anExpectedTokenSequence : expectedTokenSequence) {
+                expected.append(tokenImage[anExpectedTokenSequence]).append(' ');
+            }
+            if (expectedTokenSequence[expectedTokenSequence.length - 1] != 0) {
+                expected.append("...");
+            }
+            expected.append(eol).append("    ");
+        }
+        StringBuilder retval = new StringBuilder("Encountered \"");
+        Token tok = currentToken.next;
+        for (int i = 0; i < maxSize; i++) {
+            if (i != 0) retval.append(" ");
+            if (tok.kind == 0) {
+                retval.append(tokenImage[0]);
+                break;
+            }
+            retval.append(" ").append(tokenImage[tok.kind]);
+            retval.append(" \"");
+            retval.append(add_escapes(tok.image));
+            retval.append(" \"");
+            tok = tok.next;
+        }
+        retval.append("\" at line ").append(currentToken.next.beginLine).append(", column ").append(currentToken.next.beginColumn);
+        retval.append(".").append(eol);
+        if (expectedTokenSequences.length == 1) {
+            retval.append("Was expecting:").append(eol).append("    ");
+        } else {
+            retval.append("Was expecting one of:").append(eol).append("    ");
+        }
+        retval.append(expected.toString());
+        return retval.toString();
+    }
+
+    /**
+     * Used to convert raw characters to their escaped version
+     * when these raw version cannot be used as part of an ASCII
+     * string literal.
+     */
+    static String add_escapes(String str) {
+        StringBuilder retval = new StringBuilder();
+        char ch;
+        for (int i = 0; i < str.length(); i++) {
+            switch (str.charAt(i)) {
+                case 0:
+                    continue;
+                case '\b':
+                    retval.append("\\b");
+                    continue;
+                case '\t':
+                    retval.append("\\t");
+                    continue;
+                case '\n':
+                    retval.append("\\n");
+                    continue;
+                case '\f':
+                    retval.append("\\f");
+                    continue;
+                case '\r':
+                    retval.append("\\r");
+                    continue;
+                case '\"':
+                    retval.append("\\\"");
+                    continue;
+                case '\'':
+                    retval.append("\\\'");
+                    continue;
+                case '\\':
+                    retval.append("\\\\");
+                    continue;
+                default:
+                    if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
+                        String s = "0000" + Integer.toString(ch, 16);
+                        retval.append("\\u").append(s.substring(s.length() - 4, s.length()));
+                    } else {
+                        retval.append(ch);
+                    }
+            }
+        }
+        return retval.toString();
+    }
+}