Added tests for yang.model.util
[yangtools.git] / code-generator / binding-java-api-generator / src / main / java / org / opendaylight / yangtools / sal / java / api / generator / BuilderTemplate.xtend
index b4940a97c385207bbaf515c408a6cc619b86996f..286b5f06b17017a6c01fe9ad678db612a65af16b 100644 (file)
@@ -7,7 +7,14 @@
  */
 package org.opendaylight.yangtools.sal.java.api.generator
 
-import java.util.Arrays;
+import com.google.common.collect.ImmutableSortedSet
+import com.google.common.collect.Range
+import java.util.ArrayList
+import java.util.Arrays
+import java.util.Collection
+import java.util.Collections
+import java.util.HashMap
+import java.util.HashSet
 import java.util.LinkedHashSet
 import java.util.List
 import java.util.Map
@@ -15,19 +22,14 @@ import java.util.Set
 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl
 import org.opendaylight.yangtools.binding.generator.util.Types
 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl
+import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType
 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty
 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject
 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
 import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature
 import org.opendaylight.yangtools.sal.binding.model.api.Type
 import org.opendaylight.yangtools.yang.binding.Augmentable
-import static org.opendaylight.yangtools.binding.generator.util.Types.*
-import java.util.HashMap
-import java.util.Collections
 import org.opendaylight.yangtools.yang.binding.DataObject
-import java.util.ArrayList
-import java.util.HashSet
-import java.util.Collection
 import org.opendaylight.yangtools.yang.binding.Identifiable
 
 /**
@@ -61,6 +63,8 @@ class BuilderTemplate extends BaseTemplate {
      */
     val Set<GeneratedProperty> properties
 
+    private static val METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<MethodSignature>();
+
     /**
      * Constructs new instance of this class.
      * @throws IllegalArgumentException if <code>genType</code> equals <code>null</code>
@@ -77,15 +81,17 @@ class BuilderTemplate extends BaseTemplate {
      * @returns set of method signature instances
      */
     def private Set<MethodSignature> createMethods() {
-        val Set<MethodSignature> methods = new LinkedHashSet
+        val Set<MethodSignature> methods = new LinkedHashSet();
         methods.addAll(type.methodDefinitions)
         collectImplementedMethods(methods, type.implements)
-        return methods
+        val Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods).build()
+
+        return sortedMethods
     }
 
     /**
      * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code> 
-     * and recursivelly their implemented interfaces.
+     * and recursively their implemented interfaces.
      * 
      * @param methods set of method signatures
      * @param implementedIfcs list of implemented interfaces
@@ -137,12 +143,12 @@ class BuilderTemplate extends BaseTemplate {
         return if (lastDotIndex == -1) "" else fullyQualifiedName.substring(0, lastDotIndex)
     }
 
-       /**
-        * Returns the name of tye type from <code>fullyQualifiedName</code>
-        * 
-        * @param fullyQualifiedName string with fully qualified type name (package + type)
-        * @return string with the name of the type
-        */
+    /**
+     * Returns the name of tye type from <code>fullyQualifiedName</code>
+     *
+     * @param fullyQualifiedName string with fully qualified type name (package + type)
+     * @return string with the name of the type
+     */
     def private String getName(String fullyQualifiedName) {
         val lastDotIndex = fullyQualifiedName.lastIndexOf(Constants.DOT)
         return if (lastDotIndex == -1) fullyQualifiedName else fullyQualifiedName.substring(lastDotIndex + 1)
@@ -154,7 +160,7 @@ class BuilderTemplate extends BaseTemplate {
      * @param set of method signature instances which should be transformed to list of properties 
      * @return set of generated property instances which represents the getter <code>methods</code>
      */
-    def private propertiesFromMethods(Set<MethodSignature> methods) {
+    def private propertiesFromMethods(Collection<MethodSignature> methods) {
         if (methods == null || methods.isEmpty()) {
             return Collections.emptySet
         }
@@ -174,10 +180,10 @@ class BuilderTemplate extends BaseTemplate {
      * @param method method signature from which is the method name and return type obtained
      * @return generated property instance for the getter <code>method</code>
      * @throws IllegalArgumentException<ul>
-     *         <li>if the <code>method</code> equals <code>null</code></li>
-     *         <li>if the name of the <code>method</code> equals <code>null</code></li>
-     *         <li>if the name of the <code>method</code> is empty</li>
-     *         <li>if the return type of the <code>method</code> equals <code>null</code></li>
+     *  <li>if the <code>method</code> equals <code>null</code></li>
+     *  <li>if the name of the <code>method</code> equals <code>null</code></li>
+     *  <li>if the name of the <code>method</code> is empty</li>
+     *  <li>if the return type of the <code>method</code> equals <code>null</code></li>
      * </ul>
      */
     def private GeneratedProperty propertyFromGetter(MethodSignature method) {
@@ -185,7 +191,7 @@ class BuilderTemplate extends BaseTemplate {
             throw new IllegalArgumentException("Method, method name, method return type reference cannot be NULL or empty!")
         }
         var prefix = "get";
-        if(BOOLEAN.equals(method.returnType)) {
+        if(Types.BOOLEAN.equals(method.returnType)) {
             prefix = "is";
         } 
         if (method.name.startsWith(prefix)) {
@@ -202,13 +208,17 @@ class BuilderTemplate extends BaseTemplate {
      * @return string with JAVA source code
      */
     override body() '''
-
+        «wrapToDocumentation(formatDataForJavaDoc(type))»
         public class «type.name»«BUILDER» {
 
             «generateFields(false)»
 
+            «generateAugmentField(true)»
+
             «generateConstructorsFromIfcs(type)»
 
+            «generateCopyConstructor(false)»
+
             «generateMethodFieldsFrom(type)»
 
             «generateGetters(false)»
@@ -225,7 +235,9 @@ class BuilderTemplate extends BaseTemplate {
 
                 «generateFields(true)»
 
-                «generateConstructor»
+                «generateAugmentField(false)»
+
+                «generateCopyConstructor(true)»
 
                 «generateGetters(true)»
 
@@ -256,7 +268,7 @@ class BuilderTemplate extends BaseTemplate {
     /**
      * Generate constructor with argument of given type.
      */
-    def private generateConstructorFromIfc(Type impl) '''
+    def private Object generateConstructorFromIfc(Type impl) '''
         «IF (impl instanceof GeneratedType)»
             «val implType = impl as GeneratedType»
 
@@ -271,7 +283,7 @@ class BuilderTemplate extends BaseTemplate {
         «ENDIF»
     '''
 
-    def private printConstructorPropertySetter(Type implementedIfc) '''
+    def private Object printConstructorPropertySetter(Type implementedIfc) '''
         «IF (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject))»
             «val ifc = implementedIfc as GeneratedType»
             «FOR getter : ifc.methodDefinitions»
@@ -310,7 +322,7 @@ class BuilderTemplate extends BaseTemplate {
 
     def private generateMethodFieldsFromComment(GeneratedType type) '''
         /**
-         Set fields from given grouping argument. Valid argument is instance of one of following types:
+         *Set fields from given grouping argument. Valid argument is instance of one of following types:
          * <ul>
          «FOR impl : type.getAllIfcs»
          * <li>«impl.fullyQualifiedName»</li>
@@ -386,53 +398,117 @@ class BuilderTemplate extends BaseTemplate {
         return names
     }
 
-       /**
-        * Template method which generates class attributes.
-        * 
-        * @param boolean value which specify whether field is|isn't final
-        * @return string with class attributes and their types
-        */
+    /**
+     * Template method which generates class attributes.
+     *
+     * @param boolean value which specify whether field is|isn't final
+     * @return string with class attributes and their types
+     */
     def private generateFields(boolean _final) '''
-        «IF !properties.empty»
+        «IF properties !== null»
             «FOR f : properties»
                 private«IF _final» final«ENDIF» «f.returnType.importedName» «f.fieldName»;
+                «val restrictions = f.returnType.restrictions»
+                «IF !_final && restrictions != null»
+                    «IF !(restrictions.lengthConstraints.empty)»
+                        private static «List.importedName»<«Range.importedName»<«f.returnType.importedNumber»>> «f.fieldName»_length;
+                    «ENDIF»
+                    «IF !(restrictions.rangeConstraints.empty)»
+                        private static «List.importedName»<«Range.importedName»<«f.returnType.importedNumber»>> «f.fieldName»_range;
+                    «ENDIF»
+                «ENDIF»
             «ENDFOR»
         «ENDIF»
+    '''
+
+    def private generateAugmentField(boolean init) '''
         «IF augmentField != null»
-            private «Map.importedName»<Class<? extends «augmentField.returnType.importedName»>, «augmentField.returnType.importedName»> «augmentField.name» = new «HashMap.importedName»<>();
+            private «Map.importedName»<«Class.importedName»<? extends «augmentField.returnType.importedName»>, «augmentField.returnType.importedName»> «augmentField.name» = new «HashMap.importedName»<>();
         «ENDIF»
     '''
 
-       /**
-        * Template method which generates setter methods
-        * 
-        * @return string with the setter methods 
-        */
+    /**
+     * Template method which generates setter methods
+     *
+     * @return string with the setter methods
+     */
     def private generateSetters() '''
         «FOR field : properties SEPARATOR '\n'»
+            «val length = field.fieldName + "_length"»
+            «val range = field.fieldName + "_range"»
             public «type.name»«BUILDER» set«field.name.toFirstUpper»(«field.returnType.importedName» value) {
-                «generateRestrictions(field, "value")»
-
+                «generateRestrictions(field, "value", length, range)»
                 this.«field.fieldName» = value;
                 return this;
             }
+            «generateLengthMethod(length, field.returnType, type.name+BUILDER, length)»
+            «generateRangeMethod(range, field.returnType.restrictions, field.returnType, type.name+BUILDER, range)»
         «ENDFOR»
         «IF augmentField != null»
 
-            public «type.name»«BUILDER» add«augmentField.name.toFirstUpper»(Class<? extends «augmentField.returnType.importedName»> augmentationType, «augmentField.returnType.importedName» augmentation) {
+            public «type.name»«BUILDER» add«augmentField.name.toFirstUpper»(«Class.importedName»<? extends «augmentField.returnType.importedName»> augmentationType, «augmentField.returnType.importedName» augmentation) {
                 this.«augmentField.name».put(augmentationType, augmentation);
                 return this;
             }
         «ENDIF»
     '''
 
-    /**
-     * Template method which generate constructor for IMPL class.
-     * 
-     * @return string with IMPL class constructor
-     */
-    def private generateConstructor() '''
-        private «type.name»«IMPL»(«type.name»«BUILDER» builder) {
+    def generateRestrictions(GeneratedProperty field, String paramName, String lengthGetter, String rangeGetter) '''
+        «val Type type = field.returnType»
+        «IF type instanceof ConcreteType»
+            «createRestrictions(type, paramName, type.name.contains("["), lengthGetter, rangeGetter)»
+        «ELSEIF type instanceof GeneratedTransferObject»
+            «createRestrictions(type, paramName, isArrayType(type as GeneratedTransferObject), lengthGetter, rangeGetter)»
+        «ENDIF»
+    '''
+
+    def private createRestrictions(Type type, String paramName, boolean isArray, String lengthGetter, String rangeGetter) '''
+        «val restrictions = type.getRestrictions»
+        «IF restrictions !== null»
+            «val boolean isNestedType = !(type instanceof ConcreteType)»
+            «IF !restrictions.lengthConstraints.empty»
+                «generateLengthRestriction(type, paramName, lengthGetter, isNestedType, isArray)»
+            «ENDIF»
+            «IF !restrictions.rangeConstraints.empty»
+                «generateRangeRestriction(type, paramName, rangeGetter, isNestedType)»
+            «ENDIF»
+        «ENDIF»
+    '''
+
+    def private generateLengthRestriction(Type type, String paramName, String getterName, boolean isNestedType, boolean isArray) '''
+        «val restrictions = type.getRestrictions»
+        if («paramName» != null) {
+            «val clazz = restrictions.lengthConstraints.iterator.next.min.class»
+            «printLengthConstraint(type, clazz, paramName, isNestedType, isArray)»
+            boolean isValidLength = false;
+            for («Range.importedName»<«clazz.importedNumber»> r : «getterName»()) {
+                if (r.contains(_constraint)) {
+                    isValidLength = true;
+                }
+            }
+            if (!isValidLength) {
+                throw new IllegalArgumentException(String.format("Invalid length: %s, expected: %s.", «paramName», «getterName»));
+            }
+        }
+    '''
+
+    def private generateRangeRestriction(Type type, String paramName, String getterName, boolean isNestedType) '''
+        if («paramName» != null) {
+            «printRangeConstraint(type, paramName, isNestedType)»
+            boolean isValidRange = false;
+            for («Range.importedName»<«type.importedNumber»> r : «getterName»()) {
+                if (r.contains(_constraint)) {
+                    isValidRange = true;
+                }
+            }
+            if (!isValidRange) {
+                throw new IllegalArgumentException(String.format("Invalid range: %s, expected: %s.", «paramName», «getterName»));
+            }
+        }
+    '''
+
+    def private CharSequence generateCopyConstructor(boolean impl) '''
+        «IF impl»private«ELSE»public«ENDIF» «type.name»«IF impl»«IMPL»«ELSE»«BUILDER»«ENDIF»(«type.name»«IF impl»«BUILDER»«ENDIF» base) {
             «val allProps = new ArrayList(properties)»
             «val isList = implementsIfc(type, Types.parameterizedTypeFor(Types.typeForClass(Identifiable), type))»
             «val keyType = type.getKey»
@@ -447,27 +523,45 @@ class BuilderTemplate extends BaseTemplate {
                     «removeProperty(allProps, field.name)»
                 «ENDFOR»
                 «removeProperty(allProps, "key")»
-                if (builder.getKey() == null) {
+                if (base.getKey() == null) {
                     this._key = new «keyType.importedName»(
                         «FOR keyProp : keyProps SEPARATOR ", "»
-                            builder.«keyProp.getterMethodName»()
+                            base.«keyProp.getterMethodName»()
                         «ENDFOR»
                     );
                     «FOR field : keyProps»
-                        this.«field.fieldName» = builder.«field.getterMethodName»();
+                        this.«field.fieldName» = base.«field.getterMethodName»();
                     «ENDFOR»
                 } else {
-                    this._key = builder.getKey();
+                    this._key = base.getKey();
                     «FOR field : keyProps»
                            this.«field.fieldName» = _key.«field.getterMethodName»();
                     «ENDFOR»
                 }
             «ENDIF»
             «FOR field : allProps»
-                this.«field.fieldName» = builder.«field.getterMethodName»();
+                this.«field.fieldName» = base.«field.getterMethodName»();
             «ENDFOR»
             «IF augmentField != null»
-                this.«augmentField.name».putAll(builder.«augmentField.name»);
+                «IF !impl»if (base instanceof «type.name»«IMPL») {«ENDIF»
+                    «IF !impl»«type.name»«IMPL» _impl = («type.name»«IMPL») base;«ENDIF»
+                    «val prop = if (impl) "base" else "_impl"»
+                    «IF impl»
+                        switch («prop».«augmentField.name».size()) {
+                        case 0:
+                            this.«augmentField.name» = «Collections.importedName».emptyMap();
+                            break;
+                            case 1:
+                                final «Map.importedName».Entry<«Class.importedName»<? extends «augmentField.returnType.importedName»>, «augmentField.returnType.importedName»> e = «prop».«augmentField.name».entrySet().iterator().next();
+                                this.«augmentField.name» = «Collections.importedName».<«Class.importedName»<? extends «augmentField.returnType.importedName»>, «augmentField.returnType.importedName»>singletonMap(e.getKey(), e.getValue());       
+                            break;
+                        default :
+                            this.«augmentField.name» = new «HashMap.importedName»<>(«prop».«augmentField.name»);
+                        }
+                    «ELSE»
+                        this.«augmentField.name» = new «HashMap.importedName»<>(«prop».«augmentField.name»);
+                    «ENDIF»
+                «IF !impl»}«ENDIF»
             «ENDIF»
         }
     '''
@@ -518,7 +612,7 @@ class BuilderTemplate extends BaseTemplate {
 
             @SuppressWarnings("unchecked")
             «IF addOverride»@Override«ENDIF»
-            public <E extends «augmentField.returnType.importedName»> E get«augmentField.name.toFirstUpper»(Class<E> augmentationType) {
+            public <E extends «augmentField.returnType.importedName»> E get«augmentField.name.toFirstUpper»(«Class.importedName»<E> augmentationType) {
                 if (augmentationType == null) {
                     throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!");
                 }
@@ -561,39 +655,54 @@ class BuilderTemplate extends BaseTemplate {
     def protected generateEquals() '''
         «IF !properties.empty || augmentField != null»
             @Override
-            public boolean equals(java.lang.Object obj) {
+            public boolean equals(«Object.importedName» obj) {
                 if (this == obj) {
                     return true;
                 }
-                if (obj == null) {
+                if (!(obj instanceof «DataObject.importedName»)) {
                     return false;
                 }
-                if (getClass() != obj.getClass()) {
+                if (!«type.importedName».class.equals(((«DataObject.importedName»)obj).getImplementedInterface())) {
                     return false;
                 }
-                «type.name»«IMPL» other = («type.name»«IMPL») obj;
+                «type.importedName» other = («type.importedName»)obj;
                 «FOR property : properties»
                     «val fieldName = property.fieldName»
                     if («fieldName» == null) {
-                        if (other.«fieldName» != null) {
+                        if (other.«property.getterMethodName»() != null) {
                             return false;
                         }
                     «IF property.returnType.name.contains("[")»
-                    } else if(!«Arrays.importedName».equals(«fieldName», other.«fieldName»)) {
+                    } else if(!«Arrays.importedName».equals(«fieldName», other.«property.getterMethodName»())) {
                     «ELSE»
-                    } else if(!«fieldName».equals(other.«fieldName»)) {
+                    } else if(!«fieldName».equals(other.«property.getterMethodName»())) {
                     «ENDIF»
                         return false;
                     }
                 «ENDFOR»
                 «IF augmentField != null»
-                    «val fieldName = augmentField.name»
-                    if («fieldName» == null) {
-                        if (other.«fieldName» != null) {
+                    if (getClass() == obj.getClass()) {
+                        // Simple case: we are comparing against self
+                        «type.name»«IMPL» otherImpl = («type.name»«IMPL») obj;
+                        «val fieldName = augmentField.name»
+                        if («fieldName» == null) {
+                            if (otherImpl.«fieldName» != null) {
+                                return false;
+                            }
+                        } else if(!«fieldName».equals(otherImpl.«fieldName»)) {
+                            return false;
+                        }
+                    } else {
+                        // Hard case: compare our augments with presence there...
+                        for («Map.importedName».Entry<«Class.importedName»<? extends «augmentField.returnType.importedName»>, «augmentField.returnType.importedName»> e : «augmentField.name».entrySet()) {
+                            if (!e.getValue().equals(other.getAugmentation(e.getKey()))) {
+                                return false;
+                            }
+                        }
+                        // .. and give the other one the chance to do the same
+                        if (!obj.equals(this)) {
                             return false;
                         }
-                    } else if(!«fieldName».equals(other.«fieldName»)) {
-                        return false;
                     }
                 «ENDIF»
                 return true;
@@ -602,10 +711,10 @@ class BuilderTemplate extends BaseTemplate {
     '''
 
     def override generateToString(Collection<GeneratedProperty> properties) '''
-        «IF !properties.empty»
+        «IF !(properties === null)»
             @Override
-            public String toString() {
-                StringBuilder builder = new StringBuilder("«type.name» [");
+            public «String.importedName» toString() {
+                «StringBuilder.importedName» builder = new «StringBuilder.importedName» ("«type.name» [");
                 boolean first = true;
 
                 «FOR property : properties»
@@ -646,6 +755,23 @@ class BuilderTemplate extends BaseTemplate {
         return «type.importedName».class;
     }
     '''
+    
+    private def createDescription(GeneratedType type) {
+        return '''
+        Class that builds {@link «type.importedName»} instances.
+        
+        @see «type.importedName»
+    '''
+    }
+    
+    override def protected String formatDataForJavaDoc(GeneratedType type) {
+        val typeDescription = createDescription(type)
 
+        return '''
+            «IF !typeDescription.nullOrEmpty»
+            «typeDescription»
+            «ENDIF»
+        '''.toString
+    }
 }