Merge "BUG-865: get rid of InstanceIdentifier-related warnings"
authorTony Tkacik <ttkacik@cisco.com>
Mon, 21 Jul 2014 13:12:05 +0000 (13:12 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Mon, 21 Jul 2014 13:12:05 +0000 (13:12 +0000)
27 files changed:
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/BindingGeneratorImpl.java
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/LazyGeneratedCodecRegistry.java
code-generator/binding-generator-util/src/main/java/org/opendaylight/yangtools/binding/generator/util/generated/type/builder/EnumerationBuilderImpl.java
code-generator/binding-generator-util/src/main/java/org/opendaylight/yangtools/binding/generator/util/generated/type/builder/GeneratedTOBuilderImpl.java
code-generator/binding-generator-util/src/main/java/org/opendaylight/yangtools/binding/generator/util/generated/type/builder/GeneratedTypeBuilderImpl.java
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/ClassTemplate.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/UnionBuilderTemplate.xtend
code-generator/binding-java-api-generator/src/test/resources/compilation/augment-uses-to-augment/bar.yang
code-generator/binding-java-api-generator/src/test/resources/compilation/augment-uses-to-augment/baz.yang
code-generator/binding-java-api-generator/src/test/resources/compilation/augment-uses-to-augment/foo.yang
code-generator/binding-model-api/src/main/java/org/opendaylight/yangtools/sal/binding/model/api/DocumentedType.java [new file with mode: 0644]
code-generator/binding-model-api/src/main/java/org/opendaylight/yangtools/sal/binding/model/api/Enumeration.java
code-generator/binding-model-api/src/main/java/org/opendaylight/yangtools/sal/binding/model/api/GeneratedType.java
code-generator/binding-model-api/src/main/java/org/opendaylight/yangtools/sal/binding/model/api/type/builder/EnumBuilder.java
code-generator/binding-model-api/src/main/java/org/opendaylight/yangtools/sal/binding/model/api/type/builder/GeneratedTypeBuilderBase.java
code-generator/binding-type-provider/src/main/java/org/opendaylight/yangtools/sal/binding/yang/types/TypeProviderImpl.java
yang/yang-common/src/main/java/org/opendaylight/yangtools/yang/common/QName.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/xml/XmlDocumentUtils.java
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/TreeNodeUtilsTest.java [new file with mode: 0644]
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/BaseTypes.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/Leafref.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/TwoRevisionsTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/util/RefineHolderTest.java

index d7c5532af8fccec139ccf34df9d4d4730bc137e4..15fa0902d0029ee7084d6f64ea63d1e76a1a7257 100644 (file)
@@ -290,8 +290,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
         return genType;
     }
 
-    private void containerToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
-            final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
+    private void containerToGenType(final Module module, final String basePackageName,
+            final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
         final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
         if (genType != null) {
             constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType);
@@ -575,14 +575,14 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *            information about base of identity
      *
      */
-    private void identityToGenType(final Module module, final String basePackageName, final IdentitySchemaNode identity,
-            final SchemaContext context) {
+    private void identityToGenType(final Module module, final String basePackageName,
+            final IdentitySchemaNode identity, final SchemaContext context) {
         if (identity == null) {
             return;
         }
         final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
         final String genTypeName = BindingMapping.getClassName(identity.getQName());
-        final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
+        final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
         final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
         if (baseIdentity == null) {
             final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
@@ -590,7 +590,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
             newType.setExtendsType(gto.toInstance());
         } else {
             final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
-            final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule.getQNameModule());
+            final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
+                    .getQNameModule());
             final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
             final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
                     .toInstance();
@@ -598,13 +599,19 @@ public class BindingGeneratorImpl implements BindingGenerator {
         }
         newType.setAbstract(true);
         newType.addComment(identity.getDescription());
+        newType.setDescription(identity.getDescription());
+        newType.setReference(identity.getReference());
+        newType.setModuleName(module.getName());
+        newType.setSchemaPath(identity.getPath().getPathFromRoot());
+
         final QName qname = identity.getQName();
         qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
 
         genCtx.get(module).addIdentityType(identity.getQName(), newType);
     }
 
-    private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName, final QName name) {
+    private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
+            final QName name) {
         StringBuilder sb = new StringBuilder("org.opendaylight.yangtools.yang.common.QName");
         sb.append(".create(");
         sb.append('"');
@@ -686,6 +693,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
                 && (enumTypeDef.getQName().getLocalName() != null)) {
             final String enumerationName = BindingMapping.getClassName(enumName);
             final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
+            enumBuilder.setDescription(enumTypeDef.getDescription());
             enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
             return enumBuilder;
         }
@@ -710,7 +718,13 @@ public class BindingGeneratorImpl implements BindingGenerator {
         checkArgument(module != null, "Module reference cannot be NULL.");
         final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
         final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
-        return new GeneratedTypeBuilderImpl(packageName, moduleName);
+
+        final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
+        moduleBuilder.setDescription(module.getDescription());
+        moduleBuilder.setReference(module.getReference());
+        moduleBuilder.setModuleName(moduleName);
+
+        return moduleBuilder;
     }
 
     /**
@@ -737,7 +751,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      * @throws IllegalStateException
      *             if augment target path is null
      */
-    private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema, final Module module) {
+    private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
+            final Module module) {
         checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
         checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
         checkState(augSchema.getTargetPath() != null,
@@ -781,8 +796,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
         }
     }
 
-    private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema, final Module module,
-            final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
+    private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
+            final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
         checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
         checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
         checkState(augSchema.getTargetPath() != null,
@@ -1015,7 +1030,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *         added to it.
      */
     private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
-            final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Set<DataSchemaNode> schemaNodes) {
+            final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
+            final Set<DataSchemaNode> schemaNodes) {
         if ((schemaNodes != null) && (typeBuilder != null)) {
             for (DataSchemaNode schemaNode : schemaNodes) {
                 if (!schemaNode.isAugmenting()) {
@@ -1087,8 +1103,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *             <li>if <code>choiceNode</code> is null</li>
      *             </ul>
      */
-    private void choiceToGeneratedType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
-            final ChoiceNode choiceNode) {
+    private void choiceToGeneratedType(final Module module, final String basePackageName,
+            final GeneratedTypeBuilder parent, final ChoiceNode choiceNode) {
         checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
         checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
 
@@ -1130,8 +1146,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *             <li>if <code>caseNodes</code> equals null</li>
      *             </ul>
      */
-    private void generateTypesFromChoiceCases(final Module module, final String basePackageName, final Type refChoiceType,
-            final ChoiceNode choiceNode) {
+    private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
+            final Type refChoiceType, final ChoiceNode choiceNode) {
         checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
         checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
         checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
@@ -1214,8 +1230,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *             <li>if <code>augmentedNodes</code> is null</li>
      *             </ul>
      */
-    private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName, final Type targetType,
-            final ChoiceNode targetNode, final Set<DataSchemaNode> augmentedNodes) {
+    private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
+            final Type targetType, final ChoiceNode targetNode, final Set<DataSchemaNode> augmentedNodes) {
         checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
         checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
         checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
@@ -1303,12 +1319,12 @@ public class BindingGeneratorImpl implements BindingGenerator {
                     }
                     ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
                 } else if (typeDef instanceof UnionType) {
-                    genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf);
+                    genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
                     if (genTOBuilder != null) {
                         returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
                     }
                 } else if (typeDef instanceof BitsTypeDefinition) {
-                    genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf);
+                    genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
                     if (genTOBuilder != null) {
                         returnType = new ReferencedTypeImpl(genTOBuilder.getPackageName(), genTOBuilder.getName());
                     }
@@ -1325,7 +1341,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
         return returnType;
     }
 
-    private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter, final Module module) {
+    private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
+            final Module module) {
         for (UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
             final QName nodeType = node.getNodeType();
             if ("context-reference".equals(nodeType.getLocalName())) {
@@ -1439,8 +1456,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *         <li>true - other cases</li>
      *         </ul>
      */
-    private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf, final Type returnType,
-            final boolean isReadOnly) {
+    private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
+            final Type returnType, final boolean isReadOnly) {
         if (returnType == null) {
             return false;
         }
@@ -1490,12 +1507,12 @@ public class BindingGeneratorImpl implements BindingGenerator {
                     returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
                     ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
                 } else if (typeDef instanceof UnionType) {
-                    final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node);
+                    final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
                     if (genTOBuilder != null) {
                         returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
                     }
                 } else if (typeDef instanceof BitsTypeDefinition) {
-                    final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node);
+                    final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
                     returnType = new ReferencedTypeImpl(genTOBuilder.getPackageName(), genTOBuilder.getName());
                 } else {
                     final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
@@ -1514,6 +1531,12 @@ public class BindingGeneratorImpl implements BindingGenerator {
             final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
         final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
                 genTOBuilder.getName());
+
+        returnType.setDescription(typeDef.getDescription());
+        returnType.setReference(typeDef.getReference());
+        returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
+        returnType.setModuleName(parentModule.getName());
+
         genTOBuilder.setTypedef(true);
         genTOBuilder.setIsUnion(true);
         ((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
@@ -1565,7 +1588,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *            parent type (can be null)
      * @return generated type builder <code>schemaNode</code>
      */
-    private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode, final Type parent) {
+    private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
+            final Type parent) {
         final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
         if (parent == null) {
             it.addImplementsType(DATA_OBJECT);
@@ -1622,7 +1646,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *             </ul>
      *
      */
-    private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode, final String prefix) {
+    private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
+            final String prefix) {
         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
         checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
         checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
@@ -1640,6 +1665,13 @@ public class BindingGeneratorImpl implements BindingGenerator {
         final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
         qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
         newType.addComment(schemaNode.getDescription());
+        newType.setDescription(schemaNode.getDescription());
+        newType.setReference(schemaNode.getReference());
+        newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
+
+        final Module module = findParentModule(schemaContext, schemaNode);
+        newType.setModuleName(module.getName());
+
         if (!genTypeBuilders.containsKey(packageName)) {
             final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
             builders.put(genTypeName, newType);
@@ -1696,8 +1728,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      * @return method signature builder which represents the getter method of
      *         <code>interfaceBuilder</code>
      */
-    private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final String schemaNodeName,
-            final String comment, final Type returnType) {
+    private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
+            final String schemaNodeName, final String comment, final Type returnType) {
         final MethodSignatureBuilder getMethod = interfaceBuilder
                 .addMethod(getterMethodName(schemaNodeName, returnType));
         getMethod.setComment(comment);
@@ -1730,7 +1762,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *             </ul>
      */
     private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
-            final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys, final Module module) {
+            final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
+            final Module module) {
         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
 
@@ -1758,7 +1791,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
         }
     }
 
-    private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder) {
+    private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
+            final GeneratedTOBuilder genTOBuilder) {
         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
 
         if (genTOBuilder != null) {
@@ -1834,8 +1868,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      * @param leaf
      * @return generated TO builder for <code>typeDef</code>
      */
-    private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef, final GeneratedTypeBuilder typeBuilder,
-            final DataSchemaNode leaf) {
+    private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
+            final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
         final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
         final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
         final String packageName = typeBuilder.getFullyQualifiedName();
@@ -1861,7 +1895,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
 
         } else if (typeDef instanceof BitsTypeDefinition) {
             genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
-                    packageName, typeDef, classNameFromLeaf));
+                    packageName, typeDef, classNameFromLeaf, parentModule.getName()));
         }
         if (genTOBuilders != null && !genTOBuilders.isEmpty()) {
             for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
index c890252a3fb00808dec50e1b54cd6018bea1e603..5a520d111389086ca02c8075fc9ef07f5451297a 100644 (file)
@@ -68,7 +68,9 @@ import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -194,7 +196,12 @@ class LazyGeneratedCodecRegistry implements //
 
     @Override
     public Class<?> getClassForPath(final List<QName> names) {
-        final DataSchemaNode node = getSchemaNode(names);
+        DataSchemaNode node = getSchemaNode(names);
+        Preconditions.checkArgument(node != null, "Path %s points to invalid schema location",names);
+        SchemaNode originalDefinition = SchemaNodeUtils.getRootOriginalIfPossible(node);
+        if(originalDefinition instanceof DataSchemaNode) {
+            node =(DataSchemaNode) originalDefinition;
+        }
         final SchemaPath path = node.getPath();
         final Type t = pathToType.get(path);
 
@@ -208,9 +215,14 @@ class LazyGeneratedCodecRegistry implements //
 
         @SuppressWarnings("rawtypes")
         final WeakReference<Class> weakRef = typeToClass.get(type);
-        Preconditions.checkState(weakRef != null, "Could not find loaded class for path: %s and type: %s", path,
-                type.getFullyQualifiedName());
-        return weakRef.get();
+        if(weakRef != null) {
+            return weakRef.get();
+        }
+        try {
+            return classLoadingStrategy.loadClass(type);
+        } catch (ClassNotFoundException e) {
+            throw new IllegalStateException(String.format("Could not find loaded class for path: %s and type: %s", path,type.getFullyQualifiedName()));
+        }
     }
 
     @Override
@@ -254,7 +266,7 @@ class LazyGeneratedCodecRegistry implements //
         WeakReference<Class> weakRef = new WeakReference<>(cls);
         typeToClass.put(typeRef, weakRef);
         if (Augmentation.class.isAssignableFrom(cls)) {
-
+            // Intentionally NOOP
         } else if (DataObject.class.isAssignableFrom(cls)) {
             getCodecForDataObject((Class<? extends DataObject>) cls);
         }
index 870fcd9ec864546637ff8ed34dd2b75e78c9663c..be8d905e6baafa1a4690bd6d40d3aa6246cce785 100644 (file)
@@ -22,6 +22,8 @@ import org.opendaylight.yangtools.sal.binding.model.api.Type;
 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
 import org.opendaylight.yangtools.yang.binding.BindingMapping;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.Status;
 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
 
@@ -30,6 +32,10 @@ public final class EnumerationBuilderImpl extends AbstractBaseType implements En
     private final String name;
     private final List<Enumeration.Pair> values;
     private final List<AnnotationTypeBuilder> annotationBuilders = new ArrayList<>();
+    private String description;
+    private String reference;
+    private String moduleName;
+    private Iterable<QName> schemaPath;
 
     public EnumerationBuilderImpl(final String packageName, final String name) {
         super(packageName, name);
@@ -38,6 +44,24 @@ public final class EnumerationBuilderImpl extends AbstractBaseType implements En
         values = new ArrayList<>();
     }
 
+    public void setReference(final String reference) {
+        this.reference = reference;
+    }
+
+    public void setModuleName(final String moduleName) {
+        this.moduleName = moduleName;
+    }
+
+    public void setSchemaPath(final Iterable<QName> schemaPath) {
+        this.schemaPath = schemaPath;
+    }
+
+    @Override
+    public void setDescription(String description) {
+        this.description = description;
+
+    }
+
     @Override
     public AnnotationTypeBuilder addAnnotation(final String packageName, final String name) {
         if (packageName != null && name != null) {
@@ -50,13 +74,38 @@ public final class EnumerationBuilderImpl extends AbstractBaseType implements En
     }
 
     @Override
-    public void addValue(final String name, final Integer value) {
-        values.add(new EnumPairImpl(name, value));
+    public void addValue(final String name, final Integer value, final String description) {
+        values.add(new EnumPairImpl(name, value, description));
     }
 
     @Override
     public Enumeration toInstance(final Type definingType) {
-        return new EnumerationImpl(definingType, annotationBuilders, packageName, name, values);
+        return new EnumerationImpl(definingType, annotationBuilders, packageName, name, values,
+                description, reference, moduleName, schemaPath);
+    }
+
+    @Override
+    public void updateEnumPairsFromEnumTypeDef(final EnumTypeDefinition enumTypeDef) {
+        final List<EnumPair> enums = enumTypeDef.getValues();
+        if (enums != null) {
+            int listIndex = 0;
+            for (final EnumPair enumPair : enums) {
+                if (enumPair != null) {
+                    final String enumPairName = BindingMapping.getClassName(enumPair.getName());
+                    Integer enumPairValue = enumPair.getValue();
+
+                    if (enumPairValue == null) {
+                        enumPairValue = listIndex;
+                    }
+                    else {
+                        listIndex = enumPairValue;
+                    }
+
+                    this.addValue(enumPairName, enumPairValue, enumPair.getDescription());
+                    listIndex++;
+                }
+            }
+        }
     }
 
     /*
@@ -125,36 +174,17 @@ public final class EnumerationBuilderImpl extends AbstractBaseType implements En
         return builder.toString();
     }
 
-    @Override
-    public void updateEnumPairsFromEnumTypeDef(final EnumTypeDefinition enumTypeDef) {
-        final List<EnumPair> enums = enumTypeDef.getValues();
-        if (enums != null) {
-            int listIndex = 0;
-            for (final EnumPair enumPair : enums) {
-                if (enumPair != null) {
-                    final String enumPairName = BindingMapping.getClassName(enumPair.getName());
-                    Integer enumPairValue = enumPair.getValue();
-
-                    if (enumPairValue == null) {
-                        enumPairValue = listIndex;
-                    }
-                    this.addValue(enumPairName, enumPairValue);
-                    listIndex++;
-                }
-            }
-        }
-
-    }
-
     private static final class EnumPairImpl implements Enumeration.Pair {
 
         private final String name;
         private final Integer value;
+        private final String description;
 
-        public EnumPairImpl(String name, Integer value) {
+        public EnumPairImpl(String name, Integer value, String description) {
             super();
             this.name = name;
             this.value = value;
+            this.description = description;
         }
 
         @Override
@@ -230,6 +260,23 @@ public final class EnumerationBuilderImpl extends AbstractBaseType implements En
             builder.append("]");
             return builder.toString();
         }
+
+        @Override
+        public String getDescription() {
+            return description;
+        }
+
+        @Override
+        public String getReference() {
+            return null;
+        }
+
+        @Override
+        public Status getStatus() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
     }
 
     private static final class EnumerationImpl implements Enumeration {
@@ -237,11 +284,16 @@ public final class EnumerationBuilderImpl extends AbstractBaseType implements En
         private final Type definingType;
         private final String packageName;
         private final String name;
+        private final String description;
+        private final String reference;
+        private final String moduleName;
+        private final Iterable<QName> schemaPath;
         private final List<Pair> values;
         private List<AnnotationType> annotations = new ArrayList<>();
 
         public EnumerationImpl(final Type definingType, final List<AnnotationTypeBuilder> annotationBuilders,
-                final String packageName, final String name, final List<Pair> values) {
+                final String packageName, final String name, final List<Pair> values, final String description,
+                final String reference, final String moduleName, final Iterable<QName> schemaPath) {
             super();
             this.definingType = definingType;
             for (final AnnotationTypeBuilder builder : annotationBuilders) {
@@ -251,6 +303,10 @@ public final class EnumerationBuilderImpl extends AbstractBaseType implements En
             this.packageName = packageName;
             this.name = name;
             this.values = Collections.unmodifiableList(values);
+            this.description = description;
+            this.reference = reference;
+            this.moduleName = moduleName;
+            this.schemaPath = schemaPath;
         }
 
         @Override
@@ -434,5 +490,25 @@ public final class EnumerationBuilderImpl extends AbstractBaseType implements En
         public List<GeneratedProperty> getProperties() {
             return Collections.emptyList();
         }
+
+        @Override
+        public String getDescription() {
+            return description;
+        }
+
+        @Override
+        public String getReference() {
+            return reference;
+        }
+
+        @Override
+        public Iterable<QName> getSchemaPath() {
+            return schemaPath;
+        }
+
+        @Override
+        public String getModuleName() {
+            return moduleName;
+        }
     }
 }
index b3b1c7ce256ddff61166bc341dbafdfdc1b966ab..18efb661d6b980417f5abc2ac898e8c856895332 100644 (file)
@@ -18,6 +18,7 @@ import org.opendaylight.yangtools.sal.binding.model.api.Type;
 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
+import org.opendaylight.yangtools.yang.common.QName;
 
 public final class GeneratedTOBuilderImpl extends AbstractGeneratedTypeBuilder<GeneratedTOBuilder> implements
         GeneratedTOBuilder {
@@ -31,6 +32,10 @@ public final class GeneratedTOBuilderImpl extends AbstractGeneratedTypeBuilder<G
     private boolean isUnionTypeBuilder = false;
     private Restrictions restrictions;
     private GeneratedPropertyBuilder SUID;
+    private String reference;
+    private String description;
+    private String moduleName;
+    private Iterable<QName> schemaPath;
 
     public GeneratedTOBuilderImpl(final String packageName, final String name) {
         super(packageName, name);
@@ -102,7 +107,8 @@ public final class GeneratedTOBuilderImpl extends AbstractGeneratedTypeBuilder<G
 
     @Override
     public GeneratedTransferObject toInstance() {
-        // FIXME: can we compact the arrays now? It needs to be thread-safe, though
+        // FIXME: can we compact the arrays now? It needs to be thread-safe,
+        // though
         return new GeneratedTransferObjectImpl(this);
     }
 
@@ -148,6 +154,26 @@ public final class GeneratedTOBuilderImpl extends AbstractGeneratedTypeBuilder<G
         this.isUnionTypeBuilder = isUnionTypeBuilder;
     }
 
+    @Override
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    @Override
+    public void setModuleName(String moduleName) {
+        this.moduleName = moduleName;
+    }
+
+    @Override
+    public void setSchemaPath(Iterable<QName> schemaPath) {
+        this.schemaPath = schemaPath;
+    }
+
+    @Override
+    public void setReference(String reference) {
+        this.reference = reference;
+    }
+
     private static final class GeneratedTransferObjectImpl extends AbstractGeneratedType implements
             GeneratedTransferObject {
 
@@ -160,6 +186,10 @@ public final class GeneratedTOBuilderImpl extends AbstractGeneratedTypeBuilder<G
         private final boolean isUnionTypeBuilder;
         private final Restrictions restrictions;
         private final GeneratedProperty SUID;
+        private final String reference;
+        private final String description;
+        private final String moduleName;
+        private final Iterable<QName> schemaPath;
 
         public GeneratedTransferObjectImpl(final GeneratedTOBuilderImpl builder) {
             super(builder);
@@ -171,6 +201,11 @@ public final class GeneratedTOBuilderImpl extends AbstractGeneratedTypeBuilder<G
             this.isUnionType = builder.isUnionType;
             this.isUnionTypeBuilder = builder.isUnionTypeBuilder;
             this.restrictions = builder.restrictions;
+            this.reference = builder.reference;
+            this.description = builder.description;
+            this.moduleName = builder.moduleName;
+            this.schemaPath = builder.schemaPath;
+
             if (builder.SUID == null) {
                 this.SUID = null;
             } else {
@@ -225,7 +260,7 @@ public final class GeneratedTOBuilderImpl extends AbstractGeneratedTypeBuilder<G
 
         @Override
         public String toString() {
-            if(isTypedef) {
+            if (isTypedef) {
                 return serializeTypedef(this);
             }
             StringBuilder builder = new StringBuilder();
@@ -283,5 +318,24 @@ public final class GeneratedTOBuilderImpl extends AbstractGeneratedTypeBuilder<G
             }
         }
 
+        @Override
+        public String getDescription() {
+            return description;
+        }
+
+        @Override
+        public String getReference() {
+            return reference;
+        }
+
+        @Override
+        public Iterable<QName> getSchemaPath() {
+            return schemaPath;
+        }
+
+        @Override
+        public String getModuleName() {
+            return moduleName;
+        }
     }
 }
index 27fe08f411808d90baae77d78ac9758f5b75c649..92c5629eab8861674bb2532957d4ab0bb9239256 100644 (file)
@@ -7,13 +7,19 @@
  */
 package org.opendaylight.yangtools.binding.generator.util.generated.type.builder;
 
-
 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
+import org.opendaylight.yangtools.yang.common.QName;
+
+public final class GeneratedTypeBuilderImpl extends AbstractGeneratedTypeBuilder<GeneratedTypeBuilder> implements
+        GeneratedTypeBuilder {
 
-public final class GeneratedTypeBuilderImpl extends AbstractGeneratedTypeBuilder<GeneratedTypeBuilder> implements GeneratedTypeBuilder {
+    private String description;
+    private String reference;
+    private String moduleName;
+    private Iterable<QName> schemaPath;
 
-    public GeneratedTypeBuilderImpl(String packageName, String name) {
+    public GeneratedTypeBuilderImpl(final String packageName, final String name) {
         super(packageName, name);
         setAbstract(true);
     }
@@ -23,6 +29,26 @@ public final class GeneratedTypeBuilderImpl extends AbstractGeneratedTypeBuilder
         return new GeneratedTypeImpl(this);
     }
 
+    @Override
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    @Override
+    public void setModuleName(String moduleName) {
+        this.moduleName = moduleName;
+    }
+
+    @Override
+    public void setSchemaPath(Iterable<QName> schemaPath) {
+        this.schemaPath = schemaPath;
+    }
+
+    @Override
+    public void setReference(String reference) {
+        this.reference = reference;
+    }
+
     @Override
     public String toString() {
         StringBuilder builder = new StringBuilder();
@@ -48,7 +74,7 @@ public final class GeneratedTypeBuilderImpl extends AbstractGeneratedTypeBuilder
         builder.append("]");
         return builder.toString();
     }
-    
+
     @Override
     protected GeneratedTypeBuilderImpl thisInstance() {
         return this;
@@ -56,8 +82,38 @@ public final class GeneratedTypeBuilderImpl extends AbstractGeneratedTypeBuilder
 
     private static final class GeneratedTypeImpl extends AbstractGeneratedType {
 
+        private final String description;
+        private final String reference;
+        private final String moduleName;
+        private final Iterable<QName> schemaPath;
+
         public GeneratedTypeImpl(GeneratedTypeBuilderImpl builder) {
             super(builder);
+
+            this.description = builder.description;
+            this.reference = builder.reference;
+            this.moduleName = builder.moduleName;
+            this.schemaPath = builder.schemaPath;
+        }
+
+        @Override
+        public String getDescription() {
+            return description;
+        }
+
+        @Override
+        public String getReference() {
+            return reference;
+        }
+
+        @Override
+        public Iterable<QName> getSchemaPath() {
+            return schemaPath;
+        }
+
+        @Override
+        public String getModuleName() {
+            return moduleName;
         }
     }
 }
index c1b1074d5d45b06e0db40be6181d250030ed27e0..24d0a7fd6031f30b2410033337f7f6bef89f59f4 100644 (file)
@@ -7,29 +7,31 @@
  */
 package org.opendaylight.yangtools.sal.java.api.generator
 
-import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty
-import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
-import java.util.Map
-import org.opendaylight.yangtools.sal.binding.model.api.Type
-import org.opendaylight.yangtools.binding.generator.util.Types
-import com.google.common.base.Splitter
-import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature
+import com.google.common.collect.ImmutableList
 import com.google.common.collect.Range
+import java.math.BigDecimal
+import java.math.BigInteger
+import java.util.Arrays
+import java.util.Collection
+import java.util.HashMap
 import java.util.List
+import java.util.Map
+import java.util.StringTokenizer
+import org.opendaylight.yangtools.binding.generator.util.Types
 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType
-import org.opendaylight.yangtools.sal.binding.model.api.Restrictions
+import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty
 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject
-import java.util.Collection
-import java.util.Arrays
-import java.util.HashMap
-import com.google.common.collect.ImmutableList
-import java.math.BigInteger
-import java.math.BigDecimal
+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.Restrictions
+import org.opendaylight.yangtools.sal.binding.model.api.Type
+import org.opendaylight.yangtools.yang.common.QName
 
 abstract class BaseTemplate {
     protected val GeneratedType type;
     protected val Map<String, String> importMap;
-    static val paragraphSplitter = Splitter.on("\n\n").omitEmptyStrings();
+
+    private static final String NEW_LINE = '\n'
 
     new(GeneratedType _type) {
         if (_type == null) {
@@ -50,7 +52,7 @@ abstract class BaseTemplate {
         '''
             Â«packageDefinition»
             Â«imports»
-            
+
             Â«_body»
         '''.toString
     }
@@ -63,7 +65,7 @@ abstract class BaseTemplate {
                 Â«ENDIF»
             Â«ENDFOR»
         Â«ENDIF»
-        
+
     '''
 
     protected abstract def CharSequence body();
@@ -154,22 +156,204 @@ abstract class BaseTemplate {
      * @return string with comment in JAVA format
      */
     def protected CharSequence asJavadoc(String comment) {
-        if(comment == null) return '';
+        if(comment == null) return ''
         var txt = comment
         if (txt.contains("*/")) {
             txt = txt.replace("*/", "&#42;&#47;")
         }
-        val paragraphs = paragraphSplitter.split(txt)
+        txt = comment.trim
+        txt = formatToParagraph(txt)
 
         return '''
-            /**
-              Â«FOR p : paragraphs SEPARATOR "<p>"»
-                  Â«p»
-              Â«ENDFOR»
-            **/
+            Â«wrapToDocumentation(txt)»
         '''
     }
 
+    def String wrapToDocumentation(String text) {
+        val StringTokenizer tokenizer = new StringTokenizer(text, "\n", false)
+        val StringBuilder sb = new StringBuilder()
+
+        if(text.empty)
+            return ""
+
+        sb.append("/**")
+        sb.append(NEW_LINE)
+
+        while(tokenizer.hasMoreTokens) {
+            sb.append(" * ")
+            sb.append(tokenizer.nextToken)
+            sb.append(NEW_LINE)
+        }
+        sb.append(" */")
+
+        return sb.toString
+    }
+
+    def protected String formatDataForJavaDoc(GeneratedType type) {
+        val typeDescription = type.description
+        val typeReference = type.reference
+        val typeModuleName = type.moduleName
+        val typeSchemaPath = type.schemaPath
+
+        return '''
+            Â«IF !type.isDocumentationParametersNullOrEmtpy»
+               Â«IF typeDescription != null && !typeDescription.empty»
+                Â«formatToParagraph(typeDescription)»
+               Â«ENDIF»
+               Â«IF typeReference != null && !typeReference.empty»
+                Reference:
+                    Â«formatReference(typeReference)»
+               Â«ENDIF»
+               Â«IF typeModuleName != null && !typeModuleName.empty»
+                Module name:
+                    Â«typeModuleName»
+               Â«ENDIF»
+               Â«IF typeSchemaPath != null && !typeSchemaPath.empty»
+                Schema path:
+                    Â«formatPath(typeSchemaPath)»
+               Â«ENDIF»
+            Â«ENDIF»
+        '''.toString
+    }
+
+    def formatPath(Iterable<QName> schemaPath) {
+        var currentElement = schemaPath.head
+        val StringBuilder sb = new StringBuilder()
+        sb.append('[')
+        sb.append(currentElement)
+
+        for(pathElement : schemaPath) {
+            if(!currentElement.namespace.equals(pathElement.namespace)) {
+                currentElement = pathElement
+                sb.append('/')
+                sb.append(pathElement)
+            }
+            else {
+                sb.append('/')
+                sb.append(pathElement.localName)
+            }
+        }
+        sb.append(']')
+        return sb.toString
+    }
+
+    def formatReference(String reference) {
+        if(reference == null || reference.isEmpty)
+            return reference
+
+        val StringTokenizer tokenizer = new StringTokenizer(reference, " ", true)
+        val StringBuilder sb = new StringBuilder();
+
+        while(tokenizer.hasMoreTokens) {
+            var String oneElement = tokenizer.nextToken
+            if (oneElement.contains("http://")) {
+                oneElement = asLink(oneElement)
+            }
+            sb.append(oneElement)
+        }
+        return sb.toString
+    }
+
+    def asLink(String text) {
+        val StringBuilder sb = new StringBuilder()
+        var tempText = text
+        var char lastChar = ' '
+        var boolean badEnding = false
+
+        if(text.endsWith(".") || text.endsWith(":") || text.endsWith(",")) {
+            tempText = text.substring(0, text.length - 1)
+            lastChar = text.charAt(text.length - 1)
+            badEnding = true
+        }
+        sb.append("<a href = \"")
+        sb.append(tempText)
+        sb.append("\">")
+        sb.append(tempText)
+        sb.append("</a>")
+
+        if(badEnding)
+            sb.append(lastChar)
+
+        return sb.toString
+    }
+
+    protected def formatToParagraph(String text) {
+        if(text == null || text.isEmpty)
+            return text
+
+        var formattedText = text
+        val StringBuilder sb = new StringBuilder();
+        var StringBuilder lineBuilder = new StringBuilder();
+        var boolean isFirstElementOnNewLineEmptyChar = false;
+
+        formattedText = formattedText.replace("*/", "&#42;&#47;")
+        formattedText = formattedText.replace(NEW_LINE, "")
+        formattedText = formattedText.replace("\t", "")
+        formattedText = formattedText.replaceAll(" +", " ");
+
+        val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
+
+        while(tokenizer.hasMoreElements) {
+            val nextElement = tokenizer.nextElement.toString
+
+            if(lineBuilder.length + nextElement.length > 80) {
+                if (lineBuilder.charAt(lineBuilder.length - 1) == ' ') {
+                    lineBuilder.setLength(0)
+                    lineBuilder.append(lineBuilder.substring(0, lineBuilder.length - 1))
+                }
+                if (lineBuilder.charAt(0) == ' ') {
+                    lineBuilder.setLength(0)
+                    lineBuilder.append(lineBuilder.substring(1))
+                }
+
+                sb.append(lineBuilder);
+                lineBuilder.setLength(0)
+                sb.append(NEW_LINE)
+
+                if(nextElement.toString == ' ')
+                    isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
+            }
+
+            if(isFirstElementOnNewLineEmptyChar) {
+                isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
+            }
+
+            else {
+                lineBuilder.append(nextElement)
+            }
+        }
+        sb.append(lineBuilder)
+        sb.append(NEW_LINE)
+
+        return sb.toString
+    }
+
+    def isDocumentationParametersNullOrEmtpy(GeneratedType type) {
+        var boolean isNullOrEmpty = true
+        val String typeDescription = type.description
+        val String typeReference = type.reference
+        val String typeModuleName = type.moduleName
+        val Iterable<QName> typeSchemaPath = type.schemaPath
+
+        if(typeDescription != null && !typeDescription.empty) {
+            isNullOrEmpty = false
+            return isNullOrEmpty
+        }
+        if(typeReference != null && !typeReference.empty) {
+            isNullOrEmpty = false
+            return isNullOrEmpty
+        }
+        if(typeModuleName != null && !typeModuleName.empty) {
+            isNullOrEmpty = false
+            return isNullOrEmpty
+        }
+        if(typeSchemaPath != null && !typeSchemaPath.empty) {
+            isNullOrEmpty = false
+            return isNullOrEmpty
+        }
+        return isNullOrEmpty
+    }
+
     def generateRestrictions(Type type, String paramName, Type returnType) '''
         Â«val restrictions = type.getRestrictions»
         Â«IF restrictions !== null»
index 8b465758d0691ca67c386b5c7dbef63104b3cfb9..7645504e6c7584a1f1c3d2857e0bc6197383caa2 100644 (file)
@@ -140,12 +140,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)
@@ -177,10 +177,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) {
@@ -205,7 +205,7 @@ class BuilderTemplate extends BaseTemplate {
      * @return string with JAVA source code
      */
     override body() '''
-
+        Â«wrapToDocumentation(formatDataForJavaDoc(type))»
         public class Â«type.name»«BUILDER» {
 
             Â«generateFields(false)»
@@ -319,7 +319,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>
index eb5b94c5da742df982350567d99606116e351d2a..e92f84e489ae1e3db0bea4faf4569b3ae2e8f304 100644 (file)
@@ -100,7 +100,7 @@ class ClassTemplate extends BaseTemplate {
      * @return string with class source code in JAVA format
      */
     def protected generateBody(boolean isInnerClass) '''
-        Â«type.comment.asJavadoc»
+        Â«wrapToDocumentation(formatDataForJavaDoc(type))»
         Â«generateClassDeclaration(isInnerClass)» {
             Â«suidDeclaration»
             Â«innerClassesDeclarations»
index fecae3de47dd1b7efa0fea1b694b4deeda3f5941..cc05fb49120d10dbfc12e065d76440dd837ae6f8 100644 (file)
@@ -41,17 +41,22 @@ class EnumTemplate extends BaseTemplate {
         return body
     }
     
+    def writeEnumItem(String name, int value, String description) '''
+        Â«asJavadoc(formatToParagraph(description))»
+        Â«name»(«value»)
+    '''
+
     /**
      * Template method which generates enumeration body (declaration + enumeration items).
      * 
      * @return string with the enumeration body 
      */
     override body() '''
+        Â«wrapToDocumentation(formatDataForJavaDoc(enums))»
         public enum Â«enums.name» {
-        Â«FOR v : enums.values SEPARATOR ",\n"»
-            Â«"    "»«v.name»(«v.value»)«
-        ENDFOR»;
-        
+            Â«writeEnumeration(enums)»
+
+
             int value;
             static java.util.Map<java.lang.Integer, Â«enums.name»> valueMap;
 
@@ -83,4 +88,11 @@ class EnumTemplate extends BaseTemplate {
             }
         }
     '''
+
+    def writeEnumeration(Enumeration enumeration)
+    '''
+    Â«FOR v : enumeration.values SEPARATOR ",\n" AFTER ";"»
+    Â«writeEnumItem(v.name, v.value, v.description)»«
+    ENDFOR»
+    '''
 }
index 54c2eeb45d16a6f641eee1a0c48831c64de979dc..b9210287cf07fe2a3414b5ff4ff3ba303e9925cb 100644 (file)
@@ -58,15 +58,13 @@ class InterfaceTemplate extends BaseTemplate {
         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() '''
-        Â«type.comment.asJavadoc»
+        Â«wrapToDocumentation(formatDataForJavaDoc(type))»
         public interface Â«type.name»
             Â«superInterfaces»
         {
index edce4bdcffa51bbd3174919dd3e2b4888b34e67b..dbed6c75153613df5fdb0701f947934120841101 100644 (file)
@@ -25,7 +25,7 @@ class UnionBuilderTemplate extends ClassTemplate {
     }
 
     def override body() '''
-        Â«type.comment.asJavadoc»
+        Â«wrapToDocumentation(formatDataForJavaDoc(type))»
         public class Â«type.name» {
 
             Â«generateMethods»
index 0b41762aeb07be4cab6507aee211394719dd6905..069fbe1619b75d5be2d0ccd3b01e9bf4118bd00f 100644 (file)
@@ -9,14 +9,25 @@ module bar {
     yang-version 1;
     namespace "urn:opendaylight.bar";
     prefix "bar";
+       
+       description "bar - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+       reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
 
     revision "2013-10-08" {
     }
 
     container network-topology {
+               description "network-topology - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+               reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
+               
         list topology {
+                       description "topology - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+                       reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
+                       
             key "topology-id";
             leaf topology-id {
+                               description "topology-id - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+                               reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
                 type int32;
             }
             uses link;
@@ -25,6 +36,8 @@ module bar {
 
     grouping link {
         list link {
+                       description "Link - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+                       reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
             key "link-id";
             uses link-attributes;
         }
@@ -32,8 +45,37 @@ module bar {
 
     grouping link-attributes {
         leaf link-id {
+                       description "Link-attributes - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+                       reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
             type int8;
         }
     }
+       
+       leaf inclusion-rulez {
+               description "Specified rulez description.";
+               reference "RFC 6020 http://technet.com";
+               
+               type string;
+       }
 
+       leaf inclusion-rule {
+        description "Specify how inheritance will work for this label";
+        default include;
+
+        type enumeration {
+            enum include {
+                description 
+                    "This label will be included normally in the 
+                     matching. This seems to be a little bit longer comment. I hear you very weel my darling.
+                                        Network topology is the arrangement of the various elements (links, nodes, etc.) of any other builder nodes types.";
+            }
+            enum exclude {
+                description 
+                    "This label will be excluded from the 
+                    matching.  This allows removing labels that
+                    would have otherwise been included because of
+                    inheritence rules.";
+            }
+        }
+    }
 }
index 99e66a155a4812774f689584a9b9e0871bacb957..4bdc209aa7b6f7afde77d393e203c67c4e740068 100644 (file)
@@ -19,6 +19,9 @@ module baz {
         prefix "br";
         revision-date 2013-10-08;
     }
+       
+       description "Baz - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+       reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
 
     revision "2013-10-08" {
     }
@@ -31,7 +34,12 @@ module baz {
 
     grouping link-attributes {
         container ospf-link-attributes {
+                       description "Ospf-link-attributes - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+                       reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
             leaf multi-topology-id {
+                               description "Multi-topology-id - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+                               reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
+                               
                 type uint8 {
                     range "0..127";
                 }
index a20749d56dd13d41aea70e9cd9a6e5d23bec372d..5fa313eaec10986959da870b3f6c948d5c4b9660 100644 (file)
@@ -14,6 +14,9 @@ module foo {
         prefix "br";
         revision-date 2013-10-08;
     }
+       
+       description "Foo - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+       reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
 
     revision "2013-10-08" {
     }
@@ -25,13 +28,22 @@ module foo {
 
     grouping igp-link-attributes {
         container igp-link-attributes {
+                       description "Igp-link-attributes - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+                       reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
+               
             leaf name {
+                               description "Name - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+                               reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
                 type string;
             }
             leaf-list flag {
+                               description "Flag - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+                               reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
                 type string;
             }
             leaf metric {
+                               description "Metric - Network topology is the arrangement of the various elements (links, nodes, etc.) of a computer network.[1][2] Essentially, it is the topological[3] structure of a network, and may be depicted physically or logically. Physical topology is the placement of the various components of a network, including device location and cable installation, while logical topology illustrates how data flows within a network, regardless of its physical design. Distances between nodes, physical interconnections, transmission rates, or signal types may differ between two networks, yet their topologies may be identical.";
+                               reference "RFC 6020 - http://tools.ietf.org/html/rfc6020";
                 type uint32 {
                     range "0..16777215"  {
                     }
diff --git a/code-generator/binding-model-api/src/main/java/org/opendaylight/yangtools/sal/binding/model/api/DocumentedType.java b/code-generator/binding-model-api/src/main/java/org/opendaylight/yangtools/sal/binding/model/api/DocumentedType.java
new file mode 100644 (file)
index 0000000..484d7d4
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2013 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.binding.model.api;
+
+import org.opendaylight.yangtools.yang.common.QName;
+
+/**
+ * Implementing this interface allows an object to hold information which are
+ * essential for generating java doc from type definition.
+ */
+public interface DocumentedType {
+
+    /**
+     * Returns a string that contains a human-readable textual description of
+     * type definition.
+     *
+     * @return a human-readable textual description of type definition.
+     */
+    String getDescription();
+
+    /**
+     * Returns a string that is used to specify a textual cross-reference to an
+     * external document, either another module that defines related management
+     * information, or a document that provides additional information relevant
+     * to this definition.
+     *
+     * @return a textual cross-reference to an external document.
+     */
+    String getReference();
+
+    /**
+     * Returns a list of QNames which represent schema path in schema tree from
+     * actual concrete type to the root.
+     *
+     * @return a schema path in schema tree from actual concrete schema node
+     *         identifier to the root.
+     */
+    Iterable<QName> getSchemaPath();
+
+    /**
+     * Returns the name of the module, in which generated type was specified.
+     *
+     * @return the name of the module, in which generated type was specified.
+     */
+    String getModuleName();
+}
index 9599a7af22840b45425693cabb01edb95d9bd009..9709be32def1212aa5b66ce9024f02891c9e1279 100644 (file)
@@ -9,32 +9,36 @@ package org.opendaylight.yangtools.sal.binding.model.api;
 
 import java.util.List;
 
+import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
+
 /**
  * Interface provide methods for reading data of enumeration class.
  */
 public interface Enumeration extends GeneratedType {
 
     /**
-     * 
+     *
      * Returns list of annotation definitions associated with enumeration type.
-     * 
+     *
      * @return list of annotation definitions associated with enumeration type.
-     * 
+     *
      */
+    @Override
     List<AnnotationType> getAnnotations();
 
+    @Override
     Type getParentType();
 
     /**
      * Returns list of the couples - name and value.
-     * 
+     *
      * @return list of the enumeration pairs.
      */
     List<Pair> getValues();
 
     /**
      * Formats enumeration according to rules of the programming language.
-     * 
+     *
      * @return string with source code in some programming language
      */
     String toFormattedString();
@@ -43,18 +47,18 @@ public interface Enumeration extends GeneratedType {
      * Interface is used for reading enumeration item. It means item's name and
      * its value.
      */
-    interface Pair {
+    interface Pair extends DocumentedNode {
 
         /**
          * Returns the name of the enumeration item.
-         * 
+         *
          * @return the name of the enumeration item.
          */
         String getName();
 
         /**
          * Returns value of the enumeration item.
-         * 
+         *
          * @return the value of the enumeration item.
          */
         Integer getValue();
index 4506daf98df4041732964bfabd43a47a3134d147..0e9b51ee741f42bb5952961421d046c7c52efa2a 100644 (file)
@@ -28,17 +28,17 @@ import java.util.List;
  * <li><code>method definitions</code> with specified input parameters (with
  * types) and return values</li>
  * </ul>
- * 
+ *
  * By the definition of the interface constant, enum, enclosed types and method
  * definitions MUST be public, so there is no need to specify the scope of
  * visibility.
  */
-public interface GeneratedType extends Type {
+public interface GeneratedType extends Type, DocumentedType {
 
     /**
      * Returns the parent type if Generated Type is defined as enclosing type,
      * otherwise returns <code>null</code>
-     * 
+     *
      * @return the parent type if Generated Type is defined as enclosing type,
      *         otherwise returns <code>null</code>
      */
@@ -46,35 +46,35 @@ public interface GeneratedType extends Type {
 
     /**
      * Returns comment string associated with Generated Type.
-     * 
+     *
      * @return comment string associated with Generated Type.
      */
     String getComment();
 
     /**
      * Returns List of annotation definitions associated with generated type.
-     * 
+     *
      * @return List of annotation definitions associated with generated type.
      */
     List<AnnotationType> getAnnotations();
 
     /**
      * Returns <code>true</code> if The Generated Type is defined as abstract.
-     * 
+     *
      * @return <code>true</code> if The Generated Type is defined as abstract.
      */
     boolean isAbstract();
 
     /**
      * Returns List of Types that Generated Type will implement.
-     * 
+     *
      * @return List of Types that Generated Type will implement.
      */
     List<Type> getImplements();
 
     /**
      * Returns List of enclosing Generated Types.
-     * 
+     *
      * @return List of enclosing Generated Types.
      */
     List<GeneratedType> getEnclosedTypes();
@@ -82,7 +82,7 @@ public interface GeneratedType extends Type {
     /**
      * Returns List of all Enumerator definitions associated with Generated
      * Type.
-     * 
+     *
      * @return List of all Enumerator definitions associated with Generated
      *         Type.
      */
@@ -90,16 +90,16 @@ public interface GeneratedType extends Type {
 
     /**
      * Returns List of Constant definitions associated with Generated Type.
-     * 
+     *
      * @return List of Constant definitions associated with Generated Type.
      */
     List<Constant> getConstantDefinitions();
 
     /**
      * Returns List of Method Definitions associated with Generated Type.
-     * 
+     *
      * List does not contains getters and setters for properties.
-     * 
+     *
      * @return List of Method Definitions associated with Generated Type.
      */
     List<MethodSignature> getMethodDefinitions();
@@ -107,7 +107,7 @@ public interface GeneratedType extends Type {
     /**
      * Returns List of Properties that are declared for Generated Transfer
      * Object.
-     * 
+     *
      * @return List of Properties that are declared for Generated Transfer
      *         Object.
      */
index 264b92c0da9ebf12259913a84694cbafe62cfded..a3339b9276fb701c07b50ff1538322909778f9fe 100644 (file)
@@ -14,7 +14,7 @@ import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
 /**
  * Enum Builder is interface that contains methods to build and instantiate
  * Enumeration definition.
- * 
+ *
  * @see Enumeration
  */
 public interface EnumBuilder extends Type {
@@ -25,7 +25,7 @@ public interface EnumBuilder extends Type {
      * Neither the package name or annotation name can contain <code>null</code>
      * references. In case that any of parameters contains <code>null</code> the
      * method SHOULD thrown {@link IllegalArgumentException}
-     * 
+     *
      * @param packageName
      *            Package Name of Annotation Type
      * @param name
@@ -35,14 +35,14 @@ public interface EnumBuilder extends Type {
     AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
 
     /**
-     * 
+     *
      * @param name
      * @param value
      */
-    void addValue(final String name, final Integer value);
+    void addValue(final String name, final Integer value, final String description);
 
     /**
-     * 
+     *
      * @param definingType
      * @return
      */
@@ -51,11 +51,16 @@ public interface EnumBuilder extends Type {
     /**
      * Updates this builder with data from <code>enumTypeDef</code>.
      * Specifically this data represents list of value-name pairs.
-     * 
+     *
      * @param enumTypeDef
      *            enum type definition as source of enum data for
      *            <code>enumBuilder</code>
      */
     void updateEnumPairsFromEnumTypeDef(final EnumTypeDefinition enumTypeDef);
 
+    /**
+     * @param description
+     */
+    void setDescription(final String description);
+
 }
index 22dce2cd84e89c0690cc46017ede3c83f1f71ab2..628029f02869760998d3f33618832b2f70a428c2 100644 (file)
@@ -8,8 +8,10 @@
 package org.opendaylight.yangtools.sal.binding.model.api.type.builder;
 
 import java.util.List;
+
 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
 import org.opendaylight.yangtools.sal.binding.model.api.Type;
+import org.opendaylight.yangtools.yang.common.QName;
 
 public interface GeneratedTypeBuilderBase<T extends GeneratedTypeBuilderBase<T>> extends Type {
 
@@ -179,4 +181,42 @@ public interface GeneratedTypeBuilderBase<T extends GeneratedTypeBuilderBase<T>>
      */
     boolean containsProperty(final String name);
 
+    /**
+     * Set a string that contains a human-readable textual description of type
+     * definition.
+     *
+     * @param description
+     *            a string that contains a human-readable textual description of
+     *            type definition.
+     */
+    public void setDescription(String description);
+
+    /**
+     * Set the name of the module, in which generated type was specified.
+     *
+     * @param moduleName
+     *            the name of the module
+     */
+    public void setModuleName(String moduleName);
+
+    /**
+     * Set a list of QNames which represent schema path in schema tree from
+     * actual concrete type to the root.
+     *
+     * @param schemaPath
+     *            a list of QNames which represent schema path in schema tree
+     */
+    public void setSchemaPath(Iterable<QName> schemaPath);
+
+    /**
+     * Set a string that is used to specify a textual cross-reference to an
+     * external document, either another module that defines related management
+     * information, or a document that provides additional information relevant
+     * to this definition.
+     *
+     * @param reference
+     *            a textual cross-reference to an external document.
+     */
+    public void setReference(String reference);
+
 }
index 7b1aa834f813b10b746907666a7db59cf65b95c7..cf23c844de29cfe5e5ea5d2ab36905f8a7dfb3ce 100644 (file)
@@ -14,9 +14,6 @@ import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findD
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
 
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Sets;
-import com.google.common.io.BaseEncoding;
 import java.io.Serializable;
 import java.math.BigDecimal;
 import java.math.BigInteger;
@@ -34,6 +31,7 @@ import java.util.Set;
 import java.util.TreeMap;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+
 import org.apache.commons.lang3.StringEscapeUtils;
 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
@@ -92,6 +90,10 @@ import org.opendaylight.yangtools.yang.model.util.Uint64;
 import org.opendaylight.yangtools.yang.model.util.Uint8;
 import org.opendaylight.yangtools.yang.model.util.UnionType;
 
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Sets;
+import com.google.common.io.BaseEncoding;
+
 public final class TypeProviderImpl implements TypeProvider {
     private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
 
@@ -195,8 +197,7 @@ public final class TypeProviderImpl implements TypeProvider {
         Preconditions.checkArgument(typeDefinition.getQName() != null,
                 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
         String typedefName = typeDefinition.getQName().getLocalName();
-        Preconditions.checkArgument(typedefName != null,
-                "Type Definitions Local Name cannot be NULL!");
+        Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
 
         if (typeDefinition instanceof ExtendedType) {
             returnType = javaTypeForExtendedType(typeDefinition);
@@ -549,7 +550,11 @@ public final class TypeProviderImpl implements TypeProvider {
         Module module = findParentModule(schemaContext, parentNode);
         final String basePackageName = moduleNamespaceToPackageName(module);
 
-        final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
+        final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
+        enumBuilder.setDescription(enumTypeDef.getDescription());
+        enumBuilder.setReference(enumTypeDef.getReference());
+        enumBuilder.setModuleName(module.getName());
+        enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
         return enumBuilder.toInstance(null);
     }
@@ -590,6 +595,7 @@ public final class TypeProviderImpl implements TypeProvider {
         final String enumerationName = BindingMapping.getClassName(enumName);
 
         final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
+        enumBuilder.setDescription(enumTypeDef.getDescription());
         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
         return enumBuilder.toInstance(enumBuilder);
     }
@@ -637,7 +643,8 @@ public final class TypeProviderImpl implements TypeProvider {
         for (Module modul : modules) {
             modulesArray[i++] = modul;
         }
-        final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort.sort(modulesArray);
+        final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
+                .sort(modulesArray);
 
         for (final Module module : modulesSortedByDependency) {
             Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
@@ -694,7 +701,8 @@ public final class TypeProviderImpl implements TypeProvider {
                 Type returnType = null;
                 if (innerTypeDefinition instanceof ExtendedType) {
                     ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
-                    returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName);
+                    returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName,
+                            module.getName());
                 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
                             (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
@@ -727,7 +735,7 @@ public final class TypeProviderImpl implements TypeProvider {
                 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
                     final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
-                            basePackageName, bitsTypeDefinition, typedefName);
+                            basePackageName, bitsTypeDefinition, typedefName, module.getName());
                     genTOBuilder.setTypedef(true);
                     addUnitsToGenTO(genTOBuilder, typedef.getUnits());
                     makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
@@ -735,7 +743,7 @@ public final class TypeProviderImpl implements TypeProvider {
                 } else {
                     final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
                             innerTypeDefinition, typedef);
-                    returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
+                    returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
                 }
                 if (returnType != null) {
                     final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
@@ -762,11 +770,11 @@ public final class TypeProviderImpl implements TypeProvider {
      * @return generated transfer object which represent<code>javaType</code>
      */
     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
-            final Type javaType) {
+            final Type javaType, final String moduleName) {
         Preconditions.checkNotNull(javaType, "javaType cannot be null");
         final String propertyName = "value";
 
-        final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
+        final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
         genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
         final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
         genPropBuilder.setReturnType(javaType);
@@ -846,13 +854,18 @@ public final class TypeProviderImpl implements TypeProvider {
 
         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
         final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
+        final Module module = findParentModule(schemaContext, parentNode);
 
-        final GeneratedTOBuilder unionGenTOBuilder;
+        final GeneratedTOBuilderImpl unionGenTOBuilder;
         if (typeDefName != null && !typeDefName.isEmpty()) {
             final String typeName = BindingMapping.getClassName(typeDefName);
             unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
+            unionGenTOBuilder.setDescription(typedef.getDescription());
+            unionGenTOBuilder.setReference(typedef.getReference());
+            unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
+            unionGenTOBuilder.setModuleName(module.getName());
         } else {
-            unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
+            unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
         }
 
         generatedTOBuilders.add(unionGenTOBuilder);
@@ -942,8 +955,7 @@ public final class TypeProviderImpl implements TypeProvider {
      *            list of strings with the regular expressions
      */
     private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
-            final ExtendedType unionSubtype, final List<String> regularExpressions,
-            final SchemaNode parentNode) {
+            final ExtendedType unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
         final String unionTypeName = unionSubtype.getQName().getLocalName();
         final Type genTO = findGenTO(unionTypeName, unionSubtype);
         if (genTO != null) {
@@ -995,7 +1007,8 @@ public final class TypeProviderImpl implements TypeProvider {
      *            generated TO builder which is converted to generated TO and
      *            stored
      */
-    private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
+    private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
+            final SchemaNode parentNode) {
         if (!(newTypeDef instanceof UnionType)) {
 
             final Module parentModule = findParentModule(schemaContext, parentNode);
@@ -1043,15 +1056,21 @@ public final class TypeProviderImpl implements TypeProvider {
      * @return generated TO builder which contains data from
      *         <code>typedef</code> and <code>basePackageName</code>
      */
-    private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
+    private GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName,
+            final TypeDefinition<?> typedef, final String moduleName) {
 
         final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
         final String typeDefTOName = typedef.getQName().getLocalName();
 
         if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
             final String genTOName = BindingMapping.getClassName(typeDefTOName);
-            final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
-            newType.addComment(typedef.getDescription());
+            final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
+
+            newType.setDescription(typedef.getDescription());
+            newType.setReference(typedef.getReference());
+            newType.setSchemaPath(typedef.getPath().getPathFromRoot());
+            newType.setModuleName(moduleName);
+
             return newType;
         }
         return null;
@@ -1078,7 +1097,7 @@ public final class TypeProviderImpl implements TypeProvider {
      *             </ul>
      */
     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
-            final TypeDefinition<?> typeDef, final String typeDefName) {
+            final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
 
         Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
         Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
@@ -1087,7 +1106,12 @@ public final class TypeProviderImpl implements TypeProvider {
             BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
 
             final String typeName = BindingMapping.getClassName(typeDefName);
-            final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
+            final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
+
+            genTOBuilder.setDescription(typeDef.getDescription());
+            genTOBuilder.setReference(typeDef.getReference());
+            genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
+            genTOBuilder.setModuleName(moduleName);
 
             final List<Bit> bitList = bitsTypeDefinition.getBits();
             GeneratedPropertyBuilder genPropertyBuilder;
@@ -1192,7 +1216,7 @@ public final class TypeProviderImpl implements TypeProvider {
      *             </ul>
      */
     private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
-            final ExtendedType innerExtendedType, final String basePackageName) {
+            final ExtendedType innerExtendedType, final String basePackageName, final String moduleName) {
         Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
         Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
 
@@ -1200,6 +1224,11 @@ public final class TypeProviderImpl implements TypeProvider {
         final String classTypedefName = BindingMapping.getClassName(typedefName);
         final String innerTypeDef = innerExtendedType.getQName().getLocalName();
         final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
+
+        genTOBuilder.setDescription(typedef.getDescription());
+        genTOBuilder.setReference(typedef.getReference());
+        genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
+        genTOBuilder.setModuleName(moduleName);
         genTOBuilder.setTypedef(true);
         Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
         genTOBuilder.setRestrictions(r);
@@ -1461,7 +1490,8 @@ public final class TypeProviderImpl implements TypeProvider {
         return sb.toString();
     }
 
-    private String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
+    private String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
+            final boolean isExt) {
         List<Bit> bits = new ArrayList<>(type.getBits());
         Collections.sort(bits, new Comparator<Bit>() {
             @Override
index d2ccf637d78ec6096daeb56ddbf2a3b3380ffc76..0ac89ae8da2c1d634d134bc07977877e5a9c4484 100644 (file)
@@ -117,59 +117,6 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
         return localName;
     }
 
-    /**
-     * QName Constructor.
-     *
-     * @param namespace
-     *            the namespace assigned to the YANG module
-     * @param revision
-     *            the revision of the YANG module
-     * @param localName
-     *            YANG schema identifier
-     *
-     * @deprecated Use {@link #create(URI, Date, String)} instead.
-     */
-    @Deprecated
-    public QName(final URI namespace, final Date revision, final String localName) {
-        this(QNameModule.create(namespace, revision), null, localName);
-    }
-
-    /**
-     * Construct new QName which reuses namespace, revision and prefix from
-     * base.
-     *
-     * @param base
-     * @param localName
-     * @deprecated Use {@link #create(QName, String)} instead.
-     */
-    @Deprecated
-    public QName(final QName base, final String localName) {
-        this(base.getModule(), base.getPrefix(), localName);
-    }
-
-    /**
-     * @deprecated Use {@link #create(String)} instead. This implementation is
-     *             broken.
-     */
-    @Deprecated
-    public QName(final String input) throws ParseException {
-        final String nsAndRev = input.substring(input.indexOf("(") + 1, input.indexOf(")"));
-        final Date revision;
-        final URI namespace;
-        if (nsAndRev.contains("?")) {
-            String[] splitted = nsAndRev.split("\\?");
-            namespace = URI.create(splitted[0]);
-            revision = getRevisionFormat().parse(splitted[1]);
-        } else {
-            namespace = URI.create(nsAndRev);
-            revision = null;
-        }
-
-        this.localName = checkLocalName(input.substring(input.indexOf(")") + 1));
-        this.prefix = null;
-        this.module = QNameModule.create(namespace, revision);
-    }
-
     public static QName create(final String input) {
         Matcher matcher = QNAME_PATTERN_FULL.matcher(input);
         if (matcher.matches()) {
index 53f768c072e9bb1dcae93077c08b62bd2d117f77..4b65eae332be2c6465be66d81f5605058a53e54d 100644 (file)
@@ -9,13 +9,6 @@ package org.opendaylight.yangtools.yang.data.impl.codec.xml;
 
 import static com.google.common.base.Preconditions.checkState;
 
-import com.google.common.base.Function;
-import com.google.common.base.Objects;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableList;
-
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.List;
@@ -27,6 +20,10 @@ import javax.activation.UnsupportedDataTypeException;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.dom.DOMResult;
 
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
@@ -61,8 +58,14 @@ import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NodeList;
 
-public class XmlDocumentUtils {
+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
 
+public class XmlDocumentUtils {
     private static class ElementWithSchemaContext {
         Element element;
         SchemaContext schemaContext;
@@ -81,16 +84,16 @@ public class XmlDocumentUtils {
         }
     }
 
+    public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
+    private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
+    private static final XMLOutputFactory FACTORY = XMLOutputFactory.newFactory();
     private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
-
         @Override
         public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(final TypeDefinition<?> baseType) {
             return TypeDefinitionAwareCodec.from(baseType);
         }
     };
 
-    private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
-
     /**
      * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
      * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
@@ -108,14 +111,20 @@ public class XmlDocumentUtils {
         Preconditions.checkNotNull(data);
         Preconditions.checkNotNull(schema);
 
-        Document doc = getDocument();
+        if (!(schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode)) {
+            throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
+        }
 
-        if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
-            doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
-            return doc;
-        } else {
-            throw new UnsupportedDataTypeException(
-                    "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
+        final DOMResult result = new DOMResult();
+        result.setNode(getDocument());
+        try {
+            final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
+            XmlStreamUtils.create(codecProvider).writeDocument(writer, data, (SchemaNode)schema);
+            writer.close();
+            return (Document)result.getNode();
+        } catch (XMLStreamException e) {
+            logger.error("Failed to serialize data {}", data, e);
+            return null;
         }
     }
 
@@ -141,57 +150,17 @@ public class XmlDocumentUtils {
      * @return new instance of XML Document
      * @throws UnsupportedDataTypeException
      */
-    public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider)
-            throws UnsupportedDataTypeException {
-        Preconditions.checkNotNull(data);
-
-        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-        dbf.setNamespaceAware(true);
-        Document doc = null;
+    public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider) {
+        final DOMResult result = new DOMResult();
         try {
-            DocumentBuilder bob = dbf.newDocumentBuilder();
-            doc = bob.newDocument();
-        } catch (ParserConfigurationException e) {
+            final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
+            XmlStreamUtils.create(codecProvider).writeDocument(writer, data);
+            writer.close();
+            return (Document)result.getNode();
+        } catch (XMLStreamException e) {
+            logger.error("Failed to serialize data {}", data, e);
             return null;
         }
-
-        doc.appendChild(createXmlRootElement(doc, data, null, codecProvider));
-        return doc;
-    }
-
-    private static Element createXmlRootElement(final Document doc, final Node<?> data, final SchemaNode schema,
-            final XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
-        Element itemEl = createElementFor(doc, data);
-        if (data instanceof SimpleNode<?>) {
-            if (schema instanceof LeafListSchemaNode) {
-                writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
-                        (DataSchemaNode) schema, codecProvider);
-            } else if (schema instanceof LeafSchemaNode) {
-                writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
-                        (DataSchemaNode) schema, codecProvider);
-            } else {
-                Object value = data.getValue();
-                if (value != null) {
-                    itemEl.setTextContent(String.valueOf(value));
-                }
-            }
-        } else { // CompositeNode
-            for (Node<?> child : ((CompositeNode) data).getValue()) {
-                DataSchemaNode childSchema = null;
-                if (schema instanceof DataNodeContainer) {
-                    childSchema = findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
-                    if (logger.isDebugEnabled()) {
-                        if (childSchema == null) {
-                            logger.debug("Probably the data node \""
-                                    + ((child == null) ? "" : child.getNodeType().getLocalName())
-                                    + "\" is not conform to schema");
-                        }
-                    }
-                }
-                itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
-            }
-        }
-        return itemEl;
     }
 
     private static final Element createElementFor(final Document doc, final QName qname, final Object obj) {
@@ -376,8 +345,6 @@ public class XmlDocumentUtils {
         return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
     }
 
-    public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
-
     public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
         Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
         if(attributeNodeNS == null) {
diff --git a/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/TreeNodeUtilsTest.java b/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/TreeNodeUtilsTest.java
new file mode 100644 (file)
index 0000000..9098e32
--- /dev/null
@@ -0,0 +1,187 @@
+package org.opendaylight.yangtools.yang.data.impl.schema.tree;
+
+import com.google.common.base.Optional;
+import junit.framework.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+
+import static org.junit.Assert.*;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.*;
+
+
+public class TreeNodeUtilsTest {
+    private static final Logger LOG = LoggerFactory.getLogger(TreeNodeUtilsTest.class);
+
+    private static final Short ONE_ID = 1;
+    private static final Short TWO_ID = 2;
+    private static final String TWO_ONE_NAME = "one";
+    private static final String TWO_TWO_NAME = "two";
+
+    private static final InstanceIdentifier OUTER_LIST_1_PATH = InstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+            .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, ONE_ID) //
+            .build();
+
+    private static final InstanceIdentifier OUTER_LIST_2_PATH = InstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+            .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, TWO_ID) //
+            .build();
+
+    private static final InstanceIdentifier TWO_TWO_PATH = InstanceIdentifier.builder(OUTER_LIST_2_PATH)
+            .node(TestModel.INNER_LIST_QNAME) //
+            .nodeWithKey(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, TWO_TWO_NAME) //
+            .build();
+
+    private static final MapEntryNode BAR_NODE = mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, TWO_ID) //
+            .withChild(mapNodeBuilder(TestModel.INNER_LIST_QNAME) //
+                    .withChild(mapEntry(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, TWO_ONE_NAME)) //
+                    .withChild(mapEntry(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, TWO_TWO_NAME)) //
+                    .build()) //
+            .build();
+
+    private SchemaContext schemaContext;
+    private RootModificationApplyOperation rootOper;
+
+    @Before
+    public void prepare() {
+        schemaContext = TestModel.createTestContext();
+        assertNotNull("Schema context must not be null.", schemaContext);
+        rootOper = RootModificationApplyOperation.from(SchemaAwareApplyOperation.from(schemaContext));
+    }
+
+    public NormalizedNode<?, ?> createDocumentOne() {
+        return ImmutableContainerNodeBuilder
+                .create()
+                .withNodeIdentifier(new InstanceIdentifier.NodeIdentifier(schemaContext.getQName()))
+                .withChild(createTestContainer()).build();
+
+    }
+
+    private ContainerNode createTestContainer() {
+        return ImmutableContainerNodeBuilder
+                .create()
+                .withNodeIdentifier(new InstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+                .withChild(
+                        mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
+                                .withChild(mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, ONE_ID))
+                                .withChild(BAR_NODE).build()).build();
+    }
+
+    private static <T> T assertPresentAndType(final Optional<?> potential, final Class<T> type) {
+        assertNotNull(potential);
+        assertTrue(potential.isPresent());
+        assertTrue(type.isInstance(potential.get()));
+        return type.cast(potential.get());
+    }
+
+    @Test
+    public void findNodeTestNodeFound() {
+        InMemoryDataTreeSnapshot inMemoryDataTreeSnapshot = new InMemoryDataTreeSnapshot(schemaContext,
+                TreeNodeFactory.createTreeNode(createDocumentOne(), Version.initial()), rootOper);
+        TreeNode rootNode = inMemoryDataTreeSnapshot.getRootNode();
+        Optional<TreeNode> node = TreeNodeUtils.findNode(rootNode, OUTER_LIST_1_PATH);
+        assertPresentAndType(node, TreeNode.class);
+    }
+
+    @Test
+    public void findNodeTestNodeNotFound() {
+        InMemoryDataTreeSnapshot inMemoryDataTreeSnapshot = new InMemoryDataTreeSnapshot(schemaContext,
+                TreeNodeFactory.createTreeNode(createDocumentOne(), Version.initial()), rootOper);
+        TreeNode rootNode = inMemoryDataTreeSnapshot.getRootNode();
+        final InstanceIdentifier outerList1InvalidPath = InstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+                .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 3) //
+                .build();
+        Optional<TreeNode> node = TreeNodeUtils.findNode(rootNode, outerList1InvalidPath);
+        Assert.assertFalse(node.isPresent());
+    }
+
+    @Test
+    public void findNodeCheckedTestNodeFound() {
+        InMemoryDataTreeSnapshot inMemoryDataTreeSnapshot = new InMemoryDataTreeSnapshot(schemaContext,
+                TreeNodeFactory.createTreeNode(createDocumentOne(), Version.initial()), rootOper);
+        TreeNode rootNode = inMemoryDataTreeSnapshot.getRootNode();
+        TreeNode foundNode = null;
+        try {
+            foundNode = TreeNodeUtils.findNodeChecked(rootNode, OUTER_LIST_1_PATH);
+        } catch (IllegalArgumentException e) {
+            fail("Illegal argument exception was thrown and should not have been" + e.getMessage());
+        }
+        Assert.assertNotNull(foundNode);
+    }
+
+    @Test
+    public void findNodeCheckedTestNodeNotFound() {
+        InMemoryDataTreeSnapshot inMemoryDataTreeSnapshot = new InMemoryDataTreeSnapshot(schemaContext,
+                TreeNodeFactory.createTreeNode(createDocumentOne(), Version.initial()), rootOper);
+        TreeNode rootNode = inMemoryDataTreeSnapshot.getRootNode();
+        final InstanceIdentifier outerList1InvalidPath = InstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+                .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 3) //
+                .build();
+        try {
+            TreeNodeUtils.findNodeChecked(rootNode, outerList1InvalidPath);
+            fail("Illegal argument exception should have been thrown");
+        } catch (IllegalArgumentException e) {
+            LOG.debug("Illegal argument exception was thrown as expected: '{}' - '{}'", e.getClass(), e.getMessage());
+        }
+    }
+
+    @Test
+    public void findClosestOrFirstMatchTestNodeExists() {
+        InMemoryDataTreeSnapshot inMemoryDataTreeSnapshot = new InMemoryDataTreeSnapshot(schemaContext,
+                TreeNodeFactory.createTreeNode(createDocumentOne(), Version.initial()), rootOper);
+        TreeNode rootNode = inMemoryDataTreeSnapshot.getRootNode();
+        Optional<TreeNode> expectedNode = TreeNodeUtils.findNode(rootNode, TWO_TWO_PATH);
+        assertPresentAndType(expectedNode, TreeNode.class);
+        Map.Entry<InstanceIdentifier, TreeNode> actualNode = TreeNodeUtils.findClosest(rootNode, TWO_TWO_PATH);
+        Assert.assertEquals("Expected node and actual node are not the same", expectedNode.get(), actualNode.getValue());
+    }
+
+    @Test
+    public void findClosestOrFirstMatchTestNodeDoesNotExist() {
+        InMemoryDataTreeSnapshot inMemoryDataTreeSnapshot = new InMemoryDataTreeSnapshot(schemaContext,
+                TreeNodeFactory.createTreeNode(createDocumentOne(), Version.initial()), rootOper);
+        TreeNode rootNode = inMemoryDataTreeSnapshot.getRootNode();
+        final InstanceIdentifier outerListInnerListPath = InstanceIdentifier.builder(OUTER_LIST_2_PATH)
+                .node(TestModel.INNER_LIST_QNAME)
+                .build();
+        final InstanceIdentifier twoTwoInvalidPath = InstanceIdentifier.builder(OUTER_LIST_2_PATH)
+                .node(TestModel.INNER_LIST_QNAME) //
+                .nodeWithKey(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "three") //
+                .build();
+        Optional<TreeNode> expectedNode = TreeNodeUtils.findNode(rootNode, outerListInnerListPath);
+        assertPresentAndType(expectedNode, TreeNode.class);
+        Map.Entry<InstanceIdentifier, TreeNode> actualNode = TreeNodeUtils.findClosest(rootNode, twoTwoInvalidPath);
+        Assert.assertEquals("Expected node and actual node are not the same", expectedNode.get(), actualNode.getValue());
+    }
+
+    @Test
+    public void getChildTestChildFound() {
+        InMemoryDataTreeSnapshot inMemoryDataTreeSnapshot = new InMemoryDataTreeSnapshot(schemaContext,
+                TreeNodeFactory.createTreeNode(createDocumentOne(), Version.initial()), rootOper);
+        TreeNode rootNode = inMemoryDataTreeSnapshot.getRootNode();
+        Optional<TreeNode> node = TreeNodeUtils.getChild(Optional.fromNullable(rootNode),
+                TestModel.TEST_PATH.getLastPathArgument());
+        assertPresentAndType(node, TreeNode.class);
+    }
+
+    @Test
+    public void getChildTestChildNotFound() {
+        InMemoryDataTreeSnapshot inMemoryDataTreeSnapshot = new InMemoryDataTreeSnapshot(schemaContext,
+                TreeNodeFactory.createTreeNode(createDocumentOne(), Version.initial()), rootOper);
+        TreeNode rootNode = inMemoryDataTreeSnapshot.getRootNode();
+        Optional<TreeNode> node = TreeNodeUtils.getChild(Optional.fromNullable(rootNode),
+                TestModel.OUTER_LIST_PATH.getLastPathArgument());
+        Assert.assertFalse(node.isPresent());
+    }
+}
index c4831ef3f2a56b49280ea1e29af96be1bccb6155..002746fa571d8b9616e4ca78ddfd406bcfd005ef 100644 (file)
@@ -123,7 +123,7 @@ public final class BaseTypes {
         }
         final List<QName> pathList = new ArrayList<QName>();
         for (final String path : actualPath) {
-            final QName qname = new QName(namespace, revision, path);
+            final QName qname = QName.create(namespace, revision, path);
             if (qname != null) {
                 pathList.add(qname);
             }
index 65fd92458f72564de1f9fd084490854fc4c50498..5a14d3097b7c2eb8fdf9c780e18fc3fb0582bf2e 100644 (file)
@@ -7,9 +7,9 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
+import com.google.common.base.Preconditions;
 import java.util.Collections;
 import java.util.List;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
@@ -17,8 +17,6 @@ import org.opendaylight.yangtools.yang.model.api.Status;
 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
 
-import com.google.common.base.Preconditions;
-
 /**
  * The <code>default</code> implementation of Instance Leafref Type Definition
  * interface.
@@ -27,7 +25,7 @@ import com.google.common.base.Preconditions;
  */
 public final class Leafref implements LeafrefTypeDefinition {
     private static final QName NAME = BaseTypes.constructQName("leafref");
-    private static final SchemaPath PATH = BaseTypes.schemaPath(NAME);
+    private static final SchemaPath PATH = SchemaPath.create(true, NAME);
     private static final String DESCRIPTION = "The leafref type is used to reference a particular leaf instance in the data tree.";
     private static final String REF = "https://tools.ietf.org/html/rfc6020#section-9.9";
 
index 4d31c1a2e080d89a9fbe5e296f55b242dfe23dac..5e29a76719b045fdbf60f6620dbb5610b1b9b2ad 100644 (file)
@@ -12,21 +12,13 @@ import static org.junit.Assert.assertEquals;
 import java.util.Set;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
 
 public class TwoRevisionsTest {
 
     @Test
     public void testTwoRevisions() throws Exception {
-        YangModelParser parser = new YangParserImpl();
-
         Set<Module> modules = TestUtils.loadModules(getClass().getResource("/ietf").toURI());
         assertEquals(2, TestUtils.findModules(modules, "network-topology").size());
-
-        SchemaContext schemaContext = parser.resolveSchemaContext(modules);
-        assertEquals(2, TestUtils.findModules(schemaContext.getModules(), "network-topology").size());
-
     }
 
 }
index ee2d7facbee4ceb61460ed723633f3849ce2aceb..ea33db06c1f95fe97c67fb3bfa0801ecdcd89653 100644 (file)
@@ -12,6 +12,7 @@ import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
+import com.google.common.base.Optional;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.util.ArrayList;
@@ -130,13 +131,17 @@ public class RefineHolderTest {
     @Test
     public void testMustEqualsBranch() {
         assertEquals("rh should equal to rh1", rh, rh1);
-        rh1.setMust(new MustDefinitionImpl("mustStr1", "description1", "reference1", "errorAppTag1", "errorMessage1"));
+        rh1.setMust(MustDefinitionImpl.create("mustStr1", Optional.of("description1"), Optional.of("reference1"),
+                Optional.of("errorAppTag1"), Optional.of("errorMessage1")));
         assertFalse("rh shouldn't equal to rh1", rh.equals(rh1));
-        rh.setMust(new MustDefinitionImpl("mustStr1", "description1", "reference1", "errorAppTag1", "errorMessage1"));
+        rh.setMust(MustDefinitionImpl.create("mustStr1", Optional.of("description1"), Optional.of("reference1"),
+                Optional.of("errorAppTag1"), Optional.of("errorMessage1")));
         assertEquals("rh should equal to rh1", rh, rh1);
-        rh.setMust(new MustDefinitionImpl("mustStr", "description", "reference", "errorAppTag", "errorMessage"));
+        rh.setMust(MustDefinitionImpl.create("mustStr", Optional.of("description"), Optional.of("reference"),
+                Optional.of("errorAppTag"), Optional.of("errorMessage")));
         assertFalse("rh shouldn't equal to rh1", rh.equals(rh1));
-        rh1.setMust(new MustDefinitionImpl("mustStr", "description", "reference", "errorAppTag", "errorMessage"));
+        rh1.setMust(MustDefinitionImpl.create("mustStr", Optional.of("description"), Optional.of("reference"),
+                Optional.of("errorAppTag"), Optional.of("errorMessage")));
     }
 
     @Test