Merge "Bug 2818: Updated implementation of parser."
authorRobert Varga <nite@hq.sk>
Thu, 12 Mar 2015 21:20:01 +0000 (21:20 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Thu, 12 Mar 2015 21:20:02 +0000 (21:20 +0000)
13 files changed:
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTree.java [new file with mode: 0644]
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeFactory.java [new file with mode: 0644]
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeNode.java [new file with mode: 0644]
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCachingCodec.java [new file with mode: 0644]
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCodec.java [new file with mode: 0644]
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/BaseTemplate.xtend
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/BuilderTemplate.xtend
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/EnumTemplate.xtend
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/InterfaceTemplate.xtend
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/UnionTemplate.xtend
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/YangModuleInfoTemplate.xtend
code-generator/binding-java-api-generator/src/test/java/org/opendaylight/yangtools/sal/java/api/generator/test/UnionTypedefUnusedImportTest.java [new file with mode: 0644]
code-generator/binding-java-api-generator/src/test/resources/compilation/union-typedef/union-typedef-test.yang [new file with mode: 0644]

diff --git a/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTree.java b/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTree.java
new file mode 100644 (file)
index 0000000..ea28281
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+
+/**
+ *
+ * Navigable tree representing hierarchy of Binding to Normalized Node codecs
+ *
+ * This navigable tree is associated to conrete set of YANG models, represented
+ * by SchemaContext and provides access to subtree specific serialization
+ * context.
+ *
+ * TODO: Add more detailed documentation
+ **/
+public interface BindingCodecTree {
+
+      @Nullable <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(InstanceIdentifier<T> path);
+
+      @Nullable BindingCodecTreeNode<?> getSubtreeCodec(YangInstanceIdentifier path);
+
+      @Nullable BindingCodecTreeNode<?> getSubtreeCodec(SchemaPath path);
+
+}
\ No newline at end of file
diff --git a/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeFactory.java b/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeFactory.java
new file mode 100644 (file)
index 0000000..4757038
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public interface BindingCodecTreeFactory {
+
+    /**
+     *
+     * Creates Binding Codec Tree for specified Binding runtime context.
+     *
+     * @param context
+     *            Binding Runtime Context for which Binding codecs should be
+     *            instantiated.
+     * @return Binding Codec Tree for specified Binding runtime context.
+     */
+    BindingCodecTree create(BindingRuntimeContext context);
+
+    /**
+    *
+    * Creates Binding Codec Tree for specified Binding runtime context.
+    *
+    * @param context
+    *            Binding Runtime Context for which Binding codecs should be
+    *            instantiated.
+    * @param bindingClasses
+    * @return Binding Codec Tree for specified Binding runtime context.
+    */
+    @Beta
+   BindingCodecTree create(SchemaContext context, Class<?>... bindingClasses);
+
+}
diff --git a/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeNode.java b/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeNode.java
new file mode 100644 (file)
index 0000000..5e7b054
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableCollection;
+import java.util.List;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
+
+/**
+ * Subtree codec specific to model subtree between Java Binding and
+ * NormalizedNode.
+ *
+ */
+@Beta
+public interface BindingCodecTreeNode<T extends DataObject> extends BindingNormalizedNodeCodec<T> {
+
+    /**
+     *
+     * Returns binding class of interface which represents API of current
+     * schema node.
+     *
+     * The result is same as invoking {@link DataObject#getImplementedInterface()}
+     * on instance of data.
+     *
+     * @return interface which defines API of binding representation of data.
+     */
+    @Nonnull
+    Class<T> getBindingClass();
+
+    /**
+     *
+     * Returns child context as if it was walked by
+     * {@link BindingStreamEventWriter}. This means that to enter case, one must
+     * issue getChild(ChoiceClass).getChild(CaseClass).
+     *
+     * @param childClass
+     * @return Context of child
+     * @throws IllegalArgumentException
+     *             If supplied child class is not valid in specified context.
+     */
+    @Nonnull
+    <E extends DataObject> BindingCodecTreeNode<E> streamChild(@Nonnull Class<E> childClass);
+
+    /**
+     *
+     * Returns child context as if it was walked by
+     * {@link BindingStreamEventWriter}. This means that to enter case, one must
+     * issue getChild(ChoiceClass).getChild(CaseClass).
+     *
+     * This method differs from {@link #streamChild(Class)}, that is less
+     * stricter for interfaces representing augmentation and cases, that
+     * may return {@link BindingCodecTreeNode} even if augmentation interface
+     * containing same data was supplied and does not represent augmentation
+     * of this node.
+     *
+     * @param childClass
+     * @return Context of child or Optional absent is supplied class is not
+     *         applicable in context.
+     */
+    <E extends DataObject> Optional<? extends BindingCodecTreeNode<E>> possibleStreamChild(@Nonnull Class<E> childClass);
+
+    /**
+     * Returns nested node context using supplied YANG Instance Identifier
+     *
+     * @param child
+     *            Yang Instance Identifier Argument
+     * @return Context of child
+     * @throws IllegalArgumentException
+     *             If supplied argument does not represent valid child.
+     */
+    @Nonnull
+    BindingCodecTreeNode<?> yangPathArgumentChild(@Nonnull YangInstanceIdentifier.PathArgument child);
+
+    /**
+     * Returns nested node context using supplied Binding Instance Identifier
+     * and adds YANG instance identifiers to supplied list.
+     *
+     * @param arg
+     *            Binding Instance Identifier Argument
+     * @param builder
+     *            Mutable instance of list, which is appended by YangInstanceIdentifiers
+     *            as tree is walked. Use null if such side-product is not needed.
+     * @return Context of child
+     * @throws IllegalArgumentException
+     *             If supplied argument does not represent valid child.
+     */
+    @Nonnull
+    BindingCodecTreeNode<?> bindingPathArgumentChild(@Nonnull InstanceIdentifier.PathArgument arg,
+            @Nullable List<YangInstanceIdentifier.PathArgument> builder);
+
+    /**
+     *
+     * Returns codec which uses caches serialization / deserialization results
+     *
+     * Caching may introduce performance penalty to serialization / deserialization
+     * but may decrease use of heap for repetitive objects.
+     *
+     *
+     * @param cacheSpecifier Set of objects, for which cache may be in place
+     * @return Codec whihc uses cache for serialization / deserialization.
+     */
+    @Nonnull
+    BindingNormalizedNodeCachingCodec<T> createCachingCodec(@Nonnull
+            ImmutableCollection<Class<? extends DataObject>> cacheSpecifier);
+
+    @Beta
+    void writeAsNormalizedNode(T data, NormalizedNodeStreamWriter writer);
+}
diff --git a/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCachingCodec.java b/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCachingCodec.java
new file mode 100644 (file)
index 0000000..2e990d9
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+
+/**
+ *
+ * Caching variant of Binding to Normalized Node codec.
+ *
+ * Caching may introduce performance penalty to serialization / deserialization
+ * but may decrease use of heap for repetitive objects.
+ *
+ * @param <T> Binding representtion of data
+ *
+ */
+@Beta
+public interface BindingNormalizedNodeCachingCodec<T extends DataObject> extends BindingNormalizedNodeCodec<T>, AutoCloseable {
+
+    /**
+     *
+     * Invoking close will invalidate this codec and any of its child
+     * codecs and will invalidate cache.
+     *
+     * Any subsequent calls to this codec will fail with {@link IllegalStateException}
+     * thrown.
+     *
+     */
+    @Override
+    public void close();
+}
diff --git a/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCodec.java b/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCodec.java
new file mode 100644 (file)
index 0000000..ca48ea8
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import javax.annotation.Nonnull;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ *
+ * Codec providing serialization and deserializiation between Binding
+ * and NormalizedNode representation of data.
+ *
+ *
+ * @param <T> Binding representation of data
+ */
+@Beta
+public interface BindingNormalizedNodeCodec<T extends DataObject> {
+
+    /**
+     * Converts from Normalized Node to Binding representation of data.
+     *
+     * @param data Normalized Node representation of data
+     * @return Binding representation of data
+     */
+    @Nonnull T deserialize(@Nonnull NormalizedNode<?,?> data);
+
+    /**
+     * Converts from  Binding to Normalized Node representation of data.
+     *
+     * @param data Binding representation of data
+     * @return Normalized Node representation of data
+     */
+    @Nonnull NormalizedNode<?,?> serialize(@Nonnull T data);
+
+}
index a9788cdef433ec811ee5185dbdc86fc5f364b6bd..d98b52fc471bd2b6ac4f152cae09be14d1dc6a20 100644 (file)
@@ -63,10 +63,10 @@ abstract class BaseTemplate {
         '''.toString
     }
 
-    protected def imports() ''' 
+    protected def imports() '''
         «IF !importMap.empty»
             «FOR entry : importMap.entrySet»
-                «IF entry.value != fullyQualifiedName»
+                «IF !hasSamePackage(entry.value)»
                     import «entry.value».«entry.key»;
                 «ENDIF»
             «ENDFOR»
@@ -74,6 +74,17 @@ abstract class BaseTemplate {
 
     '''
 
+    /**
+     * Checks if packages of generated type and imported type is the same
+     *
+     * @param importedTypePackageNam
+     * the package name of imported type
+     * @return true if the packages are the same false otherwise
+     */
+    final private def boolean hasSamePackage(String importedTypePackageName) {
+        return type.packageName.equals(importedTypePackageName);
+    }
+
     protected abstract def CharSequence body();
 
     // Helper patterns
@@ -93,10 +104,10 @@ abstract class BaseTemplate {
 
     /**
      * Template method which generates the getter method for <code>field</code>
-     * 
-     * @param field 
+     *
+     * @param field
      * generated property with data about field which is generated as the getter method
-     * @return string with the getter method source code in JAVA format 
+     * @return string with the getter method source code in JAVA format
      */
     final protected def getterMethod(GeneratedProperty field) {
         '''
@@ -117,10 +128,10 @@ abstract class BaseTemplate {
 
     /**
      * Template method which generates the setter method for <code>field</code>
-     * 
-     * @param field 
+     *
+     * @param field
      * generated property with data about field which is generated as the setter method
-     * @return string with the setter method source code in JAVA format 
+     * @return string with the setter method source code in JAVA format
      */
     final protected def setterMethod(GeneratedProperty field) '''
         «val returnType = field.returnType.importedName»
@@ -141,7 +152,7 @@ abstract class BaseTemplate {
 
     /**
      * Template method which generates method parameters with their types from <code>parameters</code>.
-     * 
+     *
      * @param parameters
      * group of generated property instances which are transformed to the method parameters
      * @return string with the list of the method parameters with their types in JAVA format
@@ -151,17 +162,17 @@ abstract class BaseTemplate {
 
     /**
      * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
-     * 
-     * @param parameters 
+     *
+     * @param parameters
      * group of generated property instances which are transformed to the sequence of parameter names
-     * @return string with the list of the parameter names of the <code>parameters</code> 
+     * @return string with the list of the parameter names of the <code>parameters</code>
      */
     def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
         fieldName»«ENDFOR»«ENDIF»'''
 
     /**
      * Template method which generates JAVA comments.
-     * 
+     *
      * @param comment string with the comment for whole JAVA class
      * @return string with comment in JAVA format
      */
@@ -185,8 +196,11 @@ abstract class BaseTemplate {
         sb.append(NEW_LINE)
 
         for (String t : NL_SPLITTER.split(text)) {
-            sb.append(" * ")
-            sb.append(t)
+            sb.append(" *")
+            if (!t.isEmpty()) {
+                sb.append(' ');
+                sb.append(t)
+            }
             sb.append(NEW_LINE)
         }
         sb.append(" */")
@@ -439,7 +453,7 @@ abstract class BaseTemplate {
 
     /**
      * Template method which generates method parameters with their types from <code>parameters</code>.
-     * 
+     *
      * @param parameters
      * list of parameter instances which are transformed to the method parameters
      * @return string with the list of the method parameters with their types in JAVA format
index a15d014fe937267e6549989bcccb7855b9b9f5e8..15e93756576ab94104cd4d33549e8b486937e6f9 100644 (file)
@@ -34,7 +34,7 @@ import org.opendaylight.yangtools.yang.binding.Identifiable
 import org.opendaylight.yangtools.concepts.Builder
 
 /**
- * Template for generating JAVA builder classes. 
+ * Template for generating JAVA builder classes.
  */
 
 class BuilderTemplate extends BaseTemplate {
@@ -84,7 +84,7 @@ class BuilderTemplate extends BaseTemplate {
     /**
      * Returns set of method signature instances which contains all the methods of the <code>genType</code>
      * and all the methods of the implemented interfaces.
-     * 
+     *
      * @returns set of method signature instances
      */
     def private Set<MethodSignature> createMethods() {
@@ -97,9 +97,9 @@ class BuilderTemplate extends BaseTemplate {
     }
 
     /**
-     * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code> 
+     * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
      * and recursively their implemented interfaces.
-     * 
+     *
      * @param methods set of method signatures
      * @param implementedIfcs list of implemented interfaces
      */
@@ -132,7 +132,7 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Returns the first element of the list <code>elements</code>.
-     * 
+     *
      * @param list of elements
      */
     def private <E> first(List<E> elements) {
@@ -141,7 +141,7 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Returns the name of the package from <code>fullyQualifiedName</code>.
-     * 
+     *
      * @param fullyQualifiedName string with fully qualified type name (package + type)
      * @return string with the package name
      */
@@ -163,8 +163,8 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Creates set of generated property instances from getter <code>methods</code>.
-     * 
-     * @param set of method signature instances which should be transformed to list of properties 
+     *
+     * @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(Collection<MethodSignature> methods) {
@@ -183,7 +183,7 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Creates generated property instance from the getter <code>method</code> name and return type.
-     * 
+     *
      * @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>
@@ -200,7 +200,7 @@ class BuilderTemplate extends BaseTemplate {
         var prefix = "get";
         if(Types.BOOLEAN.equals(method.returnType)) {
             prefix = "is";
-        } 
+        }
         if (method.name.startsWith(prefix)) {
             val fieldName = method.getName().substring(prefix.length()).toFirstLower
             val tmpGenTO = new GeneratedTOBuilderImpl("foo", "foo")
@@ -210,8 +210,8 @@ class BuilderTemplate extends BaseTemplate {
     }
 
     /**
-     * Template method which generates JAVA class body for builder class and for IMPL class. 
-     * 
+     * Template method which generates JAVA class body for builder class and for IMPL class.
+     *
      * @return string with JAVA source code
      */
     override body() '''
@@ -251,7 +251,7 @@ class BuilderTemplate extends BaseTemplate {
                 «generateHashCode()»
 
                 «generateEquals()»
-                
+
                 «generateToString(properties)»
             }
 
@@ -263,7 +263,7 @@ class BuilderTemplate extends BaseTemplate {
      */
     def private generateConstructorsFromIfcs(Type type) '''
         public «type.name»«BUILDER»() {
-        } 
+        }
         «IF (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject))»
             «val ifc = type as GeneratedType»
             «FOR impl : ifc.implements»
@@ -378,7 +378,7 @@ class BuilderTemplate extends BaseTemplate {
                 baseIfcs.add(ifc)
             }
         }
-        return baseIfcs 
+        return baseIfcs
     }
 
     private def Set<Type> getAllIfcs(Type type) {
@@ -392,7 +392,7 @@ class BuilderTemplate extends BaseTemplate {
                 baseIfcs.addAll(impl.getAllIfcs)
             }
         }
-        return baseIfcs 
+        return baseIfcs
     }
 
     private def List<String> toListOfNames(Collection<Type> types) {
@@ -566,7 +566,7 @@ class BuilderTemplate extends BaseTemplate {
                             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());       
+                                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»);
@@ -611,7 +611,7 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Template method which generate getter methods for IMPL class.
-     * 
+     *
      * @return string with getter methods
      */
     def private generateGetters(boolean addOverride) '''
@@ -636,7 +636,7 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Template method which generates the method <code>hashCode()</code>.
-     * 
+     *
      * @return string with the <code>hashCode()</code> method definition in JAVA format
      */
     def protected generateHashCode() '''
@@ -662,8 +662,8 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Template method which generates the method <code>equals()</code>.
-     * 
-     * @return string with the <code>equals()</code> method definition in JAVA format     
+     *
+     * @return string with the <code>equals()</code> method definition in JAVA format
      */
     def protected generateEquals() '''
         «IF !properties.empty || augmentField != null»
@@ -768,15 +768,15 @@ 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)
 
index 417451bc181eee82bc51d14c51909aeb56430d8c..92466b2bd2b2d7ad8e27360ddca0c982dc860cc6 100644 (file)
@@ -11,36 +11,36 @@ import org.opendaylight.yangtools.sal.binding.model.api.Enumeration
 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
 
 /**
- * Template for generating JAVA enumeration type. 
+ * Template for generating JAVA enumeration type.
  */
 class EnumTemplate extends BaseTemplate {
 
-    
+
     /**
      * Enumeration which will be transformed to JAVA source code for enumeration
      */
     val Enumeration enums
-    
+
     /**
      * Constructs instance of this class with concrete <code>enums</code>.
-     * 
-     * @param enums enumeration which will be transformed to JAVA source code 
+     *
+     * @param enums enumeration which will be transformed to JAVA source code
      */
     new(Enumeration enums) {
         super(enums as GeneratedType )
         this.enums = enums
     }
-    
-    
+
+
     /**
      * Generates only JAVA enumeration source code.
-     * 
+     *
      * @return string with JAVA enumeration source code
      */
     def generateAsInnerClass() {
         return body
     }
-    
+
     def writeEnumItem(String name, int value, String description) '''
         «asJavadoc(formatToParagraph(description))»
         «name»(«value»)
@@ -48,8 +48,8 @@ class EnumTemplate extends BaseTemplate {
 
     /**
      * Template method which generates enumeration body (declaration + enumeration items).
-     * 
-     * @return string with the enumeration body 
+     *
+     * @return string with the enumeration body
      */
     override body() '''
         «wrapToDocumentation(formatDataForJavaDoc(enums))»
@@ -69,11 +69,11 @@ class EnumTemplate extends BaseTemplate {
 
                 VALUE_MAP = b.build();
             }
-        
+
             private «enums.name»(int value) {
                 this.value = value;
             }
-            
+
             /**
              * @return integer value
              */
index 606fd753718b096bee210193b44231bd9ef3318c..acca70de9020dd151f5f63351562bb740c740c49 100644 (file)
@@ -16,34 +16,34 @@ import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
 import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature\rimport org.opendaylight.yangtools.sal.binding.model.api.AnnotationType
 
 /**
- * Template for generating JAVA interfaces. 
+ * Template for generating JAVA interfaces.
  */
 class InterfaceTemplate extends BaseTemplate {
-    
+
     /**
      * List of constant instances which are generated as JAVA public static final attributes.
      */
     val List<Constant> consts
-    
+
     /**
      * List of method signatures which are generated as method declarations.
      */
     val List<MethodSignature> methods
-    
+
     /**
      * List of enumeration which are generated as JAVA enum type.
      */
     val List<Enumeration> enums
-    
+
     /**
      * List of generated types which are enclosed inside <code>genType</code>
      */
     val List<GeneratedType> enclosedGeneratedTypes
-    
+
     /**
-     * Creates the instance of this class which is used for generating the interface file source 
+     * Creates the instance of this class which is used for generating the interface file source
      * code from <code>genType</code>.
-     * 
+     *
      * @throws IllegalArgumentException if <code>genType</code> equals <code>null</code>
      */
     new(GeneratedType genType) {
@@ -51,16 +51,16 @@ class InterfaceTemplate extends BaseTemplate {
         if (genType == null) {
             throw new IllegalArgumentException("Generated type reference cannot be NULL!")
         }
-        
+
         consts = genType.constantDefinitions
         methods = genType.methodDefinitions
         enums = genType.enumerations
         enclosedGeneratedTypes = genType.enclosedTypes
     }
-    
+
     /**
      * Template method which generate the whole body of the interface.
-     * 
+     *
      * @return string with code for interface body in JAVA format
      */
     override body() '''
@@ -68,19 +68,19 @@ class InterfaceTemplate extends BaseTemplate {
         public interface «type.name»
             «superInterfaces»
         {
-        
+
             «generateInnerClasses»
-        
+
             «generateEnums»
-        
+
             «generateConstants»
-        
+
             «generateMethods»
-        
+
         }
-        
+
     '''
-   
+
 
     def private generateAnnotations(List<AnnotationType> annotations) '''
         «IF annotations != null && !annotations.empty»
@@ -99,10 +99,10 @@ class InterfaceTemplate extends BaseTemplate {
 
     /**
      * Template method which generates the interface name declaration.
-     * 
+     *
      * @return string with the code for the interface declaration in JAVA format
      */
-    def private superInterfaces() 
+    def private superInterfaces()
     '''
     «IF (!type.implements.empty)»
          extends
@@ -114,7 +114,7 @@ class InterfaceTemplate extends BaseTemplate {
 
     /**
      * Template method which generates inner classes inside this interface.
-     * 
+     *
      * @return string with the source code for inner classes in JAVA format
      */
     def private generateInnerClasses() '''
@@ -138,9 +138,9 @@ class InterfaceTemplate extends BaseTemplate {
 
     /**
      * Template method which generates JAVA enum type.
-     * 
+     *
      * @return string with inner enum source code in JAVA format
-     */    
+     */
     def private generateEnums() '''
         «IF !enums.empty»
             «FOR e : enums SEPARATOR "\n"»
@@ -149,12 +149,12 @@ class InterfaceTemplate extends BaseTemplate {
             «ENDFOR»
         «ENDIF»
     '''
-    
+
     /**
      * Template method wich generates JAVA constants.
-     * 
-     * @return string with constants in JAVA format 
-     */    
+     *
+     * @return string with constants in JAVA format
+     */
     def private generateConstants() '''
         «IF !consts.empty»
             «FOR c : consts»
@@ -167,9 +167,9 @@ class InterfaceTemplate extends BaseTemplate {
 
     /**
      * Template method which generates the declaration of the methods.
-     * 
-     * @return string with the declaration of methods source code in JAVA format 
-     */    
+     *
+     * @return string with the declaration of methods source code in JAVA format
+     */
     def private generateMethods() '''
         «IF !methods.empty»
             «FOR m : methods SEPARATOR "\n"»
index e8ddb9673f423e1e48a9280c744b3d9da726c79a..78c2cd05253179c4bd7b3cc5b7329ef87e2509b8 100644 (file)
@@ -13,13 +13,13 @@ import org.opendaylight.yangtools.sal.binding.model.api.Enumeration
 import static org.opendaylight.yangtools.binding.generator.util.Types.*
 
 /**
- * Template for generating JAVA class. 
+ * Template for generating JAVA class.
  */
 class UnionTemplate extends ClassTemplate {
 
     /**
      * Creates instance of this class with concrete <code>genType</code>.
-     * 
+     *
      * @param genType generated transfer object which will be transformed to JAVA class source code
      */
     new(GeneratedTransferObject genType) {
@@ -44,7 +44,7 @@ class UnionTemplate extends ClassTemplate {
             «IF isCharArray»
                 /**
                  * Constructor provided only for using in JMX. Don't use it for
-                 * construction new object of this union type. 
+                 * construction new object of this union type.
                  */
                 @«ConstructorProperties.importedName»("«property.name»")
                 public «type.name»(«propRet.importedName» «property.fieldName») {
@@ -84,10 +84,10 @@ class UnionTemplate extends ClassTemplate {
                                     this.«other.fieldName» = «property.fieldName».getValue();
                                 «ELSEIF propRet instanceof GeneratedTransferObject // Is it a GeneratedTransferObject
                                         && (propRet as GeneratedTransferObject).typedef  // Is it a typedef
-                                        && (propRet as GeneratedTransferObject).properties != null 
-                                        && !(propRet as GeneratedTransferObject).properties.empty 
-                                        && ((propRet as GeneratedTransferObject).properties.size == 1) 
-                                        && (propRet as GeneratedTransferObject).properties.get(0).name.equals("value") 
+                                        && (propRet as GeneratedTransferObject).properties != null
+                                        && !(propRet as GeneratedTransferObject).properties.empty
+                                        && ((propRet as GeneratedTransferObject).properties.size == 1)
+                                        && (propRet as GeneratedTransferObject).properties.get(0).name.equals("value")
                                         && BOOLEAN.equals((propRet as GeneratedTransferObject).properties.get(0).returnType)» // And the property value is of type boolean
                                     ««« generated boolean typedef
                                     this.«other.fieldName» = «property.fieldName».isValue().toString().toCharArray();
index 9e27693962e037f36098a54754b4cb6f347c8e36..64693702ff05b90f4fcd6f92e0e822385ed09d96 100644 (file)
@@ -64,7 +64,7 @@ class YangModuleInfoTemplate {
                 «val DateFormat df = new SimpleDateFormat("yyyy-MM-dd")»
                 private final «String.importedName» revision = "«df.format(module.revision)»";
                 private final «String.importedName» resourcePath = "«sourcePath»";
-                
+
                 private final «Set.importedName»<YangModuleInfo> importedModules;
 
                 public static «YangModuleInfo.importedName» getInstance() {
@@ -190,7 +190,7 @@ class YangModuleInfoTemplate {
         return "/" + module.moduleSourcePath.replace(java.io.File.separatorChar, '/')
     }
 
-    private def imports() ''' 
+    private def imports() '''
         «IF !importMap.empty»
             «FOR entry : importMap.entrySet»
                 «IF entry.value != getRootPackageName(module.QNameModule)»
diff --git a/code-generator/binding-java-api-generator/src/test/java/org/opendaylight/yangtools/sal/java/api/generator/test/UnionTypedefUnusedImportTest.java b/code-generator/binding-java-api-generator/src/test/java/org/opendaylight/yangtools/sal/java/api/generator/test/UnionTypedefUnusedImportTest.java
new file mode 100644 (file)
index 0000000..39f3607
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.sal.java.api.generator.test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.COMPILER_OUTPUT_PATH;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.FS;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.GENERATOR_OUTPUT_PATH;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.cleanUp;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.getSourceFiles;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.testCompilation;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.HashSet;
+import java.util.List;
+import org.junit.Test;
+import org.opendaylight.yangtools.sal.binding.model.api.Type;
+import org.opendaylight.yangtools.sal.java.api.generator.GeneratorJavaFile;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class UnionTypedefUnusedImportTest extends BaseCompilationTest {
+
+    @Test
+    public void testUnionTypedefUnusedImport() throws Exception {
+        final File sourcesOutputDir = new File(GENERATOR_OUTPUT_PATH + FS + "union-typedef");
+        assertTrue("Failed to create test file '" + sourcesOutputDir + "'", sourcesOutputDir.mkdir());
+        final File compiledOutputDir = new File(COMPILER_OUTPUT_PATH + FS + "union-typedef");
+        assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdir());
+
+        final List<File> sourceFiles = getSourceFiles("/compilation/union-typedef");
+        final SchemaContext context = parser.parseFiles(sourceFiles);
+        final List<Type> types = bindingGenerator.generateTypes(context);
+        final GeneratorJavaFile generator = new GeneratorJavaFile(new HashSet<>(types));
+        generator.generateToFile(sourcesOutputDir);
+        final boolean isUsedImport = containsImport("org.opendaylight.yang.gen.v1.org.opendaylight.yangtools.union.typedef.rev130208.TypedefUnion");
+        assertFalse(String.format("Class shouldn't contain import for this type '%s'", types.get(1).getName()),
+                isUsedImport);
+
+        testCompilation(sourcesOutputDir, compiledOutputDir);
+        cleanUp(sourcesOutputDir, compiledOutputDir);
+    }
+
+    private String readFile(String path, Charset encoding) throws IOException {
+        byte[] encoded = Files.readAllBytes(Paths.get(path));
+        return new String(encoded, encoding);
+    }
+
+    private boolean containsImport(final String fullImport) throws URISyntaxException, IOException {
+        final String filePath = GENERATOR_OUTPUT_PATH + FS + "union-typedef" + FS + "org" + FS + "opendaylight" + FS + "yang" + FS + "gen" + FS + "v1" + FS + "org" + FS + "opendaylight" + FS + "yangtools" + FS + "union" + FS + "typedef" + FS + "rev141124" + FS + "TypedefUnionBuilder.java";
+        final String fileContent = readFile(filePath, StandardCharsets.UTF_8);
+
+        if (fileContent.contains(fullImport)) {
+            return true;
+        }
+        return false;
+    }
+}
diff --git a/code-generator/binding-java-api-generator/src/test/resources/compilation/union-typedef/union-typedef-test.yang b/code-generator/binding-java-api-generator/src/test/resources/compilation/union-typedef/union-typedef-test.yang
new file mode 100644 (file)
index 0000000..b271f07
--- /dev/null
@@ -0,0 +1,19 @@
+module union-typedef-test {
+    yang-version 1;
+    namespace "org:opendaylight:yangtools:union:typedef";
+    prefix "tp";
+
+    description
+        "Test unused import";
+
+    revision "2014-11-24" {
+        reference "WILL BE DEFINED LATER";
+    }
+
+    typedef typedef-union {
+        type union {
+            type int32;
+            type string;
+        }
+    }
+}
\ No newline at end of file