incubator-bval-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mben...@apache.org
Subject svn commit: r1166451 [4/6] - in /incubator/bval/trunk: ./ bval-core/ bval-core/src/main/java/org/apache/bval/ bval-core/src/main/java/org/apache/bval/model/ bval-core/src/main/java/org/apache/bval/util/ bval-json/src/main/resources/org/apache/bval/json...
Date Wed, 07 Sep 2011 22:32:28 GMT
Modified: incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/PathImpl.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/PathImpl.java?rev=1166451&r1=1166450&r2=1166451&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/PathImpl.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/PathImpl.java Wed Sep  7 22:32:26 2011
@@ -19,52 +19,92 @@
 package org.apache.bval.jsr303.util;
 
 import javax.validation.Path;
+
 import java.io.Serializable;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
 
 /**
  * Description: object holding the property path as a list of nodes.
- * (Implementation based on reference implementation)
+ * (Implementation partially based on reference implementation)
  * <br/>
  * This class is not synchronized.
+ * 
+ * @version $Rev$ $Date$
  */
 public class PathImpl implements Path, Serializable {
 
     private static final long serialVersionUID = 1L;
 
+    static final String PROPERTY_PATH_SEPARATOR = ".";
+
     /**
-     * Regular expression used to split a string path into its elements.
-     *
-     * @see <a href="http://www.regexplanet.com/simple/index.jsp">Regular expression tester</a>
+     * Builds non-root paths from expressions.
      */
-    private static final Pattern pathPattern =
-          Pattern.compile("(\\w+)(\\[(\\w*)\\])?(\\.(.*))*");
+    private static class PathImplBuilder implements PathNavigation.Callback<PathImpl> {
+        PathImpl result = new PathImpl();
+
+        /**
+         * {@inheritDoc}
+         */
+        public void handleProperty(String name) {
+            result.addProperty(name);
+        }
+
+        /**
+         * {@inheritDoc}
+         */
+        public void handleIndexOrKey(String value) {
+            // with no context to guide us, we can only parse ints and fall back to String keys:
+            NodeImpl node;
+            try {
+                node = NodeImpl.atIndex(Integer.parseInt(value));
+            } catch (NumberFormatException e) {
+                node = NodeImpl.atKey(value);
+            }
+            result.addNode(node);
+        }
+
+        /**
+         * {@inheritDoc}
+         */
+        public PathImpl result() {
+            if (result.nodeList.isEmpty()) {
+                throw new IllegalStateException();
+            }
+            return result;
+        }
+
+        /**
+         * {@inheritDoc}
+         */
+        public void handleGenericInIterable() {
+            result.addNode(NodeImpl.atIndex(null));
+        }
 
-    private static final String PROPERTY_PATH_SEPARATOR = ".";
+    }
 
     private final List<Node> nodeList;
 
     /**
-     * Returns a {@code Path} instance representing the path described by the given string. To create a root node the empty string should be passed.
-     * Note:  This signature is to maintain pluggability with the RI impl.
-     *
-     * @param propertyPath the path as string representation.
+     * Returns a {@code Path} instance representing the path described by the given string. To create a root node the
+     * empty string should be passed. Note: This signature is to maintain pluggability with the RI impl.
+     * 
+     * @param propertyPath
+     *            the path as string representation.
      * @return a {@code Path} instance representing the path described by the given string.
      */
     public static PathImpl createPathFromString(String propertyPath) {
         if (propertyPath == null || propertyPath.length() == 0) {
             return create(null);
         }
-
-        return parseProperty(propertyPath);
+        return PathNavigation.navigateAndReturn(propertyPath, new PathImplBuilder());
     }
 
     /**
      * Create a {@link PathImpl} instance representing the specified path.
+     * 
      * @param name
      * @return PathImpl
      */
@@ -77,6 +117,7 @@ public class PathImpl implements Path, S
 
     /**
      * Copy another Path.
+     * 
      * @param path
      * @return new {@link PathImpl}
      */
@@ -104,15 +145,21 @@ public class PathImpl implements Path, S
 
     /**
      * Learn whether this {@link PathImpl} points to the root of its graph.
+     * 
      * @return true if no child nodes
      */
-    //our implementation stores a nameless root node.
+    // our implementation stores a nameless root node.
     public boolean isRootPath() {
-        return nodeList.size() == 1 && nodeList.get(0).getName() == null;
+        if (nodeList.size() != 1) {
+            return false;
+        }
+        Path.Node first = nodeList.get(0);
+        return !first.isInIterable() && first.getName() == null;
     }
 
     /**
-     * Return a new {@link PathImpl} that represents <code>this</code> minus its leaf node (if present). 
+     * Return a new {@link PathImpl} that represents <code>this</code> minus its leaf node (if present).
+     * 
      * @return PathImpl
      */
     public PathImpl getPathWithoutLeafNode() {
@@ -127,21 +174,40 @@ public class PathImpl implements Path, S
 
     /**
      * Add a node to this {@link PathImpl}.
-     * @param node to add
+     * 
+     * @param node
+     *            to add
      */
     public void addNode(Node node) {
-    	if ( isRootPath() && nodeList.get(0).getIndex() == null ) {
-    		nodeList.set(0, node);
-    	}
-    	else {
-    		nodeList.add(node);
-    	}
+        if (isRootPath()) {
+            nodeList.set(0, node);
+        } else {
+            nodeList.add(node);
+        }
+    }
+
+    /**
+     * Encapsulate the node manipulations needed to add a named property to this path.
+     * 
+     * @param name
+     */
+    public void addProperty(String name) {
+        if (!nodeList.isEmpty()) {
+            NodeImpl leaf = getLeafNode();
+            if (leaf != null && leaf.isInIterable() && leaf.getName() == null) {
+                leaf.setName(name);
+                return;
+            }
+        }
+        addNode(new NodeImpl(name));
     }
 
     /**
      * Trim the leaf node from this {@link PathImpl}.
+     * 
      * @return the node removed
-     * @throws IllegalStateException if no nodes are found
+     * @throws IllegalStateException
+     *             if no nodes are found
      */
     public Node removeLeafNode() {
         if (isRootPath() || nodeList.size() == 0) {
@@ -158,6 +224,7 @@ public class PathImpl implements Path, S
 
     /**
      * Get the leaf node (if any) from this {@link PathImpl}
+     * 
      * @return {@link NodeImpl}
      */
     public NodeImpl getLeafNode() {
@@ -176,6 +243,7 @@ public class PathImpl implements Path, S
 
     /**
      * Learn whether <code>path</code> is a parent to <code>this</code>.
+     * 
      * @param path
      * @return <code>true</code> if our nodes begin with nodes equal to those found in <code>path</code>
      */
@@ -191,9 +259,25 @@ public class PathImpl implements Path, S
                 return false;
             }
             Node thisNode = thisIter.next();
-            if (!thisNode.equals(pathNode)) {
+            if (pathNode.isInIterable()) {
+                if (!thisNode.isInIterable()) {
+                    return false;
+                }
+                if (pathNode.getIndex() != null && !pathNode.getIndex().equals(thisNode.getIndex())) {
+                    return false;
+                }
+                if (pathNode.getKey() != null && !pathNode.getKey().equals(thisNode.getKey())) {
+                    return false;
+                }
+            } else if (thisNode.isInIterable()) {
+                // in this case we have shown that the proposed parent is not
+                // indexed, and we are, thus the paths cannot match
                 return false;
             }
+            if (pathNode.getName() == null || pathNode.getName().equals(thisNode.getName())) {
+                continue;
+            }
+            return false;
         }
         return true;
     }
@@ -204,13 +288,8 @@ public class PathImpl implements Path, S
     @Override
     public String toString() {
         StringBuilder builder = new StringBuilder();
-        Iterator<Path.Node> iter = iterator();
-        while (iter.hasNext()) {
-            Node node = iter.next();
-            builder.append(node.toString());
-            if (iter.hasNext() && builder.length() > 0) {
-                builder.append(PROPERTY_PATH_SEPARATOR);
-            }
+        for (Path.Node node : this) {
+            NodeImpl.appendNode(node, builder);
         }
         return builder.toString();
     }
@@ -228,8 +307,7 @@ public class PathImpl implements Path, S
         }
 
         PathImpl path = (PathImpl) o;
-        return !(nodeList != null && !nodeList.equals(path.nodeList)) &&
-              !(nodeList == null && path.nodeList != null);
+        return !(nodeList != null && !nodeList.equals(path.nodeList)) && !(nodeList == null && path.nodeList != null);
 
     }
 
@@ -241,35 +319,4 @@ public class PathImpl implements Path, S
         return nodeList != null ? nodeList.hashCode() : 0;
     }
 
-    private static PathImpl parseProperty(String property) {
-        PathImpl path = new PathImpl();
-        String tmp = property;
-        do {
-            Matcher matcher = pathPattern.matcher(tmp);
-            if (matcher.matches()) {
-                String value = matcher.group(1);
-                String indexed = matcher.group(2);
-                String index = matcher.group(3);
-                NodeImpl node = new NodeImpl(value);
-                if (indexed != null) {
-                    node.setInIterable(true);
-                }
-                if (index != null && index.length() > 0) {
-                    try {
-                        Integer i = Integer.valueOf(index);
-                        node.setIndex(i);
-                    } catch (NumberFormatException e) {
-                        node.setKey(index);
-                    }
-                }
-                path.addNode(node);
-                tmp = matcher.group(5);
-            } else {
-                throw new IllegalArgumentException(
-                      "Unable to parse property path " + property);
-            }
-        } while (tmp != null);
-        return path;
-    }
-
 }

Added: incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/PathNavigation.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/PathNavigation.java?rev=1166451&view=auto
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/PathNavigation.java (added)
+++ incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/PathNavigation.java Wed Sep  7 22:32:26 2011
@@ -0,0 +1,304 @@
+/*
+ *  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.bval.jsr303.util;
+
+import java.io.StringWriter;
+import java.text.ParsePosition;
+
+import javax.validation.ValidationException;
+
+import org.apache.commons.lang3.StringEscapeUtils;
+
+/**
+ * Defines a path navigation algorithm and a means of interacting with same.
+ * 
+ * @version $Rev: 1136233 $ $Date: 2011-06-15 17:49:27 -0500 (Wed, 15 Jun 2011) $
+ */
+public class PathNavigation {
+
+    /**
+     * Path traversal callback function interface.
+     */
+    public interface Callback<T> {
+        /**
+         * Handle a .-delimited property.
+         * 
+         * @param name
+         */
+        void handleProperty(String name);
+
+        /**
+         * Handle an index or key embedded in [].
+         * 
+         * @param value
+         */
+        void handleIndexOrKey(String value);
+
+        /**
+         * Handle contiguous [].
+         */
+        void handleGenericInIterable();
+
+        /**
+         * Return a result. Called after navigation is complete.
+         * 
+         * @return result
+         */
+        T result();
+    }
+
+    /**
+     * Callback "procedure" that always returns null.
+     */
+    public static abstract class CallbackProcedure implements Callback<Object> {
+
+        /**
+         * {@inheritDoc}
+         */
+        public final Object result() {
+            complete();
+            return null;
+        }
+
+        /**
+         * Complete this CallbackProcedure. Default implementation is noop.
+         */
+        protected void complete() {
+        }
+    }
+
+    /**
+     * Create a new PathNavigation instance.
+     */
+    private PathNavigation() {
+    }
+
+    /**
+     * Navigate a path using the specified callback, returning its result.
+     * 
+     * @param <T>
+     * @param propertyPath
+     *            , null is assumed empty/root
+     * @param callback
+     * @return T result
+     */
+    public static <T> T navigateAndReturn(CharSequence propertyPath, Callback<? extends T> callback) {
+        try {
+            parse(propertyPath == null ? "" : propertyPath, new PathPosition(callback));
+        } catch (ValidationException ex) {
+            throw ex;
+        } catch (Exception ex) {
+            throw new ValidationException(String.format("invalid property: %s", propertyPath), ex);
+        }
+        return callback.result();
+    }
+
+    /**
+     * Navigate a path using the specified callback.
+     * 
+     * @param propertyPath
+     * @param callback
+     */
+    public static void navigate(CharSequence propertyPath, Callback<?> callback) {
+        navigateAndReturn(propertyPath, callback);
+    }
+
+    private static void parse(CharSequence path, PathPosition pos) throws Exception {
+        int len = path.length();
+        boolean sep = true;
+        while (pos.getIndex() < len) {
+            int here = pos.getIndex();
+            char c = path.charAt(here);
+            switch (c) {
+            case ']':
+                throw new IllegalStateException(String.format("Position %s: unexpected '%s'", here, c));
+            case '[':
+                handleIndex(path, pos.next());
+                break;
+            case '.':
+                if (sep) {
+                    throw new IllegalStateException(String.format("Position %s: expected property, index/key, or end of expression", here));
+                }
+                sep = true;
+                pos.next();
+                // fall through:
+            default:
+                if (!sep) {
+                    throw new IllegalStateException(String.format("Position %s: expected property path separator, index/key, or end of expression", here));
+                }
+                pos.handleProperty(parseProperty(path, pos));
+            }
+            sep = false;
+        }
+    }
+
+    private static String parseProperty(CharSequence path, PathPosition pos) throws Exception {
+        int len = path.length();
+        int start = pos.getIndex();
+        loop: while (pos.getIndex() < len) {
+            switch (path.charAt(pos.getIndex())) {
+            case '[':
+            case ']':
+            case '.':
+                break loop;
+            }
+            pos.next();
+        }
+        if (pos.getIndex() > start) {
+            return path.subSequence(start, pos.getIndex()).toString();
+        }
+        throw new IllegalStateException(String.format("Position %s: expected property", start));
+    }
+
+    /**
+     * Handles an index/key. If the text contained between [] is surrounded by a pair of " or ', it will be treated as a
+     * string which may contain Java escape sequences.
+     * 
+     * @param path
+     * @param pos
+     * @throws Exception
+     */
+    private static void handleIndex(CharSequence path, PathPosition pos) throws Exception {
+        int len = path.length();
+        int start = pos.getIndex();
+        if (start < len) {
+            char first = path.charAt(pos.getIndex());
+            if (first == '"' || first == '\'') {
+                String s = parseQuotedString(path, pos);
+                if (s != null && path.charAt(pos.getIndex()) == ']') {
+                    pos.handleIndexOrKey(s);
+                    pos.next();
+                    return;
+                }
+            }
+            // no quoted string; match ] greedily
+            while (pos.getIndex() < len) {
+                int here = pos.getIndex();
+                try {
+                    if (path.charAt(here) == ']') {
+                        if (here == start) {
+                            pos.handleGenericInIterable();
+                        } else {
+                            pos.handleIndexOrKey(path.subSequence(start, here).toString());
+                        }
+                        return;
+                    }
+                } finally {
+                    pos.next();
+                }
+            }
+        }
+        throw new IllegalStateException(String.format("Position %s: unparsable index", start));
+    }
+
+    private static String parseQuotedString(CharSequence path, PathPosition pos) throws Exception {
+        int len = path.length();
+        int start = pos.getIndex();
+        if (start < len) {
+            char quote = path.charAt(start);
+            pos.next();
+            StringWriter w = new StringWriter();
+            while (pos.getIndex() < len) {
+                int here = pos.getIndex();
+                // look for matching quote
+                if (path.charAt(here) == quote) {
+                    pos.next();
+                    return w.toString();
+                }
+                int codePoints = StringEscapeUtils.UNESCAPE_JAVA.translate(path, here, w);
+                if (codePoints == 0) {
+                    w.write(Character.toChars(Character.codePointAt(path, here)));
+                    pos.next();
+                } else {
+                    for (int i = 0; i < codePoints; i++) {
+                        pos.plus(Character.charCount(Character.codePointAt(path, pos.getIndex())));
+                    }
+                }
+            }
+            // if reached, reset due to no ending quote found
+            pos.setIndex(start);
+        }
+        return null;
+    }
+
+    /**
+     * ParsePosition/Callback
+     */
+    private static class PathPosition extends ParsePosition implements Callback<Object> {
+        final Callback<?> delegate;
+
+        /**
+         * Create a new {@link PathPosition} instance.
+         * 
+         * @param delegate
+         */
+        private PathPosition(Callback<?> delegate) {
+            super(0);
+            this.delegate = delegate;
+        }
+
+        /**
+         * Increment and return this.
+         * 
+         * @return this
+         */
+        public PathPosition next() {
+            return plus(1);
+        }
+
+        /**
+         * Increase position and return this.
+         * 
+         * @param addend
+         * @return this
+         */
+        public PathPosition plus(int addend) {
+            setIndex(getIndex() + addend);
+            return this;
+        }
+
+        /**
+         * {@inheritDoc}
+         */
+        public void handleProperty(String name) {
+            delegate.handleProperty(name);
+        }
+
+        /**
+         * {@inheritDoc}
+         */
+        public void handleIndexOrKey(String value) {
+            delegate.handleIndexOrKey(value);
+        }
+
+        /**
+         * {@inheritDoc}
+         */
+        public void handleGenericInIterable() {
+            delegate.handleGenericInIterable();
+        }
+
+        /**
+         * {@inheritDoc}
+         */
+        public Object result() {
+            return null;
+        }
+
+    }
+
+}

Propchange: incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/PathNavigation.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/SecureActions.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/SecureActions.java?rev=1166451&r1=1166450&r2=1166451&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/SecureActions.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/SecureActions.java Wed Sep  7 22:32:26 2011
@@ -18,8 +18,6 @@
  */
 package org.apache.bval.jsr303.util;
 
-import org.apache.bval.util.PrivilegedActions;
-
 import java.lang.reflect.AccessibleObject;
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
@@ -27,6 +25,8 @@ import java.lang.reflect.Modifier;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 
+import org.apache.bval.util.PrivilegedActions;
+
 /**
  * Description: utility methods to perform actions with AccessController or without.<br/>
  */

Added: incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ValidationContextTraversal.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ValidationContextTraversal.java?rev=1166451&view=auto
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ValidationContextTraversal.java (added)
+++ incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ValidationContextTraversal.java Wed Sep  7 22:32:26 2011
@@ -0,0 +1,203 @@
+/*
+ * 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.bval.jsr303.util;
+
+import java.lang.reflect.Type;
+
+import org.apache.bval.DynamicMetaBean;
+import org.apache.bval.jsr303.Jsr303MetaBeanFactory;
+import org.apache.bval.jsr303.UnknownPropertyException;
+import org.apache.bval.jsr303.util.PathNavigation.CallbackProcedure;
+import org.apache.bval.model.MetaBean;
+import org.apache.bval.model.MetaProperty;
+import org.apache.bval.model.ValidationContext;
+import org.apache.bval.util.AccessStrategy;
+import org.apache.bval.util.IndexedAccess;
+import org.apache.bval.util.KeyedAccess;
+import org.apache.bval.util.PropertyAccess;
+import org.apache.commons.lang3.ObjectUtils;
+import org.apache.commons.lang3.reflect.TypeUtils;
+
+/**
+ * {@link ValidationContext} traversal {@link CallbackProcedure}.
+ * 
+ * @version $Rev: 1137074 $ $Date: 2011-06-17 18:20:30 -0500 (Fri, 17 Jun 2011) $
+ */
+public class ValidationContextTraversal extends CallbackProcedure {
+    private static class NullSafePropertyAccess extends PropertyAccess {
+
+        /**
+         * Create a new NullSafePropertyAccess instance.
+         * 
+         * @param clazz
+         * @param propertyName
+         */
+        public NullSafePropertyAccess(Class<?> clazz, String propertyName) {
+            super(clazz, propertyName);
+        }
+
+        /**
+         * {@inheritDoc}
+         */
+        @Override
+        public Object get(Object bean) {
+            return bean == null ? null : super.get(bean);
+        }
+    }
+
+    private final ValidationContext<?> validationContext;
+    private Type type;
+    private Class<?> rawType;
+
+    /**
+     * Create a new {@link ValidationContextTraversal} instance.
+     * 
+     * @param validationContext
+     */
+    public ValidationContextTraversal(ValidationContext<?> validationContext) {
+        this.validationContext = validationContext;
+        init();
+    }
+
+    /**
+     * Initialize from {@link ValidationContext}.
+     */
+    public void init() {
+        this.rawType = validationContext.getMetaBean().getBeanClass();
+        this.type = this.rawType;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void handleIndexOrKey(String token) {
+        moveDownIfNecessary();
+
+        AccessStrategy access;
+        if (IndexedAccess.getJavaElementType(type) != null) {
+            try {
+                Integer index = token == null ? null : Integer.valueOf(token);
+                access = new IndexedAccess(type, index);
+                validationContext.setCurrentIndex(index);
+            } catch (NumberFormatException e) {
+                throw new UnknownPropertyException(String.format("Cannot parse %s as an array/iterable index", token),
+                    e);
+            }
+        } else if (KeyedAccess.getJavaElementType(type) != null) {
+            access = new KeyedAccess(type, token);
+            validationContext.setCurrentKey(token);
+        } else {
+            throw new UnknownPropertyException(String.format("Cannot determine index/key type for %s", type));
+        }
+        Object value = validationContext.getBean();
+        Object child = value == null ? null : access.get(value);
+        setType(child == null ? access.getJavaType() : child.getClass());
+        validationContext.setBean(child,
+            validationContext.getMetaBean().resolveMetaBean(child == null ? rawType : child));
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void handleProperty(String token) {
+        moveDownIfNecessary();
+
+        MetaBean metaBean = validationContext.getMetaBean();
+
+        if (metaBean instanceof DynamicMetaBean) {
+            metaBean = metaBean.resolveMetaBean(ObjectUtils.defaultIfNull(validationContext.getBean(), rawType));
+        }
+        MetaProperty mp = metaBean.getProperty(token);
+        if (mp == null) {
+            // TODO this could indicate a property hosted on a superclass; should we shunt the context traversal down a path based on that type?
+
+            PropertyAccess access = new PropertyAccess(rawType, token);
+            if (access.isKnown()) {
+                // add heretofore unknown, but valid, property on the fly:
+                mp = Jsr303MetaBeanFactory.addMetaProperty(metaBean, access);
+            } else {
+                throw new UnknownPropertyException("unknown property '" + token + "' in " + metaBean.getId());
+            }
+        }
+        validationContext.setMetaProperty(mp);
+        setType(mp.getType());
+    }
+
+    /**
+     * If we currently have a property, navigate the context such that the property becomes the bean, in preparation for
+     * another property.
+     * 
+     * @param validationContext
+     */
+    public void moveDownIfNecessary() {
+        MetaProperty mp = validationContext.getMetaProperty();
+        if (mp != null) {
+            if (mp.getMetaBean() == null) {
+                throw new UnknownPropertyException(String.format("Property %s.%s is not cascaded", mp
+                    .getParentMetaBean().getId(), mp.getName()));
+            }
+            validationContext.moveDown(mp, new NullSafePropertyAccess(validationContext.getMetaBean().getBeanClass(),
+                mp.getName()));
+        }
+    }
+
+    /**
+     * Set the type of the expression processed thus far.
+     * 
+     * @param type
+     */
+    protected void setType(Type type) {
+        this.rawType = TypeUtils.getRawType(type, this.type);
+        this.type = type;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void handleGenericInIterable() {
+        throw new UnsupportedOperationException("Cannot navigate a ValidationContext to []");
+    }
+
+    /**
+     * @return the type
+     */
+    public Type getType() {
+        return type;
+    }
+
+    /**
+     * @return the rawType
+     */
+    public Class<?> getRawType() {
+        return rawType;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected void complete() {
+        super.complete();
+        if (validationContext.getMetaProperty() != null) {
+            return;
+        }
+        if (validationContext.getMetaBean() instanceof DynamicMetaBean) {
+            validationContext.setMetaBean(validationContext.getMetaBean().resolveMetaBean(
+                ObjectUtils.defaultIfNull(validationContext.getBean(), rawType)));
+        }
+    }
+}
\ No newline at end of file

Propchange: incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ValidationContextTraversal.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxy.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxy.java?rev=1166451&r1=1166450&r2=1166451&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxy.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxy.java Wed Sep  7 22:32:26 2011
@@ -16,9 +16,6 @@
  */
 package org.apache.bval.jsr303.xml;
 
-
-import org.apache.bval.jsr303.util.SecureActions;
-
 import java.io.Serializable;
 import java.lang.annotation.Annotation;
 import java.lang.reflect.InvocationHandler;
@@ -30,16 +27,17 @@ import java.util.Map;
 import java.util.SortedSet;
 import java.util.TreeSet;
 
+import org.apache.bval.jsr303.util.SecureActions;
 
 /**
  * Description: <br/>
- * InvocationHandler implementation of <code>Annotation</code> that pretends it is a
- * "real" source code annotation.
+ * InvocationHandler implementation of <code>Annotation</code> that pretends it
+ * is a "real" source code annotation.
  * <p/>
  */
-//TODO confirm that this class must be public for RT invocation purposes, then document this fact
-//TODO move this guy up to org.apache.bval.jsr303 or org.apache.bval.jsr303.model
-public class AnnotationProxy implements Annotation, InvocationHandler, Serializable {
+// TODO move this guy up to org.apache.bval.jsr303 or
+// org.apache.bval.jsr303.model
+class AnnotationProxy implements Annotation, InvocationHandler, Serializable {
 
     /** Serialization version */
     private static final long serialVersionUID = 1L;
@@ -49,6 +47,7 @@ public class AnnotationProxy implements 
 
     /**
      * Create a new AnnotationProxy instance.
+     * 
      * @param <A>
      * @param descriptor
      */
@@ -74,8 +73,7 @@ public class AnnotationProxy implements 
             }
         }
         if (processedValuesFromDescriptor != descriptor.size()) {
-            throw new RuntimeException(
-                  "Trying to instanciate " + annotationType + " with unknown paramters.");
+            throw new RuntimeException("Trying to instanciate " + annotationType + " with unknown paramters.");
         }
         return result;
     }
@@ -105,7 +103,8 @@ public class AnnotationProxy implements 
         result.append('@').append(annotationType().getName()).append('(');
         boolean comma = false;
         for (String m : getMethodsSorted()) {
-            if (comma) result.append(", ");
+            if (comma)
+                result.append(", ");
             result.append(m).append('=').append(values.get(m));
             comma = true;
         }
@@ -129,4 +128,3 @@ public class AnnotationProxy implements 
         }
     }
 }
-

Modified: incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxyBuilder.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxyBuilder.java?rev=1166451&r1=1166450&r2=1166451&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxyBuilder.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxyBuilder.java Wed Sep  7 22:32:26 2011
@@ -16,28 +16,31 @@
  */
 package org.apache.bval.jsr303.xml;
 
-
-import org.apache.bval.jsr303.Jsr303MetaBeanFactory;
-import org.apache.bval.jsr303.util.SecureActions;
-
-import javax.validation.Payload;
-import javax.validation.ValidationException;
 import java.lang.annotation.Annotation;
-import java.lang.reflect.*;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.HashMap;
 import java.util.Map;
 
+import javax.validation.Payload;
+import javax.validation.ValidationException;
+
+import org.apache.bval.jsr303.ConstraintAnnotationAttributes;
+import org.apache.bval.jsr303.util.SecureActions;
+
 /**
- * Description: Holds the information and creates an annotation proxy
- * during xml parsing of validation mapping constraints. <br/>
+ * Description: Holds the information and creates an annotation proxy during xml
+ * parsing of validation mapping constraints. <br/>
  */
-//TODO move this guy up to org.apache.bval.jsr303 or org.apache.bval.jsr303.model
+// TODO move this guy up to org.apache.bval.jsr303 or
+// org.apache.bval.jsr303.model
 final public class AnnotationProxyBuilder<A extends Annotation> {
-
     private final Class<A> type;
-
     private final Map<String, Object> elements = new HashMap<String, Object>();
 
     /**
@@ -63,8 +66,9 @@ final public class AnnotationProxyBuilde
     }
 
     /**
-     * Create a builder initially configured to create an annotation equivalent to <code>annot</code>.
-     *
+     * Create a builder initially configured to create an annotation equivalent
+     * to <code>annot</code>.
+     * 
      * @param annot Annotation to be replicated.
      */
     @SuppressWarnings("unchecked")
@@ -114,7 +118,8 @@ final public class AnnotationProxyBuilde
      * Learn whether a given element has been configured.
      *
      * @param elementName
-     * @return <code>true</code> if an <code>elementName</code> element is found on this annotation
+     * @return <code>true</code> if an <code>elementName</code> element is found
+     *         on this annotation
      */
     public boolean contains(String elementName) {
         return elements.containsKey(elementName);
@@ -144,7 +149,7 @@ final public class AnnotationProxyBuilde
      * @param message
      */
     public void setMessage(String message) {
-        putValue(Jsr303MetaBeanFactory.ANNOTATION_MESSAGE, message);
+        ConstraintAnnotationAttributes.MESSAGE.put(elements, message);
     }
 
     /**
@@ -153,16 +158,16 @@ final public class AnnotationProxyBuilde
      * @param groups
      */
     public void setGroups(Class<?>[] groups) {
-        putValue(Jsr303MetaBeanFactory.ANNOTATION_GROUPS, groups);
+        ConstraintAnnotationAttributes.GROUPS.put(elements, groups);
     }
 
     /**
      * Configure the well-known JSR303 "payload" element.
-     *
+     * 
      * @param payload
      */
     public void setPayload(Class<? extends Payload>[] payload) {
-        putValue(Jsr303MetaBeanFactory.ANNOTATION_PAYLOAD, payload);
+        ConstraintAnnotationAttributes.PAYLOAD.put(elements, payload);
     }
 
     /**

Modified: incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/ValidationMappingParser.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/ValidationMappingParser.java?rev=1166451&r1=1166450&r2=1166451&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/ValidationMappingParser.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/ValidationMappingParser.java Wed Sep  7 22:32:26 2011
@@ -17,16 +17,22 @@
 package org.apache.bval.jsr303.xml;
 
 
-import org.apache.bval.jsr303.ApacheValidatorFactory;
-import org.apache.bval.jsr303.Jsr303MetaBeanFactory;
-import org.apache.bval.jsr303.util.EnumerationConverter;
-import org.apache.bval.jsr303.util.IOUtils;
-import org.apache.bval.jsr303.util.SecureActions;
-import org.apache.bval.util.FieldAccess;
-import org.apache.bval.util.MethodAccess;
-import org.apache.commons.beanutils.ConvertUtils;
-import org.apache.commons.beanutils.Converter;
-import org.apache.commons.lang.StringUtils;
+import java.io.InputStream;
+import java.io.Serializable;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Array;
+import java.lang.reflect.Field;
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
 
 import javax.validation.Constraint;
 import javax.validation.ConstraintValidator;
@@ -38,16 +44,17 @@ import javax.xml.bind.JAXBException;
 import javax.xml.bind.Unmarshaller;
 import javax.xml.transform.stream.StreamSource;
 import javax.xml.validation.Schema;
-import java.io.InputStream;
-import java.io.Serializable;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Array;
-import java.lang.reflect.Field;
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.*;
+
+import org.apache.bval.jsr303.ApacheValidatorFactory;
+import org.apache.bval.jsr303.ConstraintAnnotationAttributes;
+import org.apache.bval.jsr303.util.EnumerationConverter;
+import org.apache.bval.jsr303.util.IOUtils;
+import org.apache.bval.jsr303.util.SecureActions;
+import org.apache.bval.util.FieldAccess;
+import org.apache.bval.util.MethodAccess;
+import org.apache.commons.beanutils.ConvertUtils;
+import org.apache.commons.beanutils.Converter;
+import org.apache.commons.lang3.StringUtils;
 
 
 /**
@@ -57,10 +64,10 @@ import java.util.*;
 public class ValidationMappingParser {
     //    private static final Log log = LogFactory.getLog(ValidationMappingParser.class);
     private static final String VALIDATION_MAPPING_XSD = "META-INF/validation-mapping-1.0.xsd";
-    private static final String[] RESERVED_PARAMS = {
-            Jsr303MetaBeanFactory.ANNOTATION_MESSAGE,
-            Jsr303MetaBeanFactory.ANNOTATION_GROUPS,
-            Jsr303MetaBeanFactory.ANNOTATION_PAYLOAD };
+
+    private static final Set<ConstraintAnnotationAttributes> RESERVED_PARAMS = Collections.unmodifiableSet(EnumSet.of(
+        ConstraintAnnotationAttributes.GROUPS, ConstraintAnnotationAttributes.MESSAGE,
+        ConstraintAnnotationAttributes.PAYLOAD));
 
     private final Set<Class<?>> processedClasses;
     private final ApacheValidatorFactory factory;
@@ -180,9 +187,9 @@ public class ValidationMappingParser {
     }
 
     private void checkValidName(String name) {
-        for (String each : RESERVED_PARAMS) {
-            if (each.equals(name)) {
-                throw new ValidationException(each + " is a reserved parameter name.");
+        for (ConstraintAnnotationAttributes attr : RESERVED_PARAMS) {
+            if (attr.getAttributeName().equals(name)) {
+                throw new ValidationException(name + " is a reserved parameter name.");
             }
         }
     }
@@ -437,7 +444,8 @@ public class ValidationMappingParser {
             Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) clazz;
 
             ValidatedByType validatedByType = constraintDefinition.getValidatedBy();
-            List<Class<? extends ConstraintValidator<?,?>>> classes = new ArrayList();
+            List<Class<? extends ConstraintValidator<?, ?>>> classes =
+                new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
             /*
              If include-existing-validator is set to false,
              ConstraintValidator defined on the constraint annotation are ignored.

Added: incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/constraints/AuthorAddressKnown.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/constraints/AuthorAddressKnown.java?rev=1166451&view=auto
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/constraints/AuthorAddressKnown.java (added)
+++ incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/constraints/AuthorAddressKnown.java Wed Sep  7 22:32:26 2011
@@ -0,0 +1,75 @@
+/*
+ *  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.bval.constraints;
+
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import javax.validation.Constraint;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.Payload;
+
+import org.apache.bval.jsr303.example.Address;
+import org.apache.bval.jsr303.example.Author;
+
+/**
+ * 
+ * 
+ * @version $Rev: 999729 $ $Date: 2010-09-21 21:37:54 -0500 (Tue, 21 Sep 2010) $
+ */
+@Target( { ANNOTATION_TYPE, METHOD, FIELD })
+@Constraint(validatedBy = AuthorAddressKnown.Validator.class)
+@Retention(RUNTIME)
+public @interface AuthorAddressKnown {
+
+    String message() default "{org.apache.bval.constraints.AuthorAddressKnown.message}";
+
+    Class<?>[] groups() default {};
+
+    Class<? extends Payload>[] payload() default { };
+
+    public static class Validator implements ConstraintValidator<AuthorAddressKnown, Author> {
+
+        /**
+         * {@inheritDoc}
+         */
+        public void initialize(AuthorAddressKnown constraintAnnotation) {
+        }
+
+        /**
+         * {@inheritDoc}
+         */
+        public boolean isValid(Author value, ConstraintValidatorContext context) {
+            if (value.getAddresses() == null) {
+                return false;
+            }
+            for (Address address : value.getAddresses()) {
+                if (address != null) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+    }
+}

Propchange: incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/constraints/AuthorAddressKnown.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/constraints/HasStringValidator.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/constraints/HasStringValidator.java?rev=1166451&r1=1166450&r2=1166451&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/constraints/HasStringValidator.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/constraints/HasStringValidator.java Wed Sep  7 22:32:26 2011
@@ -18,7 +18,7 @@
  */
 package org.apache.bval.constraints;
 
-import org.apache.commons.lang.ArrayUtils;
+import org.apache.commons.lang3.ArrayUtils;
 
 import javax.validation.ConstraintValidator;
 import javax.validation.ConstraintValidatorContext;

Modified: incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/BeanDescriptorTest.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/BeanDescriptorTest.java?rev=1166451&r1=1166450&r2=1166451&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/BeanDescriptorTest.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/BeanDescriptorTest.java Wed Sep  7 22:32:26 2011
@@ -18,23 +18,31 @@
  */
 package org.apache.bval.jsr303;
 
-import junit.framework.Assert;
-import junit.framework.TestCase;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
 import org.apache.bval.jsr303.util.TestUtils;
 
-import javax.validation.*;
-import javax.validation.constraints.NotNull;
-import javax.validation.groups.Default;
-import javax.validation.metadata.*;
-import javax.validation.metadata.ElementDescriptor.ConstraintFinder;
 import java.lang.annotation.Documented;
 import java.lang.annotation.Retention;
 import java.lang.annotation.Target;
 import java.util.Locale;
 import java.util.Set;
+import org.apache.bval.jsr303.util.TestUtils;
 
-import static java.lang.annotation.ElementType.*;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import javax.validation.Constraint;
+import javax.validation.Payload;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.constraints.NotNull;
+import javax.validation.groups.Default;
+import javax.validation.metadata.*;
+import javax.validation.metadata.ElementDescriptor.ConstraintFinder;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
 
 /**
  * Tests the implementation of {@link BeanDescriptor} and its dependent
@@ -43,7 +51,6 @@ import static java.lang.annotation.Reten
  * @author Carlos Vara
  */
 public class BeanDescriptorTest extends TestCase {
-
     static ValidatorFactory factory;
 
     static {
@@ -51,19 +58,36 @@ public class BeanDescriptorTest extends 
         ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
     }
 
-    private Validator getValidator() {
+    /**
+     * Validator instance to test
+     */
+    protected Validator validator;
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        validator = createValidator();
+    }
+
+    /**
+     * Create the validator instance.
+     * 
+     * @return Validator
+     */
+    protected Validator createValidator() {
         return factory.getValidator();
     }
-    
-    
+
     /**
      * Check that groups(), message() and payload() are always in the
      * attributes.
      */
     public void testMandatoryAttributesPresentInConstraintDescriptor() {
-        Validator validator = getValidator();
-        
-        Set<ConstraintDescriptor<?>> nameDescriptors = validator.getConstraintsForClass(Form.class).getConstraintsForProperty("name").getConstraintDescriptors();
+        Set<ConstraintDescriptor<?>> nameDescriptors =
+            validator.getConstraintsForClass(Form.class).getConstraintsForProperty("name").getConstraintDescriptors();
         Assert.assertEquals("Incorrect number of descriptors", 1, nameDescriptors.size());
         ConstraintDescriptor<?> nameDescriptor = nameDescriptors.iterator().next();
         Assert.assertTrue("groups attribute not present", nameDescriptor.getAttributes().containsKey("groups"));
@@ -76,19 +100,20 @@ public class BeanDescriptorTest extends 
      * inheriting groups.
      */
     public void testCorrectValueForInheritedGroupsAttribute() {
-        Validator validator = getValidator();
-        
-        Set<ConstraintDescriptor<?>> passwordDescriptors = validator.getConstraintsForClass(Account.class).getConstraintsForProperty("password").getConstraintDescriptors();
+        Set<ConstraintDescriptor<?>> passwordDescriptors =
+            validator.getConstraintsForClass(Account.class).getConstraintsForProperty("password")
+                .getConstraintDescriptors();
         Assert.assertEquals("Incorrect number of descriptors", 1, passwordDescriptors.size());
         ConstraintDescriptor<?> passwordDescriptor = passwordDescriptors.iterator().next();
-        Assert.assertEquals("Incorrect number of composing constraints", 1, passwordDescriptor.getComposingConstraints().size());
+        Assert.assertEquals("Incorrect number of composing constraints", 1, passwordDescriptor
+            .getComposingConstraints().size());
         ConstraintDescriptor<?> notNullDescriptor = passwordDescriptor.getComposingConstraints().iterator().next();
-        
+
         // Check that the groups value containts Group1.class
         Class<?>[] notNullGroups = (Class<?>[]) notNullDescriptor.getAttributes().get("groups");
         boolean found = false;
-        for ( Class<?> group : notNullGroups ) {
-            if ( group == Group1.class ) {
+        for (Class<?> group : notNullGroups) {
+            if (group == Group1.class) {
                 found = true;
                 break;
             }
@@ -102,17 +127,19 @@ public class BeanDescriptorTest extends 
      * of the queried class.
      */
     public void testImplicitGroupIsPresent() {
-        Validator validator = getValidator();
-        
-        Set<ConstraintDescriptor<?>> nameDescriptors = validator.getConstraintsForClass(Woman.class).getConstraintsForProperty("name").getConstraintDescriptors();
+        Set<ConstraintDescriptor<?>> nameDescriptors =
+            validator.getConstraintsForClass(Woman.class).getConstraintsForProperty("name").getConstraintDescriptors();
         Assert.assertEquals("Incorrect number of descriptors", 1, nameDescriptors.size());
         ConstraintDescriptor<?> notNullDescriptor = nameDescriptors.iterator().next();
-        
-        // Check that the groups attribute value contains the implicit group Person and the Default group
+
+        // Check that the groups attribute value contains the implicit group
+        // Person and the Default group
         Class<?>[] notNullGroups = (Class<?>[]) notNullDescriptor.getAttributes().get("groups");
         Assert.assertEquals("Incorrect number of groups", 2, notNullGroups.length);
-        Assert.assertTrue("Default group not present", notNullGroups[0].equals(Default.class) || notNullGroups[1].equals(Default.class));
-        Assert.assertTrue("Implicit group not present", notNullGroups[0].equals(Person.class) || notNullGroups[1].equals(Person.class));
+        Assert.assertTrue("Default group not present", notNullGroups[0].equals(Default.class)
+            || notNullGroups[1].equals(Default.class));
+        Assert.assertTrue("Implicit group not present", notNullGroups[0].equals(Person.class)
+            || notNullGroups[1].equals(Person.class));
     }
 
     /**
@@ -120,12 +147,11 @@ public class BeanDescriptorTest extends 
      * interface group when querying the interface directly.
      */
     public void testNoImplicitGroupWhenQueryingInterfaceDirectly() {
-        Validator validator = getValidator();
-        
-        Set<ConstraintDescriptor<?>> nameDescriptors = validator.getConstraintsForClass(Person.class).getConstraintsForProperty("name").getConstraintDescriptors();
+        Set<ConstraintDescriptor<?>> nameDescriptors =
+            validator.getConstraintsForClass(Person.class).getConstraintsForProperty("name").getConstraintDescriptors();
         Assert.assertEquals("Incorrect number of descriptors", 1, nameDescriptors.size());
         ConstraintDescriptor<?> notNullDescriptor = nameDescriptors.iterator().next();
-        
+
         // Check that only the default group is present
         Class<?>[] notNullGroups = (Class<?>[]) notNullDescriptor.getAttributes().get("groups");
         Assert.assertEquals("Incorrect number of groups", 1, notNullGroups.length);
@@ -137,11 +163,9 @@ public class BeanDescriptorTest extends 
      * {@link ElementDescriptor#getElementClass()} work as defined in the spec.
      */
     public void testElementDescriptorGetElementClass() {
-        Validator validator = getValidator();
-        
-        BeanDescriptor beanDescriptor = validator.getConstraintsForClass( Person.class );
+        BeanDescriptor beanDescriptor = validator.getConstraintsForClass(Person.class);
         Assert.assertEquals("Incorrect class returned", Person.class, beanDescriptor.getElementClass());
-        
+
         PropertyDescriptor nameDescriptor = beanDescriptor.getConstraintsForProperty("name");
         Assert.assertEquals("Incorrect class returned", String.class, nameDescriptor.getElementClass());
     }
@@ -151,12 +175,12 @@ public class BeanDescriptorTest extends 
      * {@link ConstraintFinder#lookingAt(javax.validation.metadata.Scope)}.
      */
     public void testConstraintFinderLookingAt() {
-        Validator validator = getValidator();
-        
-        PropertyDescriptor nameDescriptor = validator.getConstraintsForClass( Woman.class ).getConstraintsForProperty("name");
-        Set<ConstraintDescriptor<?>> constraints = nameDescriptor.findConstraints().lookingAt(Scope.HIERARCHY).getConstraintDescriptors();
+        PropertyDescriptor nameDescriptor =
+            validator.getConstraintsForClass(Woman.class).getConstraintsForProperty("name");
+        Set<ConstraintDescriptor<?>> constraints =
+            nameDescriptor.findConstraints().lookingAt(Scope.HIERARCHY).getConstraintDescriptors();
         Assert.assertEquals("Incorrect number of descriptors", 1, constraints.size());
-        
+
         constraints = nameDescriptor.findConstraints().lookingAt(Scope.LOCAL_ELEMENT).getConstraintDescriptors();
         Assert.assertEquals("Incorrect number of descriptors", 0, constraints.size());
         TestUtils.failOnModifiable(constraints, "constraintFinder constraintDescriptors");
@@ -164,48 +188,49 @@ public class BeanDescriptorTest extends 
         constraints = nameDescriptor.getConstraintDescriptors();
         Assert.assertEquals("Incorrect number of descriptors", 1, constraints.size());
     }
-    
+
     public static class Form {
         @NotNull
         public String name;
     }
-    
+
     public static class Account {
-        @Password(groups={Group1.class})
+        @Password(groups = { Group1.class })
         public String password;
     }
-    
-    @NotNull(groups={})
+
+    @NotNull(groups = {})
     @Constraint(validatedBy = {})
     @Documented
-    @Target({ METHOD, FIELD, TYPE })
+    @Target( { METHOD, FIELD, TYPE })
     @Retention(RUNTIME)
     public static @interface Password {
         String message() default "Invalid password";
-        Class<?>[] groups() default { };
+
+        Class<?>[] groups() default {};
+
         Class<? extends Payload>[] payload() default {};
     }
-    
+
     public static interface Group1 {
     }
-    
-    
+
     public static class Woman implements Person {
-        
+
         private String name;
 
         public String getName() {
             return this.name;
         }
-        
+
         public void setName(String name) {
             this.name = name;
         }
     }
-    
+
     public static interface Person {
         @NotNull
         String getName();
     }
-    
+
 }

Modified: incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/BootstrapTest.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/BootstrapTest.java?rev=1166451&r1=1166450&r2=1166451&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/BootstrapTest.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/BootstrapTest.java Wed Sep  7 22:32:26 2011
@@ -18,40 +18,49 @@
  */
 package org.apache.bval.jsr303;
 
-import junit.framework.Assert;
-import junit.framework.TestCase;
-import org.apache.bval.constraints.NotNullValidator;
-import org.apache.bval.jsr303.example.Customer;
-
-import javax.validation.*;
-import javax.validation.bootstrap.ProviderSpecificBootstrap;
-import javax.validation.spi.ValidationProvider;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 import java.util.Locale;
 import java.util.Set;
 
+import javax.validation.Configuration;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.ConstraintViolation;
+import javax.validation.Validation;
+import javax.validation.ValidationException;
+import javax.validation.ValidationProviderResolver;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.bootstrap.ProviderSpecificBootstrap;
+import javax.validation.spi.ValidationProvider;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import org.apache.bval.constraints.NotNullValidator;
+import org.apache.bval.jsr303.example.Customer;
+
 /**
  * Description: <br/>
  */
 public class BootstrapTest extends TestCase {
     public void testDirectBootstrap() {
-        Validator validator =
-                ApacheValidatorFactory.getDefault().getValidator();
+        Validator validator = ApacheValidatorFactory.getDefault().getValidator();
         Assert.assertNotNull(validator);
-        Assert.assertTrue(ApacheValidatorFactory.getDefault() ==
-                ApacheValidatorFactory.getDefault());
+        Assert.assertTrue(ApacheValidatorFactory.getDefault() == ApacheValidatorFactory.getDefault());
     }
 
     public void testEverydayBootstrap() {
-        ApacheValidatorFactory factory =
-                (ApacheValidatorFactory) Validation.buildDefaultValidatorFactory();
+        ApacheValidatorFactory factory = (ApacheValidatorFactory) Validation.buildDefaultValidatorFactory();
         Validator validator = factory.getValidator();
         Assert.assertNotNull(validator);
 
-        // each call to Validation.getValidationBuilder() returns a new builder with new state
-        ApacheValidatorFactory factory2 =
-                (ApacheValidatorFactory) Validation.buildDefaultValidatorFactory();
+        // each call to Validation.getValidationBuilder() returns a new builder
+        // with new state
+        ApacheValidatorFactory factory2 = (ApacheValidatorFactory) Validation.buildDefaultValidatorFactory();
         Assert.assertTrue(factory2 != factory);
         Assert.assertTrue(factory2.getMessageInterpolator() != factory.getMessageInterpolator());
 
@@ -72,8 +81,8 @@ public class BootstrapTest extends TestC
     }
 
     /**
-     * some tests based on RI tested behaviors to ensure our 
-     * implementation works as the reference implementation
+     * some tests based on RI tested behaviors to ensure our implementation
+     * works as the reference implementation
      */
 
     public void testCustomConstraintFactory() {
@@ -91,37 +100,34 @@ public class BootstrapTest extends TestC
         Assert.assertFalse(ConstraintViolations.isEmpty());
 
         builder = Validation.byDefaultProvider().configure();
-        builder.constraintValidatorFactory(
-                new ConstraintValidatorFactory() {
-                    public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
-                        if (key == NotNullValidator.class) {
-                            return (T) new BadlyBehavedNotNullValidator();
-                        }
-                        return new DefaultConstraintValidatorFactory().getInstance(key);
-                    }
+        builder.constraintValidatorFactory(new ConstraintValidatorFactory() {
+            public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
+                if (key == NotNullValidator.class) {
+                    @SuppressWarnings("unchecked")
+                    final T result = (T) new BadlyBehavedNotNullValidator();
+                    return result;
                 }
-        );
+                return new DefaultConstraintValidatorFactory().getInstance(key);
+            }
+        });
         factory = builder.buildValidatorFactory();
         validator = factory.getValidator();
         Set<ConstraintViolation<Customer>> ConstraintViolations2 = validator.validate(customer);
-        Assert.assertTrue("Wrong number of constraints",
-                ConstraintViolations.size() > ConstraintViolations2.size());
+        Assert.assertTrue("Wrong number of constraints", ConstraintViolations.size() > ConstraintViolations2.size());
     }
 
     public void testCustomResolverAndType() {
         ValidationProviderResolver resolver = new ValidationProviderResolver() {
 
             public List<ValidationProvider<?>> getValidationProviders() {
-                List<ValidationProvider<?>> list = new ArrayList(1);
+                List<ValidationProvider<?>> list = new ArrayList<ValidationProvider<?>>(1);
                 list.add(new ApacheValidationProvider());
                 return list;
             }
         };
 
-        ApacheValidatorConfiguration builder = Validation
-                .byProvider(ApacheValidationProvider.class)
-                .providerResolver(resolver)
-                .configure();
+        ApacheValidatorConfiguration builder =
+            Validation.byProvider(ApacheValidationProvider.class).providerResolver(resolver).configure();
         assertDefaultBuilderAndFactory(builder);
     }
 
@@ -129,20 +135,15 @@ public class BootstrapTest extends TestC
         ValidationProviderResolver resolver = new ValidationProviderResolver() {
 
             public List<ValidationProvider<?>> getValidationProviders() {
-                List list = new ArrayList();
-                list.add(new ApacheValidationProvider());
-                return list;
+                return Collections.<ValidationProvider<?>> singletonList(new ApacheValidationProvider());
             }
         };
 
-        Configuration<?> builder = Validation
-                .byDefaultProvider()
-                .providerResolver(resolver)
-                .configure();
+        Configuration<?> builder = Validation.byDefaultProvider().providerResolver(resolver).configure();
         assertDefaultBuilderAndFactory(builder);
     }
 
-    private void assertDefaultBuilderAndFactory(Configuration builder) {
+    private void assertDefaultBuilderAndFactory(Configuration<?> builder) {
         Assert.assertNotNull(builder);
         Assert.assertTrue(builder instanceof ConfigurationImpl);
 
@@ -155,26 +156,22 @@ public class BootstrapTest extends TestC
         ValidationProviderResolver resolver = new ValidationProviderResolver() {
 
             public List<ValidationProvider<?>> getValidationProviders() {
-                return new ArrayList();
+                return Collections.emptyList();
             }
         };
 
         ProviderSpecificBootstrap<ApacheValidatorConfiguration> type =
-                Validation.byProvider(ApacheValidationProvider.class);
+            Validation.byProvider(ApacheValidationProvider.class);
 
         final ProviderSpecificBootstrap<ApacheValidatorConfiguration> specializedBuilderFactory =
-                type.providerResolver(resolver);
+            type.providerResolver(resolver);
 
         try {
             specializedBuilderFactory.configure();
             Assert.fail();
-        }
-        catch (ValidationException e) {
-            Assert.assertTrue(
-                    "Wrong error message",
-                    e.getMessage().contains("provider") && 
-                    e.getMessage().contains("org.apache.bval.jsr303.ApacheValidationProvider")
-            );
+        } catch (ValidationException e) {
+            Assert.assertTrue("Wrong error message", e.getMessage().contains("provider")
+                && e.getMessage().contains("org.apache.bval.jsr303.ApacheValidationProvider"));
         }
     }
 

Modified: incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/CircularReferencesTest.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/CircularReferencesTest.java?rev=1166451&r1=1166450&r2=1166451&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/CircularReferencesTest.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/CircularReferencesTest.java Wed Sep  7 22:32:26 2011
@@ -34,15 +34,33 @@ import java.util.Set;
  * @author Carlos Vara
  */
 public class CircularReferencesTest extends TestCase {
-    
     static ValidatorFactory factory;
 
     static {
         factory = Validation.buildDefaultValidatorFactory();
-        ((DefaultMessageInterpolator)factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
+        ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
     }
 
-    private Validator getValidator() {
+    /**
+     * Validator instance to test
+     */
+    protected Validator validator;
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        validator = createValidator();
+    }
+
+    /**
+     * Create the validator instance.
+     * 
+     * @return Validator
+     */
+    protected Validator createValidator() {
         return factory.getValidator();
     }
 
@@ -51,15 +69,12 @@ public class CircularReferencesTest exte
      * dependency.
      */
     public void testAutoreferringBean() {
-        
-        Validator validator = getValidator();
-        
         Person p1 = new Person();
         p1.name = "too-long-name";
         p1.sibling = p1;
-        
+
         Set<ConstraintViolation<Person>> violations = validator.validate(p1);
-        
+
         Assert.assertEquals("Only 1 violation should be reported", 1, violations.size());
         ConstraintViolation<Person> violation = violations.iterator().next();
         Assert.assertEquals("Incorrect violation path", "name", violation.getPropertyPath().toString());
@@ -70,37 +85,32 @@ public class CircularReferencesTest exte
      * paths inside the bean graph.
      */
     public void testNonCircularArrayOfSameBean() {
-        
-        Validator validator = getValidator();
-        
         Boss boss = new Boss();
         Person p1 = new Person();
         p1.name = "too-long-name";
-        
-        boss.employees = new Person[]{ p1, p1, p1, p1 };
-        
+
+        boss.employees = new Person[] { p1, p1, p1, p1 };
+
         Set<ConstraintViolation<Boss>> violations = validator.validate(boss);
-        
+
         Assert.assertEquals("A total of 4 violations should be reported", 4, violations.size());
-        
     }
-    
-    
+
     public static class Person {
-        
+
         @Valid
         public Person sibling;
-        
-        @Size(max=10)
+
+        @Size(max = 10)
         public String name;
-        
+
     }
-    
+
     public static class Boss {
-        
+
         @Valid
         public Person[] employees;
-        
+
     }
-    
+
 }

Modified: incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/ComposedConstraintsTest.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/ComposedConstraintsTest.java?rev=1166451&r1=1166450&r2=1166451&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/ComposedConstraintsTest.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/ComposedConstraintsTest.java Wed Sep  7 22:32:26 2011
@@ -18,11 +18,8 @@
  */
 package org.apache.bval.jsr303;
 
-import junit.framework.Assert;
-import junit.framework.TestCase;
-import org.apache.bval.jsr303.example.CompanyAddress;
-import org.apache.bval.jsr303.example.FrenchAddress;
-import org.apache.bval.jsr303.util.TestUtils;
+import java.util.Locale;
+import java.util.Set;
 
 import javax.validation.ConstraintViolation;
 import javax.validation.Validation;
@@ -31,7 +28,13 @@ import javax.validation.ValidatorFactory
 import javax.validation.constraints.Size;
 import javax.validation.metadata.ConstraintDescriptor;
 import javax.validation.metadata.ElementDescriptor;
-import java.util.Set;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import org.apache.bval.jsr303.example.CompanyAddress;
+import org.apache.bval.jsr303.example.FrenchAddress;
+import org.apache.bval.jsr303.util.TestUtils;
 
 /**
  * Description: <br/>
@@ -41,15 +44,38 @@ public class ComposedConstraintsTest ext
 
     static {
         factory = Validation.buildDefaultValidatorFactory();
+        ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
+    }
+
+    /**
+     * Validator instance to test
+     */
+    protected Validator validator;
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        validator = createValidator();
+    }
+
+    /**
+     * Create the validator instance.
+     * 
+     * @return Validator
+     */
+    protected Validator createValidator() {
+        return factory.getValidator();
     }
 
     public void testMetaDataAPI_ComposedConstraints() {
-        Validator addressValidator = factory.getValidator();
         ElementDescriptor ed =
-              addressValidator.getConstraintsForClass(FrenchAddress.class)
+              validator.getConstraintsForClass(FrenchAddress.class)
                     .getConstraintsForProperty("zipCode");
         Assert.assertEquals(1, ed.getConstraintDescriptors().size());
-        for (ConstraintDescriptor cd : ed.getConstraintDescriptors()) {
+        for (ConstraintDescriptor<?> cd : ed.getConstraintDescriptors()) {
             Assert.assertTrue(cd.isReportAsSingleViolation());
             Assert.assertEquals(3, cd.getComposingConstraints().size());
             Assert.assertTrue("no composing constraints found!!",
@@ -58,51 +84,48 @@ public class ComposedConstraintsTest ext
         }
     }
 
-    public void processConstraintDescriptor(ConstraintDescriptor cd) {
+    public void processConstraintDescriptor(ConstraintDescriptor<?> cd) {
         //Size.class is understood by the tool
         if (cd.getAnnotation().annotationType().equals(Size.class)) {
-            Size m = (Size) cd.getAnnotation();
-//            System.out.println("size.max = " + m.max());  //read and use the metadata
+            Size m = (Size) cd.getAnnotation();//what for?
         }
-        for (Object composingCd : cd.getComposingConstraints()) {
-            processConstraintDescriptor((ConstraintDescriptor) composingCd);
+        for (ConstraintDescriptor<?> composingCd : cd.getComposingConstraints()) {
             //check composing constraints recursively
+            processConstraintDescriptor(composingCd);
         }
     }
 
     public void testValidateComposed() {
         FrenchAddress adr = new FrenchAddress();
-        Validator val = factory.getValidator();
-        Set<ConstraintViolation<FrenchAddress>> findings = val.validate(adr);
+        Set<ConstraintViolation<FrenchAddress>> findings = validator.validate(adr);
         Assert.assertEquals(1, findings.size()); // with @ReportAsSingleConstraintViolation
 
         ConstraintViolation<FrenchAddress> finding = findings.iterator().next();
         Assert.assertEquals("Wrong zipcode", finding.getMessage());
 
         adr.setZipCode("1234567");
-        findings = val.validate(adr);
+        findings = validator.validate(adr);
         Assert.assertEquals(0, findings.size());
 
         adr.setZipCode("1234567234567");
-        findings = val.validate(adr);
+        findings = validator.validate(adr);
         Assert.assertTrue(findings.size() > 0); // too long
     }
 
     public void testOverridesAttributeConstraintIndex() {
         CompanyAddress adr = new CompanyAddress("invalid-string");
-        Validator val = factory.getValidator();
-        Set<ConstraintViolation<CompanyAddress>> findings = val.validate(adr);
+        Set<ConstraintViolation<CompanyAddress>> findings = validator.validate(adr);
         assertEquals(2, findings.size()); // without @ReportAsSingleConstraintViolation
         assertNotNull(TestUtils.getViolationWithMessage(findings, "Not COMPANY"));
         assertNotNull(TestUtils.getViolationWithMessage(findings, "Not an email"));
 
         adr =  new CompanyAddress("JOHN_DO@WEB.DE");
-        findings = val.validate(adr);
+        findings = validator.validate(adr);
         assertEquals(1, findings.size());
         assertNotNull(TestUtils.getViolationWithMessage(findings, "Not COMPANY"));
 
         adr =  new CompanyAddress("JOHN_DO@COMPANY.DE");
-        findings = val.validate(adr);
+        findings = validator.validate(adr);
         Assert.assertTrue(findings.isEmpty());
     }
 

Modified: incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/ConstraintCompositionTest.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/ConstraintCompositionTest.java?rev=1166451&r1=1166450&r2=1166451&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/ConstraintCompositionTest.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/ConstraintCompositionTest.java Wed Sep  7 22:32:26 2011
@@ -19,14 +19,11 @@
 
 package org.apache.bval.jsr303;
 
-import junit.framework.Assert;
-import junit.framework.TestCase;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
 
-import javax.validation.*;
-import javax.validation.constraints.NotNull;
-import javax.validation.constraints.Pattern;
-import javax.validation.constraints.Size;
-import javax.validation.metadata.ConstraintDescriptor;
 import java.lang.annotation.Annotation;
 import java.lang.annotation.Documented;
 import java.lang.annotation.Retention;
@@ -34,8 +31,21 @@ import java.lang.annotation.Target;
 import java.util.Locale;
 import java.util.Set;
 
-import static java.lang.annotation.ElementType.*;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import javax.validation.Constraint;
+import javax.validation.ConstraintViolation;
+import javax.validation.OverridesAttribute;
+import javax.validation.Payload;
+import javax.validation.ReportAsSingleViolation;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+import javax.validation.metadata.ConstraintDescriptor;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
 
 /**
  * Checks that groups are correctly inherited from the root constraint to its
@@ -44,7 +54,6 @@ import static java.lang.annotation.Reten
  * @author Carlos Vara
  */
 public class ConstraintCompositionTest extends TestCase {
-
     static ValidatorFactory factory;
 
     static {
@@ -52,36 +61,53 @@ public class ConstraintCompositionTest e
         ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
     }
 
-    private Validator getValidator() {
+    /**
+     * Validator instance to test
+     */
+    protected Validator validator;
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        validator = createValidator();
+    }
+
+    /**
+     * Create the validator instance.
+     * 
+     * @return Validator
+     */
+    protected Validator createValidator() {
         return factory.getValidator();
     }
-    
+
     /**
      * Check correct group inheritance on constraint composition on a 1 level
      * hierarchy.
      */
     public void test1LevelInheritance() {
-        Validator validator = getValidator();
         Set<ConstraintViolation<Person>> violations = validator.validate(new Person());
-        
+
         Assert.assertEquals("Wrong number of violations detected", 1, violations.size());
         String msg = violations.iterator().next().getMessage();
         Assert.assertEquals("Incorrect violation message", "A person needs a non null name", msg);
-        
+
         violations = validator.validate(new Person(), Group1.class);
         Assert.assertEquals("Wrong number of violations detected", 0, violations.size());
     }
-    
+
     /**
      * Check correct group inheritance on constraint composition on a 2 level
      * hierarchy.
      */
     public void test2LevelInheritance() {
-        Validator validator = getValidator();
         Set<ConstraintViolation<Man>> violations = validator.validate(new Man());
-        
+
         Assert.assertEquals("Wrong number of violations detected", 0, violations.size());
-        
+
         violations = validator.validate(new Man(), Group1.class);
         Assert.assertEquals("Wrong number of violations detected", 1, violations.size());
         String msg = violations.iterator().next().getMessage();
@@ -93,10 +119,10 @@ public class ConstraintCompositionTest e
      * correctly set to the inherited ones.
      */
     public void testAnnotationGroupsAreInherited() {
-        Validator validator = getValidator();
-        
         // Check that the groups() value is right when querying the metadata
-        ConstraintDescriptor<?> manNameDesc = getValidator().getConstraintsForClass(Man.class).getConstraintsForProperty("name").getConstraintDescriptors().iterator().next();
+        ConstraintDescriptor<?> manNameDesc =
+            validator.getConstraintsForClass(Man.class).getConstraintsForProperty("name").getConstraintDescriptors()
+                .iterator().next();
         ConstraintDescriptor<?> personNameDesc = manNameDesc.getComposingConstraints().iterator().next();
         ConstraintDescriptor<?> notNullDesc = personNameDesc.getComposingConstraints().iterator().next();
         Assert.assertEquals("There should only be 1 group", 1, manNameDesc.getGroups().size());
@@ -105,23 +131,24 @@ public class ConstraintCompositionTest e
         Assert.assertTrue("Group1 should be present", personNameDesc.getGroups().contains(Group1.class));
         Assert.assertEquals("There should only be 1 group", 1, personNameDesc.getGroups().size());
         Assert.assertTrue("Group1 should be present", notNullDesc.getGroups().contains(Group1.class));
-        
-        // Check that the groups() value is right when accessing it from an error
+
+        // Check that the groups() value is right when accessing it from an
+        // error
         Set<ConstraintViolation<Man>> violations = validator.validate(new Man(), Group1.class);
         Set<Class<?>> notNullGroups = violations.iterator().next().getConstraintDescriptor().getGroups();
         Assert.assertEquals("There should only be 1 group", 1, notNullGroups.size());
         Assert.assertTrue("Group1 should be the only group", notNullGroups.contains(Group1.class));
     }
-    
+
     /**
      * Checks that the payload() value of the constraint annotations are
      * correctly set to the inherited ones.
      */
     public void testAnnotationPayloadsAreInherited() {
-        Validator validator = getValidator();
-        
         // Check that the payload() value is right when querying the metadata
-        ConstraintDescriptor<?> manNameDesc = getValidator().getConstraintsForClass(Man.class).getConstraintsForProperty("name").getConstraintDescriptors().iterator().next();
+        ConstraintDescriptor<?> manNameDesc =
+            validator.getConstraintsForClass(Man.class).getConstraintsForProperty("name").getConstraintDescriptors()
+                .iterator().next();
         ConstraintDescriptor<?> personNameDesc = manNameDesc.getComposingConstraints().iterator().next();
         ConstraintDescriptor<?> notNullDesc = personNameDesc.getComposingConstraints().iterator().next();
         Assert.assertEquals("There should only be 1 payload class", 1, manNameDesc.getPayload().size());
@@ -130,10 +157,12 @@ public class ConstraintCompositionTest e
         Assert.assertTrue("Payload1 should be present", personNameDesc.getPayload().contains(Payload1.class));
         Assert.assertEquals("There should only be 1 payload class", 1, personNameDesc.getPayload().size());
         Assert.assertTrue("Payload1 should be present", notNullDesc.getPayload().contains(Payload1.class));
-        
-        // Check that the payload() value is right when accessing it from an error
+
+        // Check that the payload() value is right when accessing it from an
+        // error
         Set<ConstraintViolation<Man>> violations = validator.validate(new Man(), Group1.class);
-        Set<Class<? extends Payload>> notNullPayload = violations.iterator().next().getConstraintDescriptor().getPayload();
+        Set<Class<? extends Payload>> notNullPayload =
+            violations.iterator().next().getConstraintDescriptor().getPayload();
         Assert.assertEquals("There should only be 1 payload class", 1, notNullPayload.size());
         Assert.assertTrue("Payload1 should be the only payload", notNullPayload.contains(Payload1.class));
     }
@@ -143,23 +172,21 @@ public class ConstraintCompositionTest e
      * applying works.
      */
     public void testIndexedOverridesAttributes() {
-        Validator validator = getValidator();
-        
         Person p = new Person();
         p.name = "valid";
-        
+
         // With a valid id, no errors expected
         p.id = "1234";
         Set<ConstraintViolation<Person>> constraintViolations = validator.validate(p);
         Assert.assertTrue("No violations should be reported on valid id", constraintViolations.isEmpty());
-        
+
         // With a short id, only 1 error expected
         p.id = "1";
         constraintViolations = validator.validate(p);
         Assert.assertEquals("Only 1 violation expected", 1, constraintViolations.size());
         ConstraintViolation<Person> violation = constraintViolations.iterator().next();
         Assert.assertEquals("Wrong violation", "Id is too short", violation.getMessage());
-        
+
         // With a long id, only 1 error expected
         p.id = "loooooong id";
         constraintViolations = validator.validate(p);
@@ -173,101 +200,107 @@ public class ConstraintCompositionTest e
      * {@link ReportAsSingleViolation}.
      */
     public void testReportAsAsingleViolation() {
-        Validator validator = getValidator();
-        
         Code c = new Code();
         c.code = "very invalid code";
         Set<ConstraintViolation<Code>> constraintViolations = validator.validate(c);
-        
+
         // Only 1 error expected
         Assert.assertEquals("Only 1 violation expected", 1, constraintViolations.size());
         ConstraintViolation<Code> violation = constraintViolations.iterator().next();
         Assert.assertEquals("Wrong violation message", "Invalid code", violation.getMessage());
-        Assert.assertEquals("Wrong violation type", ElevenDigitsCode.class, ((Annotation)violation.getConstraintDescriptor().getAnnotation()).annotationType());
-        
+        Assert.assertEquals("Wrong violation type", ElevenDigitsCode.class, ((Annotation) violation
+            .getConstraintDescriptor().getAnnotation()).annotationType());
     }
-    
+
     public static class Person {
         @PersonName
         String name;
-        
+
         @PersonId
         String id;
     }
-    
+
     public static class Man {
-        @ManName(groups={Group1.class},payload={Payload1.class})
+        @ManName(groups = { Group1.class }, payload = { Payload1.class })
         String name;
     }
-    
+
     public static class Code {
         @ElevenDigitsCode
         String code;
     }
-    
-    @NotNull(message="A person needs a non null name", groups={Group1.class}, payload={})
+
+    @NotNull(message = "A person needs a non null name", groups = { Group1.class }, payload = {})
     @Constraint(validatedBy = {})
     @Documented
-    @Target({ METHOD, FIELD, TYPE })
+    @Target( { METHOD, FIELD, TYPE })
     @Retention(RUNTIME)
     public static @interface PersonName {
         String message() default "Wrong person name";
-        Class<?>[] groups() default { };
+
+        Class<?>[] groups() default {};
+
         Class<? extends Payload>[] payload() default {};
     }
-    
-    @PersonName(groups={Group2.class},payload={Payload1.class,Payload2.class})
+
+    @PersonName(groups = { Group2.class }, payload = { Payload1.class, Payload2.class })
     @Constraint(validatedBy = {})
     @Documented
-    @Target({ METHOD, FIELD, TYPE })
+    @Target( { METHOD, FIELD, TYPE })
     @Retention(RUNTIME)
     public static @interface ManName {
         String message() default "Wrong man name";
-        Class<?>[] groups() default { };
+
+        Class<?>[] groups() default {};
+
         Class<? extends Payload>[] payload() default {};
     }
-    
-    
-    @Size.List({ @Size(min=3, max=3, message="Id is too short"), @Size(min=5,max=5, message="Id is too long") })
+
+    @Size.List( { @Size(min = 3, max = 3, message = "Id is too short"),
+        @Size(min = 5, max = 5, message = "Id is too long") })
     @Constraint(validatedBy = {})
     @Documented
-    @Target({ METHOD, FIELD, TYPE })
+    @Target( { METHOD, FIELD, TYPE })
     @Retention(RUNTIME)
     public static @interface PersonId {
         String message() default "Wrong person id";
-        Class<?>[] groups() default { };
+
+        Class<?>[] groups() default {};
+
         Class<? extends Payload>[] payload() default {};
-        
-        @OverridesAttribute(constraint=Size.class,constraintIndex=0,name="max")
+
+        @OverridesAttribute(constraint = Size.class, constraintIndex = 0, name = "max")
         int maxSize() default 1000;
-        
-        @OverridesAttribute(constraint=Size.class,constraintIndex=1,name="min")
+
+        @OverridesAttribute(constraint = Size.class, constraintIndex = 1, name = "min")
         int minSize() default 0;
     }
-    
-    @Size(min=11, max=11)
-    @Pattern(regexp="\\d*")
+
+    @Size(min = 11, max = 11)
+    @Pattern(regexp = "\\d*")
     @Constraint(validatedBy = {})
     @ReportAsSingleViolation
     @Documented
-    @Target({ METHOD, FIELD, TYPE })
+    @Target( { METHOD, FIELD, TYPE })
     @Retention(RUNTIME)
     public static @interface ElevenDigitsCode {
         String message() default "Invalid code";
-        Class<?>[] groups() default { };
+
+        Class<?>[] groups() default {};
+
         Class<? extends Payload>[] payload() default {};
     }
-    
+
     public static interface Group1 {
     }
-    
+
     public static interface Group2 {
     }
-    
+
     public static class Payload1 implements Payload {
     }
-    
+
     public static class Payload2 implements Payload {
     }
-    
+
 }



Mime
View raw message