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:37:01 UTC
[09/13] cayenne git commit: CAY-2345 Own template renderer as a
replacement for Velocity - move Velocity to separate module - remove
dependencies on commons-lang
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/main/java/org/apache/cayenne/velocity/ResultDirective.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/velocity/ResultDirective.java b/cayenne-server/src/main/java/org/apache/cayenne/velocity/ResultDirective.java
deleted file mode 100644
index 5973188..0000000
--- a/cayenne-server/src/main/java/org/apache/cayenne/velocity/ResultDirective.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*****************************************************************
- * 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.velocity;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.sql.Date;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.cayenne.access.jdbc.ColumnDescriptor;
-import org.apache.cayenne.util.Util;
-import org.apache.velocity.context.InternalContextAdapter;
-import org.apache.velocity.exception.MethodInvocationException;
-import org.apache.velocity.exception.ParseErrorException;
-import org.apache.velocity.exception.ResourceNotFoundException;
-import org.apache.velocity.runtime.directive.Directive;
-import org.apache.velocity.runtime.parser.node.Node;
-
-/**
- * A custom Velocity directive to describe a ResultSet column. There are the
- * following possible invocation formats inside the template:
- *
- * <pre>
- * #result(column_name) - e.g. #result('ARTIST_ID')
- * #result(column_name java_type) - e.g. #result('ARTIST_ID' 'String')
- * #result(column_name java_type column_alias) - e.g. #result('ARTIST_ID' 'String' 'ID')
- * #result(column_name java_type column_alias data_row_key) - e.g. #result('ARTIST_ID' 'String' 'ID' 'toArtist.ID')
- * </pre>
- *
- * <p>
- * 'data_row_key' is needed if SQL 'column_alias' is not appropriate as a
- * DataRow key on the Cayenne side. One common case when this happens is when a
- * DataRow retrieved from a query is mapped using joint prefetch keys. In this
- * case DataRow must use DB_PATH expressions for joint column keys, and their
- * format is incompatible with most databases alias format.
- * </p>
- * <p>
- * Most common Java types used in JDBC can be specified without a package. This
- * includes all numeric types, primitives, String, SQL dates, BigDecimal and
- * BigInteger.
- * </p>
- *
- * @since 1.1
- */
-public class ResultDirective extends Directive {
-
- private static final Map<String, String> typesGuess;
-
- static {
- // init default types
- typesGuess = new HashMap<>();
-
- // primitives
- typesGuess.put("long", Long.class.getName());
- typesGuess.put("double", Double.class.getName());
- typesGuess.put("byte", Byte.class.getName());
- typesGuess.put("boolean", Boolean.class.getName());
- typesGuess.put("float", Float.class.getName());
- typesGuess.put("short", Short.class.getName());
- typesGuess.put("int", Integer.class.getName());
-
- // numeric
- typesGuess.put("Long", Long.class.getName());
- typesGuess.put("Double", Double.class.getName());
- typesGuess.put("Byte", Byte.class.getName());
- typesGuess.put("Boolean", Boolean.class.getName());
- typesGuess.put("Float", Float.class.getName());
- typesGuess.put("Short", Short.class.getName());
- typesGuess.put("Integer", Integer.class.getName());
-
- // other
- typesGuess.put("String", String.class.getName());
- typesGuess.put("Date", Date.class.getName());
- typesGuess.put("Time", Time.class.getName());
- typesGuess.put("Timestamp", Timestamp.class.getName());
- typesGuess.put("BigDecimal", BigDecimal.class.getName());
- typesGuess.put("BigInteger", BigInteger.class.getName());
- }
-
- @Override
- public String getName() {
- return "result";
- }
-
- @Override
- public int getType() {
- return LINE;
- }
-
- @Override
- public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException,
- ResourceNotFoundException, ParseErrorException, MethodInvocationException {
-
- String column = getChildAsString(context, node, 0);
- if (column == null) {
- throw new ParseErrorException("Column name expected at line " + node.getLine() + ", column "
- + node.getColumn());
- }
-
- String alias = getChildAsString(context, node, 2);
- String dataRowKey = getChildAsString(context, node, 3);
-
- // determine what we want to name this column in a resulting DataRow...
- String label = (!Util.isEmptyString(dataRowKey)) ? dataRowKey : (!Util.isEmptyString(alias)) ? alias : null;
-
- ColumnDescriptor columnDescriptor = new ColumnDescriptor();
- columnDescriptor.setName(column);
- columnDescriptor.setDataRowKey(label);
-
- String type = getChildAsString(context, node, 1);
- if (type != null) {
- columnDescriptor.setJavaClass(guessType(type));
- }
-
- // TODO: andrus 6/27/2007 - this is an unofficial jdbcType parameter
- // that is added
- // temporarily pending CAY-813 implementation for the sake of EJBQL
- // query...
- Object jdbcType = getChild(context, node, 4);
- if (jdbcType instanceof Number) {
- columnDescriptor.setJdbcType(((Number) jdbcType).intValue());
- }
-
- writer.write(column);
-
- // append column alias if needed.
-
- // Note that if table aliases are used, this logic will result in SQL
- // like
- // "t0.ARTIST_NAME AS ARTIST_NAME". Doing extra regex matching to handle
- // this
- // won't probably buy us much.
- if (!Util.isEmptyString(alias) && !alias.equals(column)) {
- writer.write(" AS ");
- writer.write(alias);
- }
-
- bindResult(context, columnDescriptor);
- return true;
- }
-
- protected Object getChild(InternalContextAdapter context, Node node, int i) throws MethodInvocationException {
- return (i >= 0 && i < node.jjtGetNumChildren()) ? node.jjtGetChild(i).value(context) : null;
- }
-
- /**
- * Returns a directive argument at a given index converted to String.
- *
- * @since 1.2
- */
- protected String getChildAsString(InternalContextAdapter context, Node node, int i)
- throws MethodInvocationException {
- Object value = getChild(context, node, i);
- return (value != null) ? value.toString() : null;
- }
-
- /**
- * Converts "short" type notation to the fully qualified class name. Right
- * now supports all major standard SQL types, including primitives. All
- * other types are expected to be fully qualified, and are not converted.
- */
- protected String guessType(String type) {
- String guessed = typesGuess.get(type);
- return guessed != null ? guessed : type;
- }
-
- /**
- * Adds value to the list of result columns in the context.
- */
- protected void bindResult(InternalContextAdapter context, ColumnDescriptor columnDescriptor) {
-
- Collection<Object> resultColumns = (Collection<Object>) context.getInternalUserContext().get(
- VelocitySQLTemplateProcessor.RESULT_COLUMNS_LIST_KEY);
-
- if (resultColumns != null) {
- resultColumns.add(columnDescriptor);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/main/java/org/apache/cayenne/velocity/SQLTemplateRenderingUtils.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/velocity/SQLTemplateRenderingUtils.java b/cayenne-server/src/main/java/org/apache/cayenne/velocity/SQLTemplateRenderingUtils.java
deleted file mode 100644
index 14b8646..0000000
--- a/cayenne-server/src/main/java/org/apache/cayenne/velocity/SQLTemplateRenderingUtils.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*****************************************************************
- * 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.velocity;
-
-import org.apache.cayenne.exp.ExpressionFactory;
-
-/**
- * Implements utility methods used inside Velocity templates when rendering
- * SQLTemplates.
- *
- * @since 1.1
- */
-public class SQLTemplateRenderingUtils {
- /**
- * Returns the result of evaluation of expression with object.
- */
- public Object cayenneExp(Object object, String expression) {
- return ExpressionFactory.exp(expression).evaluate(object);
- }
-}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/main/java/org/apache/cayenne/velocity/SQLTemplateResourceManager.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/velocity/SQLTemplateResourceManager.java b/cayenne-server/src/main/java/org/apache/cayenne/velocity/SQLTemplateResourceManager.java
deleted file mode 100644
index 085e2be..0000000
--- a/cayenne-server/src/main/java/org/apache/cayenne/velocity/SQLTemplateResourceManager.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*****************************************************************
- * 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.velocity;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.Map;
-
-import org.apache.commons.collections.ExtendedProperties;
-import org.apache.commons.collections.map.LRUMap;
-import org.apache.velocity.Template;
-import org.apache.velocity.exception.ParseErrorException;
-import org.apache.velocity.exception.ResourceNotFoundException;
-import org.apache.velocity.runtime.RuntimeServices;
-import org.apache.velocity.runtime.resource.Resource;
-import org.apache.velocity.runtime.resource.ResourceManager;
-import org.apache.velocity.runtime.resource.loader.ResourceLoader;
-
-/**
- * An implementation of the Velocity ResourceManager and ResourceLoader that
- * creates templates from in-memory Strings.
- *
- * @since 1.1
- */
-// class must be public since it is instantiated by Velocity via reflection.
-public class SQLTemplateResourceManager
- extends ResourceLoader
- implements ResourceManager {
-
- protected Map<String, Template> templateCache;
-
- public void initialize(RuntimeServices rs) {
- super.rsvc = rs;
- this.templateCache = new LRUMap(100);
- }
-
- public void clearCache() {
- templateCache.clear();
- }
-
- /**
- * Returns a Velocity Resource which is a Template for the given SQL.
- */
- public Resource getResource(String resourceName, int resourceType, String encoding)
- throws ResourceNotFoundException, ParseErrorException {
-
- synchronized (templateCache) {
- Template resource = templateCache.get(resourceName);
-
- if (resource == null) {
- resource = new Template();
- resource.setRuntimeServices(rsvc);
- resource.setResourceLoader(this);
- resource.setName(resourceName);
- resource.setEncoding(encoding);
- resource.process();
-
- templateCache.put(resourceName, resource);
- }
-
- return resource;
- }
- }
-
- public String getLoaderNameForResource(String resourceName) {
- return getClass().getName();
- }
-
- @Override
- public long getLastModified(Resource resource) {
- return -1;
- }
-
- @Override
- public InputStream getResourceStream(String source)
- throws ResourceNotFoundException {
- return new ByteArrayInputStream(source.getBytes());
- }
-
- @Override
- public void init(ExtendedProperties configuration) {
-
- }
-
- @Override
- public boolean isSourceModified(Resource resource) {
- return false;
- }
-}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/main/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/main/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor.java b/cayenne-server/src/main/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor.java
deleted file mode 100644
index cfa5f33..0000000
--- a/cayenne-server/src/main/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*****************************************************************
- * 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.velocity;
-
-import org.apache.cayenne.CayenneRuntimeException;
-import org.apache.cayenne.access.jdbc.ColumnDescriptor;
-import org.apache.cayenne.access.jdbc.SQLStatement;
-import org.apache.cayenne.access.jdbc.SQLTemplateProcessor;
-import org.apache.cayenne.access.translator.ParameterBinding;
-import org.apache.cayenne.exp.ExpressionException;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.context.InternalContextAdapterImpl;
-import org.apache.velocity.runtime.RuntimeConstants;
-import org.apache.velocity.runtime.RuntimeInstance;
-import org.apache.velocity.runtime.log.NullLogChute;
-import org.apache.velocity.runtime.parser.ParseException;
-import org.apache.velocity.runtime.parser.node.ASTReference;
-import org.apache.velocity.runtime.parser.node.SimpleNode;
-import org.apache.velocity.runtime.visitor.BaseVisitor;
-
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Processor for SQL velocity templates.
- *
- * @see org.apache.cayenne.query.SQLTemplate
- * @since 4.0
- */
-public class VelocitySQLTemplateProcessor implements SQLTemplateProcessor {
-
- private final class PositionalParamMapper extends BaseVisitor {
-
- private int i;
- private List<Object> positionalParams;
- private Map<String, Object> params;
-
- PositionalParamMapper(List<Object> positionalParams, Map<String, Object> params) {
- this.positionalParams = positionalParams;
- this.params = params;
- }
-
- @Override
- public Object visit(ASTReference node, Object data) {
-
- // strip off leading "$"
- String paramName = node.getFirstToken().image.substring(1);
-
- // only consider the first instance of each named parameter
- if (!params.containsKey(paramName)) {
-
- if (i >= positionalParams.size()) {
- throw new ExpressionException("Too few parameters to bind template: " + positionalParams.size());
- }
-
- params.put(paramName, positionalParams.get(i));
- i++;
- }
-
- return data;
- }
-
- void onFinish() {
- if (i < positionalParams.size()) {
- throw new ExpressionException("Too many parameters to bind template. Expected: " + i + ", actual: "
- + positionalParams.size());
- }
- }
- }
-
- static final String BINDINGS_LIST_KEY = "bindings";
- static final String RESULT_COLUMNS_LIST_KEY = "resultColumns";
- static final String HELPER_KEY = "helper";
-
- protected RuntimeInstance velocityRuntime;
- protected SQLTemplateRenderingUtils renderingUtils;
-
- public VelocitySQLTemplateProcessor() {
- this.renderingUtils = new SQLTemplateRenderingUtils();
- this.velocityRuntime = new RuntimeInstance();
-
- // set null logger
- velocityRuntime.addProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
-
- velocityRuntime
- .addProperty(RuntimeConstants.RESOURCE_MANAGER_CLASS, SQLTemplateResourceManager.class.getName());
- velocityRuntime.addProperty("userdirective", BindDirective.class.getName());
- velocityRuntime.addProperty("userdirective", BindEqualDirective.class.getName());
- velocityRuntime.addProperty("userdirective", BindNotEqualDirective.class.getName());
- velocityRuntime.addProperty("userdirective", BindObjectEqualDirective.class.getName());
- velocityRuntime.addProperty("userdirective", BindObjectNotEqualDirective.class.getName());
- velocityRuntime.addProperty("userdirective", ResultDirective.class.getName());
- velocityRuntime.addProperty("userdirective", ChainDirective.class.getName());
- velocityRuntime.addProperty("userdirective", ChunkDirective.class.getName());
- try {
- velocityRuntime.init();
- } catch (Exception ex) {
- throw new CayenneRuntimeException("Error setting up Velocity RuntimeInstance.", ex);
- }
-
- }
-
- /**
- * Builds and returns a SQLStatement based on SQL template and a set of
- * parameters. During rendering, VelocityContext exposes the following as
- * variables: all parameters in the map, {@link SQLTemplateRenderingUtils}
- * as a "helper" variable and SQLStatement object as "statement" variable.
- */
- @Override
- public SQLStatement processTemplate(String template, Map<String, ?> parameters) {
- // have to make a copy of parameter map since we are gonna modify it..
- Map<String, Object> internalParameters = (parameters != null && !parameters.isEmpty()) ? new HashMap<>(
- parameters) : new HashMap<String, Object>(5);
-
- SimpleNode parsedTemplate = parse(template);
- return processTemplate(template, parsedTemplate, internalParameters);
- }
-
- @Override
- public SQLStatement processTemplate(String template, List<Object> positionalParameters) {
-
- SimpleNode parsedTemplate = parse(template);
-
- Map<String, Object> internalParameters = new HashMap<>();
-
- PositionalParamMapper visitor = new PositionalParamMapper(positionalParameters, internalParameters);
- parsedTemplate.jjtAccept(visitor, null);
- visitor.onFinish();
-
- return processTemplate(template, parsedTemplate, internalParameters);
- }
-
- SQLStatement processTemplate(String template, SimpleNode parsedTemplate, Map<String, Object> parameters) {
- List<ParameterBinding> bindings = new ArrayList<>();
- List<ColumnDescriptor> results = new ArrayList<>();
- parameters.put(BINDINGS_LIST_KEY, bindings);
- parameters.put(RESULT_COLUMNS_LIST_KEY, results);
- parameters.put(HELPER_KEY, renderingUtils);
-
- String sql;
- try {
- sql = buildStatement(new VelocityContext(parameters), template, parsedTemplate);
- } catch (Exception e) {
- throw new CayenneRuntimeException("Error processing Velocity template", e);
- }
-
- ParameterBinding[] bindingsArray = new ParameterBinding[bindings.size()];
- bindings.toArray(bindingsArray);
-
- ColumnDescriptor[] resultsArray = new ColumnDescriptor[results.size()];
- results.toArray(resultsArray);
-
- return new SQLStatement(sql, resultsArray, bindingsArray);
- }
-
- String buildStatement(VelocityContext context, String template, SimpleNode parsedTemplate) throws Exception {
-
- // ... not sure what InternalContextAdapter is for...
- InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context);
- ica.pushCurrentTemplateName(template);
-
- StringWriter out = new StringWriter(template.length());
- try {
- parsedTemplate.init(ica, velocityRuntime);
- parsedTemplate.render(ica, out);
- return out.toString();
- } finally {
- ica.popCurrentTemplateName();
- }
- }
-
- private SimpleNode parse(String template) {
-
- SimpleNode nodeTree;
- try {
- nodeTree = velocityRuntime.parse(new StringReader(template), template);
- } catch (ParseException pex) {
- throw new CayenneRuntimeException("Error parsing template '%s' : %s", template, pex.getMessage());
- }
-
- if (nodeTree == null) {
- throw new CayenneRuntimeException("Error parsing template %s", template);
- }
-
- return nodeTree;
- }
-}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/test/java/org/apache/cayenne/template/directive/BindDirectiveIT.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/test/java/org/apache/cayenne/template/directive/BindDirectiveIT.java b/cayenne-server/src/test/java/org/apache/cayenne/template/directive/BindDirectiveIT.java
new file mode 100644
index 0000000..17406f2
--- /dev/null
+++ b/cayenne-server/src/test/java/org/apache/cayenne/template/directive/BindDirectiveIT.java
@@ -0,0 +1,239 @@
+/*****************************************************************
+ * 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 static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import java.sql.Timestamp;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.cayenne.ObjectContext;
+import org.apache.cayenne.access.DataNode;
+import org.apache.cayenne.access.MockOperationObserver;
+import org.apache.cayenne.dba.JdbcAdapter;
+import org.apache.cayenne.dba.oracle.OracleAdapter;
+import org.apache.cayenne.di.Inject;
+import org.apache.cayenne.log.JdbcEventLogger;
+import org.apache.cayenne.query.CapsStrategy;
+import org.apache.cayenne.query.ObjectSelect;
+import org.apache.cayenne.query.SQLTemplate;
+import org.apache.cayenne.test.jdbc.DBHelper;
+import org.apache.cayenne.test.jdbc.TableHelper;
+import org.apache.cayenne.testdo.testmap.Artist;
+import org.apache.cayenne.unit.di.server.CayenneProjects;
+import org.apache.cayenne.unit.di.server.ServerCase;
+import org.apache.cayenne.unit.di.server.UseServerRuntime;
+import org.junit.Test;
+
+/**
+ * Tests BindDirective for passed null parameters and for not passed parameters
+ */
+@UseServerRuntime(CayenneProjects.TESTMAP_PROJECT)
+public class BindDirectiveIT extends ServerCase {
+
+ private static String INSERT_TEMPLATE = "INSERT INTO ARTIST (ARTIST_ID, ARTIST_NAME, DATE_OF_BIRTH) "
+ + "VALUES (#bind($id), #bind($name), #bind($dob))";
+ private static String INSERT_TEMPLATE_WITH_TYPES = "INSERT INTO ARTIST (ARTIST_ID, ARTIST_NAME, DATE_OF_BIRTH) "
+ + "VALUES (#bind($id), #bind($name), #bind($dob 'DATE'))";
+
+ @Inject
+ private JdbcAdapter adapter;
+
+ @Inject
+ private ObjectContext context;
+
+ @Inject
+ private JdbcEventLogger logger;
+
+ @Inject
+ private DataNode node;
+
+ @Inject
+ private DBHelper dbHelper;
+
+ @Test
+ public void testBind_Timestamp() throws Exception {
+ Map<String, Object> parameters = new HashMap<>();
+ parameters.put("id", new Integer(1));
+ parameters.put("name", "ArtistWithDOB");
+ Calendar cal = Calendar.getInstance();
+ cal.clear();
+ cal.set(2010, 2, 8);
+ parameters.put("dob", new Timestamp(cal.getTime().getTime()));
+
+ // without JDBC usage
+ Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE);
+ assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
+ assertEquals(cal.getTime(), row.get("DATE_OF_BIRTH"));
+ assertNotNull(row.get("DATE_OF_BIRTH"));
+ assertEquals(Date.class, row.get("DATE_OF_BIRTH").getClass());
+ }
+
+ @Test
+ public void testBind_SQLDate() throws Exception {
+ Map<String, Object> parameters = new HashMap<>();
+ parameters.put("id", new Integer(1));
+ parameters.put("name", "ArtistWithDOB");
+ Calendar cal = Calendar.getInstance();
+ cal.clear();
+ cal.set(2010, 2, 8);
+ parameters.put("dob", new java.sql.Date(cal.getTime().getTime()));
+
+ // without JDBC usage
+ Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE);
+ assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
+ assertEquals(parameters.get("dob"), row.get("DATE_OF_BIRTH"));
+ assertNotNull(row.get("DATE_OF_BIRTH"));
+ assertEquals(Date.class, row.get("DATE_OF_BIRTH").getClass());
+ }
+
+ @Test
+ public void testBind_UtilDate() throws Exception {
+ Map<String, Object> parameters = new HashMap<>();
+ parameters.put("id", new Integer(1));
+ parameters.put("name", "ArtistWithDOB");
+ Calendar cal = Calendar.getInstance();
+ cal.clear();
+ cal.set(2010, 2, 8);
+ parameters.put("dob", cal.getTime());
+
+ // without JDBC usage
+ Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE);
+ assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
+ assertEquals(parameters.get("dob"), row.get("DATE_OF_BIRTH"));
+ assertNotNull(row.get("DATE_OF_BIRTH"));
+ assertEquals(Date.class, row.get("DATE_OF_BIRTH").getClass());
+ }
+
+ @Test
+ public void testBind_Collection() throws Exception {
+
+ TableHelper tArtist = new TableHelper(dbHelper, "ARTIST").setColumns("ARTIST_ID", "ARTIST_NAME");
+
+ // insert 3 artists
+ for (int i = 1; i < 4; i++) {
+ tArtist.insert(new Long(i), "Artist" + i);
+ }
+
+ // now select only with names: Artist1 and Artist3
+ Set<String> artistNames = new HashSet<String>();
+ artistNames.add("Artist1");
+ artistNames.add("Artist3");
+ String sql = "SELECT * FROM ARTIST WHERE ARTIST_NAME in (#bind($ARTISTNAMES))";
+ SQLTemplate query = new SQLTemplate(Artist.class, sql);
+
+ // customize for DB's that require trimming CHAR spaces
+ query.setTemplate(OracleAdapter.class.getName(),
+ "SELECT * FROM ARTIST WHERE RTRIM(ARTIST_NAME) in (#bind($ARTISTNAMES))");
+
+ query.setColumnNamesCapitalization(CapsStrategy.UPPER);
+ query.setParams(Collections.singletonMap("ARTISTNAMES", artistNames));
+ List<?> result = context.performQuery(query);
+ assertEquals(2, result.size());
+ }
+
+ @Test
+ public void testBind_NullParam() throws Exception {
+ Map<String, Object> parameters = new HashMap<>();
+ parameters.put("id", new Long(1));
+ parameters.put("name", "ArtistWithoutDOB");
+ // passing null in parameter
+ parameters.put("dob", null);
+
+ // without JDBC usage
+ Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE);
+ assertEquals(parameters.get("id"), row.get("ARTIST_ID"));
+ assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
+ assertEquals(parameters.get("dob"), row.get("DATE_OF_BIRTH"));
+ assertNull(row.get("DATE_OF_BIRTH"));
+ }
+
+ @Test
+ public void testBind_NullParam_JDBCTypes() throws Exception {
+ Map<String, Object> parameters = new HashMap<>();
+ parameters.put("id", new Long(1));
+ parameters.put("name", "ArtistWithoutDOB");
+ // passing null in parameter
+ parameters.put("dob", null);
+
+ // use JDBC
+ Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE_WITH_TYPES);
+ assertEquals(parameters.get("id"), row.get("ARTIST_ID"));
+ assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
+ assertEquals(parameters.get("dob"), row.get("DATE_OF_BIRTH"));
+ assertNull(row.get("DATE_OF_BIRTH"));
+ }
+
+ @Test
+ public void testBind_SkippedParam() throws Exception {
+ Map<String, Object> parameters = new HashMap<>();
+ parameters.put("id", new Long(1));
+ parameters.put("name", "ArtistWithoutDOB");
+ // skipping "dob"
+
+ // without JDBC usage
+ Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE);
+ assertEquals(parameters.get("id"), row.get("ARTIST_ID"));
+ assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
+ // parameter should be passed as null
+ assertNull(row.get("DATE_OF_BIRTH"));
+ }
+
+ @Test
+ public void testBind_SkippedParam_JDBCTypes() throws Exception {
+ Map<String, Object> parameters = new HashMap<>();
+ parameters.put("id", new Long(1));
+ parameters.put("name", "ArtistWithoutDOB");
+ // skipping "dob"
+
+ // use JDBC
+ Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE_WITH_TYPES);
+ assertEquals(parameters.get("id"), row.get("ARTIST_ID"));
+ assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
+ // parameter should be passed as null
+ assertNull(row.get("DATE_OF_BIRTH"));
+ }
+
+ /**
+ * Inserts row for given parameters
+ *
+ * @return inserted row
+ */
+ private Map<String, ?> performInsertForParameters(Map<String, Object> parameters, String templateString)
+ throws Exception {
+
+ // TODO: do we really care if an inserting SQLTemplate is executed via
+ // ObjectContext?
+ SQLTemplate template = new SQLTemplate(Object.class, templateString);
+ template.setParams(parameters);
+ MockOperationObserver observer = new MockOperationObserver();
+ node.performQueries(Collections.singletonList(template), observer);
+
+ return ObjectSelect.dataRowQuery(Artist.class).selectOne(context);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/test/java/org/apache/cayenne/template/directive/ResultDirectiveIT.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/test/java/org/apache/cayenne/template/directive/ResultDirectiveIT.java b/cayenne-server/src/test/java/org/apache/cayenne/template/directive/ResultDirectiveIT.java
new file mode 100644
index 0000000..107f0ff
--- /dev/null
+++ b/cayenne-server/src/test/java/org/apache/cayenne/template/directive/ResultDirectiveIT.java
@@ -0,0 +1,112 @@
+/*****************************************************************
+ * 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 java.sql.SQLException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.cayenne.access.MockOperationObserver;
+import org.apache.cayenne.configuration.server.ServerRuntime;
+import org.apache.cayenne.di.Inject;
+import org.apache.cayenne.query.CapsStrategy;
+import org.apache.cayenne.query.SQLTemplate;
+import org.apache.cayenne.test.jdbc.DBHelper;
+import org.apache.cayenne.test.jdbc.TableHelper;
+import org.apache.cayenne.testdo.testmap.Artist;
+import org.apache.cayenne.unit.di.server.CayenneProjects;
+import org.apache.cayenne.unit.di.server.ServerCase;
+import org.apache.cayenne.unit.di.server.UseServerRuntime;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Test for Result directive to check if we could use ResultDirective
+ * optionally.
+ */
+@UseServerRuntime(CayenneProjects.TESTMAP_PROJECT)
+public class ResultDirectiveIT extends ServerCase {
+
+ @Inject
+ private ServerRuntime runtime;
+
+ @Inject
+ protected DBHelper dbHelper;
+
+ @Before
+ public void before() throws SQLException {
+ new TableHelper(dbHelper, "ARTIST").setColumns("ARTIST_ID", "ARTIST_NAME").insert(1l, "ArtistToTestResult");
+ }
+
+ @Test
+ public void testWithoutResultDirective() throws Exception {
+ String sql = "SELECT ARTIST_ID, ARTIST_NAME FROM ARTIST";
+ Map<String, Object> selectResult = selectForQuery(sql);
+
+ assertEquals(1l, selectResult.get("ARTIST_ID"));
+ assertEquals("ArtistToTestResult", selectResult.get("ARTIST_NAME"));
+ }
+
+ @Test
+ public void testWithOnlyResultDirective() throws Exception {
+ String sql = "SELECT #result('ARTIST_ID' 'java.lang.Integer'), #result('ARTIST_NAME' 'java.lang.String')"
+ + " FROM ARTIST";
+ Map<String, Object> selectResult = selectForQuery(sql);
+
+ // TODO: is that correct to use Long (coming from DbAttribute) type for
+ // ARTIST_ID instead of Integer (coming from #result(..))?
+ assertEquals(1l, selectResult.get("ARTIST_ID"));
+ assertEquals("ArtistToTestResult", selectResult.get("ARTIST_NAME").toString().trim());
+ }
+
+ @Test
+ public void testWithMixedDirectiveUse1() throws Exception {
+ String sql = "SELECT ARTIST_ID, #result('ARTIST_NAME' 'java.lang.String') FROM ARTIST";
+ Map<String, Object> selectResult = selectForQuery(sql);
+
+ assertEquals(1l, selectResult.get("ARTIST_ID"));
+ assertEquals("ArtistToTestResult", selectResult.get("ARTIST_NAME").toString().trim());
+ }
+
+ @Test
+ public void testWithMixedDirectiveUse2() throws Exception {
+ String sql = "SELECT #result('ARTIST_ID' 'java.lang.Integer'), ARTIST_NAME FROM ARTIST";
+ Map<String, Object> selectResult = selectForQuery(sql);
+
+ assertEquals(1l, selectResult.get("ARTIST_ID"));
+ assertEquals("ArtistToTestResult", selectResult.get("ARTIST_NAME"));
+ }
+
+ private Map<String, Object> selectForQuery(String sql) {
+ SQLTemplate template = new SQLTemplate(Artist.class, sql);
+ template.setColumnNamesCapitalization(CapsStrategy.UPPER);
+ MockOperationObserver observer = new MockOperationObserver();
+ runtime.getDataDomain().performQueries(Collections.singletonList(template), observer);
+
+ @SuppressWarnings("unchecked")
+ List<Map<String, Object>> data = observer.rowsForQuery(template);
+ assertEquals(1, data.size());
+ Map<String, Object> row = data.get(0);
+ return row;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/test/java/org/apache/cayenne/velocity/BindDirectiveIT.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/test/java/org/apache/cayenne/velocity/BindDirectiveIT.java b/cayenne-server/src/test/java/org/apache/cayenne/velocity/BindDirectiveIT.java
deleted file mode 100644
index 69c8fc4..0000000
--- a/cayenne-server/src/test/java/org/apache/cayenne/velocity/BindDirectiveIT.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*****************************************************************
- * 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.velocity;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import java.sql.Timestamp;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.cayenne.ObjectContext;
-import org.apache.cayenne.access.DataNode;
-import org.apache.cayenne.access.MockOperationObserver;
-import org.apache.cayenne.dba.JdbcAdapter;
-import org.apache.cayenne.dba.oracle.OracleAdapter;
-import org.apache.cayenne.di.Inject;
-import org.apache.cayenne.log.JdbcEventLogger;
-import org.apache.cayenne.query.CapsStrategy;
-import org.apache.cayenne.query.ObjectSelect;
-import org.apache.cayenne.query.SQLTemplate;
-import org.apache.cayenne.test.jdbc.DBHelper;
-import org.apache.cayenne.test.jdbc.TableHelper;
-import org.apache.cayenne.testdo.testmap.Artist;
-import org.apache.cayenne.unit.di.server.CayenneProjects;
-import org.apache.cayenne.unit.di.server.ServerCase;
-import org.apache.cayenne.unit.di.server.UseServerRuntime;
-import org.junit.Test;
-
-/**
- * Tests BindDirective for passed null parameters and for not passed parameters
- */
-@UseServerRuntime(CayenneProjects.TESTMAP_PROJECT)
-public class BindDirectiveIT extends ServerCase {
-
- private static String INSERT_TEMPLATE = "INSERT INTO ARTIST (ARTIST_ID, ARTIST_NAME, DATE_OF_BIRTH) "
- + "VALUES (#bind($id), #bind($name), #bind($dob))";
- private static String INSERT_TEMPLATE_WITH_TYPES = "INSERT INTO ARTIST (ARTIST_ID, ARTIST_NAME, DATE_OF_BIRTH) "
- + "VALUES (#bind($id), #bind($name), #bind($dob 'DATE'))";
-
- @Inject
- private JdbcAdapter adapter;
-
- @Inject
- private ObjectContext context;
-
- @Inject
- private JdbcEventLogger logger;
-
- @Inject
- private DataNode node;
-
- @Inject
- private DBHelper dbHelper;
-
- @Test
- public void testBind_Timestamp() throws Exception {
- Map<String, Object> parameters = new HashMap<>();
- parameters.put("id", new Integer(1));
- parameters.put("name", "ArtistWithDOB");
- Calendar cal = Calendar.getInstance();
- cal.clear();
- cal.set(2010, 2, 8);
- parameters.put("dob", new Timestamp(cal.getTime().getTime()));
-
- // without JDBC usage
- Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE);
- assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
- assertEquals(cal.getTime(), row.get("DATE_OF_BIRTH"));
- assertNotNull(row.get("DATE_OF_BIRTH"));
- assertEquals(Date.class, row.get("DATE_OF_BIRTH").getClass());
- }
-
- @Test
- public void testBind_SQLDate() throws Exception {
- Map<String, Object> parameters = new HashMap<>();
- parameters.put("id", new Integer(1));
- parameters.put("name", "ArtistWithDOB");
- Calendar cal = Calendar.getInstance();
- cal.clear();
- cal.set(2010, 2, 8);
- parameters.put("dob", new java.sql.Date(cal.getTime().getTime()));
-
- // without JDBC usage
- Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE);
- assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
- assertEquals(parameters.get("dob"), row.get("DATE_OF_BIRTH"));
- assertNotNull(row.get("DATE_OF_BIRTH"));
- assertEquals(Date.class, row.get("DATE_OF_BIRTH").getClass());
- }
-
- @Test
- public void testBind_UtilDate() throws Exception {
- Map<String, Object> parameters = new HashMap<>();
- parameters.put("id", new Integer(1));
- parameters.put("name", "ArtistWithDOB");
- Calendar cal = Calendar.getInstance();
- cal.clear();
- cal.set(2010, 2, 8);
- parameters.put("dob", cal.getTime());
-
- // without JDBC usage
- Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE);
- assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
- assertEquals(parameters.get("dob"), row.get("DATE_OF_BIRTH"));
- assertNotNull(row.get("DATE_OF_BIRTH"));
- assertEquals(Date.class, row.get("DATE_OF_BIRTH").getClass());
- }
-
- @Test
- public void testBind_Collection() throws Exception {
-
- TableHelper tArtist = new TableHelper(dbHelper, "ARTIST").setColumns("ARTIST_ID", "ARTIST_NAME");
-
- // insert 3 artists
- for (int i = 1; i < 4; i++) {
- tArtist.insert(new Long(i), "Artist" + i);
- }
-
- // now select only with names: Artist1 and Artist3
- Set<String> artistNames = new HashSet<String>();
- artistNames.add("Artist1");
- artistNames.add("Artist3");
- String sql = "SELECT * FROM ARTIST WHERE ARTIST_NAME in (#bind($ARTISTNAMES))";
- SQLTemplate query = new SQLTemplate(Artist.class, sql);
-
- // customize for DB's that require trimming CHAR spaces
- query.setTemplate(OracleAdapter.class.getName(),
- "SELECT * FROM ARTIST WHERE RTRIM(ARTIST_NAME) in (#bind($ARTISTNAMES))");
-
- query.setColumnNamesCapitalization(CapsStrategy.UPPER);
- query.setParams(Collections.singletonMap("ARTISTNAMES", artistNames));
- List<?> result = context.performQuery(query);
- assertEquals(2, result.size());
- }
-
- @Test
- public void testBind_NullParam() throws Exception {
- Map<String, Object> parameters = new HashMap<>();
- parameters.put("id", new Long(1));
- parameters.put("name", "ArtistWithoutDOB");
- // passing null in parameter
- parameters.put("dob", null);
-
- // without JDBC usage
- Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE);
- assertEquals(parameters.get("id"), row.get("ARTIST_ID"));
- assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
- assertEquals(parameters.get("dob"), row.get("DATE_OF_BIRTH"));
- assertNull(row.get("DATE_OF_BIRTH"));
- }
-
- @Test
- public void testBind_NullParam_JDBCTypes() throws Exception {
- Map<String, Object> parameters = new HashMap<>();
- parameters.put("id", new Long(1));
- parameters.put("name", "ArtistWithoutDOB");
- // passing null in parameter
- parameters.put("dob", null);
-
- // use JDBC
- Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE_WITH_TYPES);
- assertEquals(parameters.get("id"), row.get("ARTIST_ID"));
- assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
- assertEquals(parameters.get("dob"), row.get("DATE_OF_BIRTH"));
- assertNull(row.get("DATE_OF_BIRTH"));
- }
-
- @Test
- public void testBind_SkippedParam() throws Exception {
- Map<String, Object> parameters = new HashMap<>();
- parameters.put("id", new Long(1));
- parameters.put("name", "ArtistWithoutDOB");
- // skipping "dob"
-
- // without JDBC usage
- Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE);
- assertEquals(parameters.get("id"), row.get("ARTIST_ID"));
- assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
- // parameter should be passed as null
- assertNull(row.get("DATE_OF_BIRTH"));
- }
-
- @Test
- public void testBind_SkippedParam_JDBCTypes() throws Exception {
- Map<String, Object> parameters = new HashMap<>();
- parameters.put("id", new Long(1));
- parameters.put("name", "ArtistWithoutDOB");
- // skipping "dob"
-
- // use JDBC
- Map<String, ?> row = performInsertForParameters(parameters, INSERT_TEMPLATE_WITH_TYPES);
- assertEquals(parameters.get("id"), row.get("ARTIST_ID"));
- assertEquals(parameters.get("name"), row.get("ARTIST_NAME"));
- // parameter should be passed as null
- assertNull(row.get("DATE_OF_BIRTH"));
- }
-
- /**
- * Inserts row for given parameters
- *
- * @return inserted row
- */
- private Map<String, ?> performInsertForParameters(Map<String, Object> parameters, String templateString)
- throws Exception {
-
- // TODO: do we really care if an inserting SQLTemplate is executed via
- // ObjectContext?
- SQLTemplate template = new SQLTemplate(Object.class, templateString);
- template.setParams(parameters);
- MockOperationObserver observer = new MockOperationObserver();
- node.performQueries(Collections.singletonList(template), observer);
-
- return ObjectSelect.dataRowQuery(Artist.class).selectOne(context);
- }
-}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/test/java/org/apache/cayenne/velocity/ResultDirectiveIT.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/test/java/org/apache/cayenne/velocity/ResultDirectiveIT.java b/cayenne-server/src/test/java/org/apache/cayenne/velocity/ResultDirectiveIT.java
deleted file mode 100644
index 38ac675..0000000
--- a/cayenne-server/src/test/java/org/apache/cayenne/velocity/ResultDirectiveIT.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*****************************************************************
- * 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.velocity;
-
-import static org.junit.Assert.assertEquals;
-
-import java.sql.SQLException;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.cayenne.access.MockOperationObserver;
-import org.apache.cayenne.configuration.server.ServerRuntime;
-import org.apache.cayenne.di.Inject;
-import org.apache.cayenne.query.CapsStrategy;
-import org.apache.cayenne.query.SQLTemplate;
-import org.apache.cayenne.test.jdbc.DBHelper;
-import org.apache.cayenne.test.jdbc.TableHelper;
-import org.apache.cayenne.testdo.testmap.Artist;
-import org.apache.cayenne.unit.di.server.CayenneProjects;
-import org.apache.cayenne.unit.di.server.ServerCase;
-import org.apache.cayenne.unit.di.server.UseServerRuntime;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Test for Result directive to check if we could use ResultDirective
- * optionally.
- */
-@UseServerRuntime(CayenneProjects.TESTMAP_PROJECT)
-public class ResultDirectiveIT extends ServerCase {
-
- @Inject
- private ServerRuntime runtime;
-
- @Inject
- protected DBHelper dbHelper;
-
- @Before
- public void before() throws SQLException {
- new TableHelper(dbHelper, "ARTIST").setColumns("ARTIST_ID", "ARTIST_NAME").insert(1l, "ArtistToTestResult");
- }
-
- @Test
- public void testWithoutResultDirective() throws Exception {
- String sql = "SELECT ARTIST_ID, ARTIST_NAME FROM ARTIST";
- Map<String, Object> selectResult = selectForQuery(sql);
-
- assertEquals(1l, selectResult.get("ARTIST_ID"));
- assertEquals("ArtistToTestResult", selectResult.get("ARTIST_NAME"));
- }
-
- @Test
- public void testWithOnlyResultDirective() throws Exception {
- String sql = "SELECT #result('ARTIST_ID' 'java.lang.Integer'), #result('ARTIST_NAME' 'java.lang.String')"
- + " FROM ARTIST";
- Map<String, Object> selectResult = selectForQuery(sql);
-
- // TODO: is that correct to use Long (coming from DbAttribute) type for
- // ARTIST_ID instead of Integer (coming from #result(..))?
- assertEquals(1l, selectResult.get("ARTIST_ID"));
- assertEquals("ArtistToTestResult", selectResult.get("ARTIST_NAME").toString().trim());
- }
-
- @Test
- public void testWithMixedDirectiveUse1() throws Exception {
- String sql = "SELECT ARTIST_ID, #result('ARTIST_NAME' 'java.lang.String') FROM ARTIST";
- Map<String, Object> selectResult = selectForQuery(sql);
-
- assertEquals(1l, selectResult.get("ARTIST_ID"));
- assertEquals("ArtistToTestResult", selectResult.get("ARTIST_NAME").toString().trim());
- }
-
- @Test
- public void testWithMixedDirectiveUse2() throws Exception {
- String sql = "SELECT #result('ARTIST_ID' 'java.lang.Integer'), ARTIST_NAME FROM ARTIST";
- Map<String, Object> selectResult = selectForQuery(sql);
-
- assertEquals(1l, selectResult.get("ARTIST_ID"));
- assertEquals("ArtistToTestResult", selectResult.get("ARTIST_NAME"));
- }
-
- private Map<String, Object> selectForQuery(String sql) {
- SQLTemplate template = new SQLTemplate(Artist.class, sql);
- template.setColumnNamesCapitalization(CapsStrategy.UPPER);
- MockOperationObserver observer = new MockOperationObserver();
- runtime.getDataDomain().performQueries(Collections.singletonList(template), observer);
-
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> data = observer.rowsForQuery(template);
- assertEquals(1, data.size());
- Map<String, Object> row = data.get(0);
- return row;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/test/java/org/apache/cayenne/velocity/SQLTemplateResourceManagerTest.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/test/java/org/apache/cayenne/velocity/SQLTemplateResourceManagerTest.java b/cayenne-server/src/test/java/org/apache/cayenne/velocity/SQLTemplateResourceManagerTest.java
deleted file mode 100644
index 9ef2229..0000000
--- a/cayenne-server/src/test/java/org/apache/cayenne/velocity/SQLTemplateResourceManagerTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*****************************************************************
- * 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.velocity;
-
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyBoolean;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.io.Reader;
-
-import org.apache.velocity.Template;
-import org.apache.velocity.runtime.RuntimeConstants;
-import org.apache.velocity.runtime.RuntimeServices;
-import org.apache.velocity.runtime.parser.node.SimpleNode;
-import org.apache.velocity.runtime.resource.Resource;
-import org.apache.velocity.runtime.resource.ResourceManager;
-import org.junit.Before;
-import org.junit.Test;
-
-public class SQLTemplateResourceManagerTest {
-
- private SQLTemplateResourceManager rm;
-
- @Before
- public void before() throws Exception {
-
- RuntimeServices rs = mock(RuntimeServices.class);
- when(rs.parse(any(Reader.class), anyString(), anyBoolean())).thenReturn(new SimpleNode(1));
- when(rs.parse(any(Reader.class), anyString())).thenReturn(new SimpleNode(1));
-
- this.rm = new SQLTemplateResourceManager();
- rm.initialize(rs);
- }
-
- @Test
- public void testFetResource() throws Exception {
-
- Resource resource = rm.getResource("abc", ResourceManager.RESOURCE_TEMPLATE, RuntimeConstants.ENCODING_DEFAULT);
-
- assertTrue(resource instanceof Template);
-
- // must be cached...
- assertSame(resource,
- rm.getResource("abc", ResourceManager.RESOURCE_TEMPLATE, RuntimeConstants.ENCODING_DEFAULT));
-
- // new resource must be different
- assertNotSame(resource,
- rm.getResource("xyz", ResourceManager.RESOURCE_TEMPLATE, RuntimeConstants.ENCODING_DEFAULT));
-
- // after clearing cache, resource must be refreshed
- rm.clearCache();
- assertNotSame(resource,
- rm.getResource("abc", ResourceManager.RESOURCE_TEMPLATE, RuntimeConstants.ENCODING_DEFAULT));
- }
-}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessorTest.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessorTest.java b/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessorTest.java
deleted file mode 100644
index 504179b..0000000
--- a/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessorTest.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*****************************************************************
- * 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.velocity;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.sql.Types;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.cayenne.CayenneDataObject;
-import org.apache.cayenne.DataObject;
-import org.apache.cayenne.ObjectId;
-import org.apache.cayenne.access.jdbc.SQLStatement;
-import org.apache.cayenne.access.translator.ParameterBinding;
-import org.junit.Before;
-import org.junit.Test;
-
-public class VelocitySQLTemplateProcessorTest {
-
- private VelocitySQLTemplateProcessor processor;
-
- @Before
- public void before() {
- processor = new VelocitySQLTemplateProcessor();
- }
-
- @Test
- public void testProcessTemplateUnchanged1() throws Exception {
- String sqlTemplate = "SELECT * FROM ME";
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, Collections.<String, Object> emptyMap());
-
- assertEquals(sqlTemplate, compiled.getSql());
- assertEquals(0, compiled.getBindings().length);
- }
-
- @Test
- public void testProcessTemplateUnchanged2() throws Exception {
- String sqlTemplate = "SELECT a.b as XYZ FROM $SYSTEM_TABLE";
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, Collections.<String, Object> emptyMap());
-
- assertEquals(sqlTemplate, compiled.getSql());
- assertEquals(0, compiled.getBindings().length);
- }
-
- @Test
- public void testProcessTemplateSimpleDynamicContent() throws Exception {
- String sqlTemplate = "SELECT * FROM ME WHERE $a";
-
- Map<String, Object> map = Collections.<String, Object> singletonMap("a", "VALUE_OF_A");
- SQLStatement compiled = processor.processTemplate(sqlTemplate, map);
-
- assertEquals("SELECT * FROM ME WHERE VALUE_OF_A", compiled.getSql());
-
- // bindings are not populated, since no "bind" macro is used.
- assertEquals(0, compiled.getBindings().length);
- }
-
- @Test
- public void testProcessTemplateBind() throws Exception {
- String sqlTemplate = "SELECT * FROM ME WHERE "
- + "COLUMN1 = #bind($a 'VARCHAR') AND COLUMN2 = #bind($b 'INTEGER')";
- Map<String, Object> map = Collections.<String, Object> singletonMap("a", "VALUE_OF_A");
- SQLStatement compiled = processor.processTemplate(sqlTemplate, map);
-
- assertEquals("SELECT * FROM ME WHERE COLUMN1 = ? AND COLUMN2 = ?", compiled.getSql());
- assertEquals(2, compiled.getBindings().length);
- assertBindingValue("VALUE_OF_A", compiled.getBindings()[0]);
- assertBindingValue(null, compiled.getBindings()[1]);
- }
-
- @Test
- public void testProcessTemplateBindGuessVarchar() throws Exception {
- String sqlTemplate = "SELECT * FROM ME WHERE COLUMN1 = #bind($a)";
- Map<String, Object> map = Collections.<String, Object> singletonMap("a", "VALUE_OF_A");
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, map);
-
- assertEquals(1, compiled.getBindings().length);
- assertBindingType(Types.VARCHAR, compiled.getBindings()[0]);
- }
-
- @Test
- public void testProcessTemplateBindGuessInteger() throws Exception {
- String sqlTemplate = "SELECT * FROM ME WHERE COLUMN1 = #bind($a)";
- Map<String, Object> map = Collections.<String, Object> singletonMap("a", 4);
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, map);
-
- assertEquals(1, compiled.getBindings().length);
- assertBindingType(Types.INTEGER, compiled.getBindings()[0]);
- }
-
- @Test
- public void testProcessTemplateBindEqual() throws Exception {
- String sqlTemplate = "SELECT * FROM ME WHERE COLUMN #bindEqual($a 'VARCHAR')";
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, Collections.<String, Object> emptyMap());
-
- assertEquals("SELECT * FROM ME WHERE COLUMN IS NULL", compiled.getSql());
- assertEquals(0, compiled.getBindings().length);
-
- Map<String, Object> map = Collections.<String, Object> singletonMap("a", "VALUE_OF_A");
-
- compiled = processor.processTemplate(sqlTemplate, map);
-
- assertEquals("SELECT * FROM ME WHERE COLUMN = ?", compiled.getSql());
- assertEquals(1, compiled.getBindings().length);
- assertBindingValue("VALUE_OF_A", compiled.getBindings()[0]);
- }
-
- @Test
- public void testProcessTemplateBindNotEqual() throws Exception {
- String sqlTemplate = "SELECT * FROM ME WHERE COLUMN #bindNotEqual($a 'VARCHAR')";
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, Collections.<String, Object> emptyMap());
-
- assertEquals("SELECT * FROM ME WHERE COLUMN IS NOT NULL", compiled.getSql());
- assertEquals(0, compiled.getBindings().length);
-
- Map<String, Object> map = Collections.<String, Object> singletonMap("a", "VALUE_OF_A");
-
- compiled = processor.processTemplate(sqlTemplate, map);
-
- assertEquals("SELECT * FROM ME WHERE COLUMN <> ?", compiled.getSql());
- assertEquals(1, compiled.getBindings().length);
- assertBindingValue("VALUE_OF_A", compiled.getBindings()[0]);
- }
-
- @Test
- public void testProcessTemplateID() throws Exception {
- String sqlTemplate = "SELECT * FROM ME WHERE COLUMN1 = #bind($helper.cayenneExp($a, 'db:ID_COLUMN'))";
-
- DataObject dataObject = new CayenneDataObject();
- dataObject.setObjectId(new ObjectId("T", "ID_COLUMN", 5));
-
- Map<String, Object> map = Collections.<String, Object> singletonMap("a", dataObject);
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, map);
-
- assertEquals("SELECT * FROM ME WHERE COLUMN1 = ?", compiled.getSql());
- assertEquals(1, compiled.getBindings().length);
- assertBindingValue(new Integer(5), compiled.getBindings()[0]);
- }
-
- @Test
- public void testProcessTemplateNotEqualID() throws Exception {
- String sqlTemplate = "SELECT * FROM ME WHERE "
- + "COLUMN1 #bindNotEqual($helper.cayenneExp($a, 'db:ID_COLUMN1')) "
- + "AND COLUMN2 #bindNotEqual($helper.cayenneExp($a, 'db:ID_COLUMN2'))";
-
- Map<String, Object> idMap = new HashMap<>();
- idMap.put("ID_COLUMN1", new Integer(3));
- idMap.put("ID_COLUMN2", "aaa");
- ObjectId id = new ObjectId("T", idMap);
- DataObject dataObject = new CayenneDataObject();
- dataObject.setObjectId(id);
-
- Map<String, Object> map = Collections.<String, Object> singletonMap("a", dataObject);
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, map);
-
- assertEquals("SELECT * FROM ME WHERE COLUMN1 <> ? AND COLUMN2 <> ?", compiled.getSql());
- assertEquals(2, compiled.getBindings().length);
- assertBindingValue(new Integer(3), compiled.getBindings()[0]);
- assertBindingValue("aaa", compiled.getBindings()[1]);
- }
-
- @Test
- public void testProcessTemplateConditions() throws Exception {
- String sqlTemplate = "SELECT * FROM ME #if($a) WHERE COLUMN1 > #bind($a)#end";
-
- Map<String, Object> map = Collections.<String, Object> singletonMap("a", "VALUE_OF_A");
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, map);
-
- assertEquals("SELECT * FROM ME WHERE COLUMN1 > ?", compiled.getSql());
- assertEquals(1, compiled.getBindings().length);
- assertBindingValue("VALUE_OF_A", compiled.getBindings()[0]);
-
- compiled = processor.processTemplate(sqlTemplate, Collections.<String, Object> emptyMap());
-
- assertEquals("SELECT * FROM ME ", compiled.getSql());
- assertEquals(0, compiled.getBindings().length);
- }
-
- @Test
- public void testProcessTemplateBindCollection() throws Exception {
- String sqlTemplate = "SELECT * FROM ME WHERE COLUMN IN (#bind($list 'VARCHAR'))";
-
- Map<String, Object> map = Collections.<String, Object> singletonMap("list", Arrays.asList("a", "b", "c"));
- SQLStatement compiled = new VelocitySQLTemplateProcessor().processTemplate(sqlTemplate, map);
-
- assertEquals("SELECT * FROM ME WHERE COLUMN IN (?,?,?)", compiled.getSql());
- assertEquals(3, compiled.getBindings().length);
-
- compiled = processor.processTemplate(sqlTemplate, map);
- assertBindingValue("a", compiled.getBindings()[0]);
- assertBindingValue("b", compiled.getBindings()[1]);
- assertBindingValue("c", compiled.getBindings()[2]);
- }
-
- private void assertBindingValue(Object expectedValue, Object binding) {
- assertTrue("Not a binding!", binding instanceof ParameterBinding);
- assertEquals(expectedValue, ((ParameterBinding) binding).getValue());
- }
-
- private void assertBindingType(Integer expectedType, Object binding) {
- assertTrue("Not a binding!", binding instanceof ParameterBinding);
- assertEquals(expectedType, ((ParameterBinding) binding).getJdbcType());
- }
-}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor_ChainTest.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor_ChainTest.java b/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor_ChainTest.java
deleted file mode 100644
index c864918..0000000
--- a/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor_ChainTest.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*****************************************************************
- * 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.velocity;
-
-import static org.junit.Assert.assertEquals;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.cayenne.access.jdbc.SQLStatement;
-import org.junit.Before;
-import org.junit.Test;
-
-public class VelocitySQLTemplateProcessor_ChainTest {
-
- private VelocitySQLTemplateProcessor processor;
-
- @Before
- public void before() {
- processor = new VelocitySQLTemplateProcessor();
- }
-
- @Test
- public void testProcessTemplateNoChunks() throws Exception {
- // whatever is inside the chain, it should render as empty if there
- // is no chunks...
-
- SQLStatement compiled = processor.processTemplate("#chain(' AND ') #end",
- Collections.<String, Object> emptyMap());
- assertEquals("", compiled.getSql());
-
- compiled = processor.processTemplate("#chain(' AND ') garbage #end", Collections.<String, Object> emptyMap());
- assertEquals("", compiled.getSql());
-
- compiled = processor.processTemplate("#chain(' AND ' 'PREFIX') #end", Collections.<String, Object> emptyMap());
-
- assertEquals("", compiled.getSql());
- compiled = processor.processTemplate("#chain(' AND ' 'PREFIX') garbage #end",
- Collections.<String, Object> emptyMap());
-
- assertEquals("", compiled.getSql());
- }
-
- @Test
- public void testProcessTemplateFullChain() throws Exception {
- String template = "#chain(' OR ')" + "#chunk($a)$a#end" + "#chunk($b)$b#end" + "#chunk($c)$c#end" + "#end";
-
- Map<String, Object> map = new HashMap<>();
- map.put("a", "[A]");
- map.put("b", "[B]");
- map.put("c", "[C]");
-
- SQLStatement compiled = processor.processTemplate(template, map);
- assertEquals("[A] OR [B] OR [C]", compiled.getSql());
- }
-
- @Test
- public void testProcessTemplateFullChainAndPrefix() throws Exception {
- String template = "#chain(' OR ' 'WHERE ')" + "#chunk($a)$a#end" + "#chunk($b)$b#end" + "#chunk($c)$c#end"
- + "#end";
-
- Map<String, Object> map = new HashMap<>();
- map.put("a", "[A]");
- map.put("b", "[B]");
- map.put("c", "[C]");
-
- SQLStatement compiled = processor.processTemplate(template, map);
- assertEquals("WHERE [A] OR [B] OR [C]", compiled.getSql());
- }
-
- @Test
- public void testProcessTemplatePartialChainMiddle() throws Exception {
- String template = "#chain(' OR ' 'WHERE ')" + "#chunk($a)$a#end" + "#chunk($b)$b#end" + "#chunk($c)$c#end"
- + "#end";
-
- Map<String, Object> map = new HashMap<>();
- map.put("a", "[A]");
- map.put("c", "[C]");
-
- SQLStatement compiled = processor.processTemplate(template, map);
- assertEquals("WHERE [A] OR [C]", compiled.getSql());
- }
-
- @Test
- public void testProcessTemplatePartialChainStart() throws Exception {
- String template = "#chain(' OR ' 'WHERE ')" + "#chunk($a)$a#end" + "#chunk($b)$b#end" + "#chunk($c)$c#end"
- + "#end";
-
- Map<String, Object> map = new HashMap<>();
- map.put("b", "[B]");
- map.put("c", "[C]");
-
- SQLStatement compiled = processor.processTemplate(template, map);
- assertEquals("WHERE [B] OR [C]", compiled.getSql());
- }
-
- @Test
- public void testProcessTemplatePartialChainEnd() throws Exception {
- String template = "#chain(' OR ' 'WHERE ')" + "#chunk($a)$a#end" + "#chunk($b)$b#end" + "#chunk($c)$c#end"
- + "#end";
-
- Map<String, Object> map = new HashMap<>();
- map.put("a", "[A]");
- map.put("b", "[B]");
-
- SQLStatement compiled = processor.processTemplate(template, map);
- assertEquals("WHERE [A] OR [B]", compiled.getSql());
- }
-
- @Test
- public void testProcessTemplateChainWithGarbage() throws Exception {
- String template = "#chain(' OR ' 'WHERE ')" + "#chunk($a)$a#end" + " some other stuff" + "#chunk($c)$c#end"
- + "#end";
-
- Map<String, Object> map = new HashMap<>();
- map.put("a", "[A]");
- map.put("c", "[C]");
-
- SQLStatement compiled = processor.processTemplate(template, map);
- assertEquals("WHERE [A] some other stuff OR [C]", compiled.getSql());
- }
-
- @Test
- public void testProcessTemplateChainUnconditionalChunks() throws Exception {
- String template = "#chain(' OR ' 'WHERE ')" + "#chunk()C1#end" + "#chunk()C2#end" + "#chunk()C3#end" + "#end";
-
- SQLStatement compiled = processor.processTemplate(template, Collections.<String, Object> emptyMap());
- assertEquals("WHERE C1 OR C2 OR C3", compiled.getSql());
- }
-
- @Test
- public void testProcessTemplateEmptyChain() throws Exception {
- String template = "#chain(' OR ' 'WHERE ')" + "#chunk($a)$a#end" + "#chunk($b)$b#end" + "#chunk($c)$c#end"
- + "#end";
-
- SQLStatement compiled = processor.processTemplate(template, Collections.<String, Object> emptyMap());
- assertEquals("", compiled.getSql());
- }
-
- @Test
- public void testProcessTemplateWithFalseOrZero1() throws Exception {
- String template = "#chain(' OR ' 'WHERE ')" + "#chunk($a)[A]#end" + "#chunk($b)[B]#end" + "#chunk($c)$c#end"
- + "#end";
-
- Map<String, Object> map = new HashMap<>();
- map.put("a", false);
- map.put("b", 0);
-
- SQLStatement compiled = processor.processTemplate(template, map);
- assertEquals("WHERE [A] OR [B]", compiled.getSql());
- }
-
- @Test
- public void testProcessTemplateWithFalseOrZero2() throws Exception {
- String template = "#chain(' OR ' 'WHERE ')" + "#chunk($a)$a#end" + "#chunk($b)$b#end" + "#chunk($c)$c#end"
- + "#end";
-
- Map<String, Object> map = new HashMap<>();
- map.put("a", false);
- map.put("b", 0);
-
- SQLStatement compiled = processor.processTemplate(template, map);
- assertEquals("WHERE false OR 0", compiled.getSql());
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor_SelectTest.java
----------------------------------------------------------------------
diff --git a/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor_SelectTest.java b/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor_SelectTest.java
deleted file mode 100644
index 74a4d22..0000000
--- a/cayenne-server/src/test/java/org/apache/cayenne/velocity/VelocitySQLTemplateProcessor_SelectTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*****************************************************************
- * 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.velocity;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-import java.util.Collections;
-
-import org.apache.cayenne.access.jdbc.ColumnDescriptor;
-import org.apache.cayenne.access.jdbc.SQLStatement;
-import org.junit.Before;
-import org.junit.Test;
-
-public class VelocitySQLTemplateProcessor_SelectTest {
-
- private VelocitySQLTemplateProcessor processor;
-
- @Before
- public void before() {
- processor = new VelocitySQLTemplateProcessor();
- }
-
- @Test
- public void testProcessTemplateUnchanged() throws Exception {
- String sqlTemplate = "SELECT * FROM ME";
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, Collections.<String, Object> emptyMap());
-
- assertEquals(sqlTemplate, compiled.getSql());
- assertEquals(0, compiled.getBindings().length);
- assertEquals(0, compiled.getResultColumns().length);
- }
-
- @Test
- public void testProcessSelectTemplate1() throws Exception {
- String sqlTemplate = "SELECT #result('A') FROM ME";
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, Collections.<String, Object> emptyMap());
-
- assertEquals("SELECT A FROM ME", compiled.getSql());
- assertEquals(0, compiled.getBindings().length);
- assertEquals(1, compiled.getResultColumns().length);
- assertEquals("A", compiled.getResultColumns()[0].getName());
- assertNull(compiled.getResultColumns()[0].getJavaClass());
- }
-
- @Test
- public void testProcessSelectTemplate2() throws Exception {
- String sqlTemplate = "SELECT #result('A' 'String') FROM ME";
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, Collections.<String, Object> emptyMap());
-
- assertEquals("SELECT A FROM ME", compiled.getSql());
- assertEquals(0, compiled.getBindings().length);
-
- assertEquals(1, compiled.getResultColumns().length);
- assertEquals("A", compiled.getResultColumns()[0].getName());
- assertEquals("java.lang.String", compiled.getResultColumns()[0].getJavaClass());
- }
-
- @Test
- public void testProcessSelectTemplate3() throws Exception {
- String sqlTemplate = "SELECT #result('A' 'String' 'B') FROM ME";
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, Collections.<String, Object> emptyMap());
-
- assertEquals("SELECT A AS B FROM ME", compiled.getSql());
- assertEquals(0, compiled.getBindings().length);
-
- assertEquals(1, compiled.getResultColumns().length);
- ColumnDescriptor column = compiled.getResultColumns()[0];
- assertEquals("A", column.getName());
- assertEquals("B", column.getDataRowKey());
- assertEquals("java.lang.String", column.getJavaClass());
- }
-
- @Test
- public void testProcessSelectTemplate4() throws Exception {
- String sqlTemplate = "SELECT #result('A'), #result('B'), #result('C') FROM ME";
-
- SQLStatement compiled = processor.processTemplate(sqlTemplate, Collections.<String, Object> emptyMap());
-
- assertEquals("SELECT A, B, C FROM ME", compiled.getSql());
- assertEquals(0, compiled.getBindings().length);
-
- assertEquals(3, compiled.getResultColumns().length);
- assertEquals("A", compiled.getResultColumns()[0].getName());
- assertEquals("B", compiled.getResultColumns()[1].getName());
- assertEquals("C", compiled.getResultColumns()[2].getName());
- }
-}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-velocity/pom.xml
----------------------------------------------------------------------
diff --git a/cayenne-velocity/pom.xml b/cayenne-velocity/pom.xml
new file mode 100644
index 0000000..7246cd7
--- /dev/null
+++ b/cayenne-velocity/pom.xml
@@ -0,0 +1,87 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ ~ 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.
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <artifactId>cayenne-parent</artifactId>
+ <groupId>org.apache.cayenne</groupId>
+ <version>4.1.M1-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>cayenne-velocity</artifactId>
+ <name>cayenne-velocity: Cayenne Velocity template processor</name>
+ <description>Integration for Velocity template processor</description>
+ <packaging>jar</packaging>
+
+ <dependencies>
+
+ <!-- Compile dependencies -->
+ <dependency>
+ <groupId>org.apache.cayenne</groupId>
+ <artifactId>cayenne-server</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.velocity</groupId>
+ <artifactId>velocity</artifactId>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- Test dependencies -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.cayenne.build-tools</groupId>
+ <artifactId>cayenne-test-utilities</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
+ <build>
+ <plugins>
+ <!-- This ensures LICENSE and NOTICE inclusion in all jars -->
+ <plugin>
+ <artifactId>maven-remote-resources-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>process</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-velocity/src/main/java/org/apache/cayenne/velocity/BindDirective.java
----------------------------------------------------------------------
diff --git a/cayenne-velocity/src/main/java/org/apache/cayenne/velocity/BindDirective.java b/cayenne-velocity/src/main/java/org/apache/cayenne/velocity/BindDirective.java
new file mode 100644
index 0000000..94080d6
--- /dev/null
+++ b/cayenne-velocity/src/main/java/org/apache/cayenne/velocity/BindDirective.java
@@ -0,0 +1,158 @@
+/*****************************************************************
+ * 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.velocity;
+
+import java.io.IOException;
+import java.io.Writer;
+import java.util.Collection;
+import java.util.Iterator;
+
+import org.apache.cayenne.access.translator.ParameterBinding;
+import org.apache.cayenne.dba.TypesMapping;
+import org.apache.cayenne.util.ConversionUtil;
+import org.apache.velocity.context.InternalContextAdapter;
+import org.apache.velocity.exception.MethodInvocationException;
+import org.apache.velocity.exception.ParseErrorException;
+import org.apache.velocity.exception.ResourceNotFoundException;
+import org.apache.velocity.runtime.directive.Directive;
+import org.apache.velocity.runtime.parser.node.Node;
+
+/**
+ * A custom Velocity directive to create a PreparedStatement parameter text.
+ * There are the following possible invocation formats inside the template:
+ *
+ * <pre>
+ * #bind(value) - e.g. #bind($xyz)
+ * #bind(value jdbc_type_name) - e.g. #bind($xyz 'VARCHAR'). This is the most common and useful form.
+ * #bind(value jdbc_type_name, scale) - e.g. #bind($xyz 'VARCHAR' 2)
+ * </pre>
+ * <p>
+ * Other examples:
+ * </p>
+ * <p>
+ * <strong>Binding literal parameter value:</strong>
+ * </p>
+ * <p>
+ * <code>"WHERE SOME_COLUMN > #bind($xyz)"</code> produces
+ * <code>"WHERE SOME_COLUMN > ?"</code> and also places the value of the
+ * "xyz" parameter in the context "bindings" collection.
+ * </p>
+ * <p>
+ * <strong>Binding ID column of a DataObject value:</strong>
+ * </p>
+ * <p>
+ * <code>"WHERE ID_COL1 = #bind($helper.cayenneExp($xyz, 'db:ID_COL2'))
+ * AND ID_COL2 = #bind($helper.cayenneExp($xyz, 'db:ID_COL2'))"</code> produces
+ * <code>"WHERE ID_COL1 = ? AND ID_COL2 = ?"</code> and also places the values
+ * of id columns of the DataObject parameter "xyz" in the context "bindings"
+ * collection.
+ * </p>
+ *
+ * @since 1.1
+ */
+public class BindDirective extends Directive {
+
+ @Override
+ public String getName() {
+ return "bind";
+ }
+
+ @Override
+ public int getType() {
+ return LINE;
+ }
+
+ /**
+ * Extracts the value of the object property to render and passes control to
+ * {@link #render(InternalContextAdapter, Writer, ParameterBinding)} to do
+ * the actual rendering.
+ */
+ @Override
+ public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException,
+ ResourceNotFoundException, ParseErrorException, MethodInvocationException {
+
+ Object value = getChild(context, node, 0);
+ Object type = getChild(context, node, 1);
+ int scale = ConversionUtil.toInt(getChild(context, node, 2), -1);
+ String typeString = type != null ? type.toString() : null;
+
+ if (value instanceof Collection) {
+ Iterator<?> it = ((Collection) value).iterator();
+ while (it.hasNext()) {
+ render(context, writer, node, it.next(), typeString, scale);
+
+ if (it.hasNext()) {
+ writer.write(',');
+ }
+ }
+ } else {
+ render(context, writer, node, value, typeString, scale);
+ }
+
+ return true;
+ }
+
+ /**
+ * @since 3.0
+ */
+ protected void render(InternalContextAdapter context, Writer writer, Node node, Object value, String typeString,
+ int scale) throws IOException, ParseErrorException {
+
+ int jdbcType = TypesMapping.NOT_DEFINED;
+ if (typeString != null) {
+ jdbcType = TypesMapping.getSqlTypeByName(typeString);
+ } else if (value != null) {
+ jdbcType = TypesMapping.getSqlTypeByJava(value.getClass());
+ } else {
+ // value is null, set JDBC type to NULL
+ jdbcType = TypesMapping.getSqlTypeByName(TypesMapping.SQL_NULL);
+ }
+
+ if (jdbcType == TypesMapping.NOT_DEFINED) {
+ throw new ParseErrorException("Can't determine JDBC type of binding (" + value + ", " + typeString
+ + ") at line " + node.getLine() + ", column " + node.getColumn());
+ }
+
+ render(context, writer, new ParameterBinding(value, jdbcType, scale));
+ }
+
+ protected void render(InternalContextAdapter context, Writer writer, ParameterBinding binding) throws IOException {
+
+ bind(context, binding);
+ writer.write('?');
+ }
+
+ protected Object getChild(InternalContextAdapter context, Node node, int i) throws MethodInvocationException {
+ return (i >= 0 && i < node.jjtGetNumChildren()) ? node.jjtGetChild(i).value(context) : null;
+ }
+
+ /**
+ * Adds value to the list of bindings in the context.
+ */
+ protected void bind(InternalContextAdapter context, ParameterBinding binding) {
+
+ Collection bindings = (Collection) context.getInternalUserContext().get(
+ VelocitySQLTemplateProcessor.BINDINGS_LIST_KEY);
+
+ if (bindings != null) {
+ bindings.add(binding);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cayenne/blob/f734851f/cayenne-velocity/src/main/java/org/apache/cayenne/velocity/BindEqualDirective.java
----------------------------------------------------------------------
diff --git a/cayenne-velocity/src/main/java/org/apache/cayenne/velocity/BindEqualDirective.java b/cayenne-velocity/src/main/java/org/apache/cayenne/velocity/BindEqualDirective.java
new file mode 100644
index 0000000..bf9c820
--- /dev/null
+++ b/cayenne-velocity/src/main/java/org/apache/cayenne/velocity/BindEqualDirective.java
@@ -0,0 +1,57 @@
+/*****************************************************************
+ * 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.velocity;
+
+import java.io.IOException;
+import java.io.Writer;
+
+import org.apache.cayenne.access.translator.ParameterBinding;
+import org.apache.velocity.context.InternalContextAdapter;
+
+/**
+ * A custom Velocity directive to create a PreparedStatement parameter text
+ * for "= ?". If null value is encountered, generated text will look like "IS NULL".
+ * Usage in Velocity template is "WHERE SOME_COLUMN #bindEqual($xyz)".
+ *
+ * @since 1.1
+ */
+public class BindEqualDirective extends BindDirective {
+
+ @Override
+ public String getName() {
+ return "bindEqual";
+ }
+
+ @Override
+ protected void render(
+ InternalContextAdapter context,
+ Writer writer,
+ ParameterBinding binding)
+ throws IOException {
+
+ if (binding.getValue() != null) {
+ bind(context, binding);
+ writer.write("= ?");
+ }
+ else {
+ writer.write("IS NULL");
+ }
+ }
+}