001    /*
002      GRANITE DATA SERVICES
003      Copyright (C) 2011 GRANITE DATA SERVICES S.A.S.
004    
005      This file is part of Granite Data Services.
006    
007      Granite Data Services is free software; you can redistribute it and/or modify
008      it under the terms of the GNU Library General Public License as published by
009      the Free Software Foundation; either version 2 of the License, or (at your
010      option) any later version.
011    
012      Granite Data Services is distributed in the hope that it will be useful, but
013      WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014      FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015      for more details.
016    
017      You should have received a copy of the GNU Library General Public License
018      along with this library; if not, see <http://www.gnu.org/licenses/>.
019    */
020    
021    package org.granite.generator.as3.reflect;
022    
023    import java.lang.annotation.Annotation;
024    import java.lang.reflect.Array;
025    import java.lang.reflect.Method;
026    import java.lang.reflect.Modifier;
027    import java.net.URL;
028    import java.util.ArrayList;
029    import java.util.Arrays;
030    import java.util.HashMap;
031    import java.util.List;
032    import java.util.Map;
033    
034    /**
035     * Entity reflection for converting validation annotations to Flex.
036     * 
037     * @author William DRAI
038     * @author Franck WOLFF
039     */
040    public class JavaValidatableEntityBean extends JavaEntityBean {
041    
042            private Map<JavaProperty, List<JavaConstraint>> constraints = new HashMap<JavaProperty, List<JavaConstraint>>();
043    
044        public JavaValidatableEntityBean(JavaTypeFactory provider, Class<?> type, URL url, String metaAnnotationName, List<String> specialAnnotationNames, Map<String, String> nameConversions) {
045            super(provider, type, url);
046            
047                    Class<? extends Annotation> metaAnnotationClass = loadMetaAnnotationClass(type, metaAnnotationName);
048                    if (metaAnnotationClass == null)
049                            return;
050            
051            // Collect validation annotations
052            for (JavaProperty property : properties.values()) {
053                    List<JavaConstraint> javaConstraints = new ArrayList<JavaConstraint>();
054                    
055                    List<Annotation> constraintAnnotations = new ArrayList<Annotation>();
056                    for (Annotation annotation : property.getDeclaredAnnotations()) {
057                            Class<? extends Annotation> annotationClass = annotation.annotationType();
058                            
059                            if (annotationClass.isAnnotationPresent(metaAnnotationClass) || specialAnnotationNames.contains(annotationClass.getName()))
060                                    constraintAnnotations.add(annotation);
061                            else {
062    
063                                    // (Spec 2.2) "...the bean validation provider treats regular annotations
064                                    // (annotations not annotated by @Constraint) whose value element has a
065                                    // return type of an array of constraint annotations in a special way.
066                                    // Each element in the value array are processed by the Bean Validation
067                                    // implementation as regular constraint annotations."
068    
069                                    Method value = null;
070                                    try {
071                                            value = annotationClass.getMethod("value");
072                                    }
073                                    catch (NoSuchMethodException e) {
074                                    }
075                                    
076                                    if (value != null && value.getReturnType().isArray() &&
077                                            value.getReturnType().getComponentType().isAnnotation() &&
078                                            value.getReturnType().getComponentType().isAnnotationPresent(metaAnnotationClass)) {
079                                            
080                                            try {
081                                                    Annotation[] annotationList = (Annotation[])value.invoke(annotation);
082                                                    constraintAnnotations.addAll(Arrays.asList(annotationList));
083                                            }
084                                            catch (Exception e) {
085                                                    // should never happen...
086                                            }
087                                    }
088                            }
089                    }
090                    
091                    for (Annotation constraint : constraintAnnotations) {
092                            List<String[]> attributes = new ArrayList<String[]>();
093    
094                            for (Method attribute : constraint.annotationType().getDeclaredMethods()) {
095                                    if (Modifier.isPublic(attribute.getModifiers()) &&
096                                            !Modifier.isStatic(attribute.getModifiers()) &&
097                                            attribute.getParameterTypes().length == 0) {
098                                            
099                                            Object value = null;
100                                            try {
101                                                    value = attribute.invoke(constraint);
102                                            }
103                                            catch (Exception e) {
104                                                    continue;
105                                            }
106                                            
107                                            if (value != null && (!value.getClass().isArray() || Array.getLength(value) > 0))
108                                                    attributes.add(new String[]{attribute.getName(), escape(value)});
109                                    }
110                            }
111                            
112                            String constraintName = constraint.annotationType().getSimpleName();
113                            if (nameConversions.containsKey(constraintName))
114                                    constraintName = nameConversions.get(constraintName);
115                            javaConstraints.add(new JavaConstraint(constraintName, attributes));
116                    }
117                    
118                    if (!javaConstraints.isEmpty())
119                            constraints.put(property, javaConstraints);
120            }
121        }
122        
123        public Map<JavaProperty, List<JavaConstraint>> getConstraints() {
124            return constraints;
125        }
126        
127        @SuppressWarnings("unchecked")
128            private static Class<? extends Annotation> loadMetaAnnotationClass(Class<?> type, String metaAnnotationName) {
129                    try {
130                            return (Class<? extends Annotation>)type.getClassLoader().loadClass(metaAnnotationName);
131                    }
132                    catch (Exception e) {
133                            return null;
134                    }
135        }
136            
137            private static String escape(Object value) {
138                    
139                    if (value.getClass().isArray()) {
140                            StringBuilder sb = new StringBuilder();
141                            
142                            final int length = Array.getLength(value);
143                            boolean first = true;
144                            for (int i = 0; i < length; i++) {
145                                    Object item = Array.get(value, i);
146                                    if (item == null)
147                                            continue;
148    
149                                    if (first)
150                                            first = false;
151                                    else
152                                            sb.append(", ");
153                                    
154                                    sb.append(escape(item, true));
155                            }
156                            
157                            return sb.toString();
158                    }
159                    
160                    return escape(value, false);
161            }
162            
163            private static String escape(Object value, boolean array) {
164                    if (value instanceof Class<?>)
165                            return ((Class<?>)value).getName();
166                    
167                    if (value.getClass().isEnum())
168                            return ((Enum<?>)value).name();
169                    
170                    value = value.toString().replace("&", "&amp;").replace("\"", "&quot;").replace("\\", "\\\\");
171                    if (array)
172                            value = ((String)value).replace(",", ",,");
173                    return (String)value;
174            }
175    }