2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.sal.binding.yang.types;
10 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.*;
11 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.*;
13 import java.math.BigDecimal;
14 import java.math.BigInteger;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.Comparator;
19 import java.util.Date;
20 import java.util.HashMap;
21 import java.util.List;
24 import java.util.TreeMap;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
28 import org.apache.commons.lang3.StringEscapeUtils;
29 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
30 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
31 import org.opendaylight.yangtools.binding.generator.util.Types;
32 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
33 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
34 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
35 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
36 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
37 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
38 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
39 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
40 import org.opendaylight.yangtools.sal.binding.model.api.Type;
41 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
42 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
43 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
44 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
47 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.Module;
52 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
53 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
54 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
56 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.YangNode;
58 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
61 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
69 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
72 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
73 import org.opendaylight.yangtools.yang.model.util.Int16;
74 import org.opendaylight.yangtools.yang.model.util.Int32;
75 import org.opendaylight.yangtools.yang.model.util.Int64;
76 import org.opendaylight.yangtools.yang.model.util.Int8;
77 import org.opendaylight.yangtools.yang.model.util.StringType;
78 import org.opendaylight.yangtools.yang.model.util.Uint16;
79 import org.opendaylight.yangtools.yang.model.util.Uint32;
80 import org.opendaylight.yangtools.yang.model.util.Uint64;
81 import org.opendaylight.yangtools.yang.model.util.Uint8;
82 import org.opendaylight.yangtools.yang.model.util.UnionType;
83 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
85 import com.google.common.base.Preconditions;
86 import com.google.common.io.BaseEncoding;
88 public final class TypeProviderImpl implements TypeProvider {
90 * Contains the schema data red from YANG files.
92 private final SchemaContext schemaContext;
95 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
97 private Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
100 * The map which maps schema paths to JAVA <code>Type</code>.
102 private final Map<SchemaPath, Type> referencedTypes;
105 * Creates new instance of class <code>TypeProviderImpl</code>.
107 * @param schemaContext
108 * contains the schema data red from YANG files
109 * @throws IllegalArgumentException
110 * if <code>schemaContext</code> equal null.
112 public TypeProviderImpl(final SchemaContext schemaContext) {
113 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
115 this.schemaContext = schemaContext;
116 this.genTypeDefsContextMap = new HashMap<>();
117 this.referencedTypes = new HashMap<>();
118 resolveTypeDefsFromContext();
122 * Puts <code>refType</code> to map with key <code>refTypePath</code>
125 * schema path used as the map key
127 * type which represents the map value
128 * @throws IllegalArgumentException
130 * <li>if <code>refTypePath</code> equal null</li>
131 * <li>if <code>refType</code> equal null</li>
135 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
136 Preconditions.checkArgument(refTypePath != null,
137 "Path reference of Enumeration Type Definition cannot be NULL!");
138 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
139 referencedTypes.put(refTypePath, refType);
144 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
147 * string with YANG name of type
148 * @return JAVA <code>Type</code> for YANG type <code>type</code>
149 * @see TypeProvider#javaTypeForYangType(String)
152 public Type javaTypeForYangType(String type) {
153 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
157 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
158 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
162 * Converts schema definition type <code>typeDefinition</code> to JAVA
165 * @param typeDefinition
166 * type definition which is converted to JAVA type
167 * @throws IllegalArgumentException
169 * <li>if <code>typeDefinition</code> equal null</li>
170 * <li>if Qname of <code>typeDefinition</code> equal null</li>
171 * <li>if name of <code>typeDefinition</code> equal null</li>
175 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
177 Type returnType = null;
178 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
179 if (typeDefinition.getQName() == null) {
180 throw new IllegalArgumentException(
181 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
183 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
184 "Type Definitions Local Name cannot be NULL!");
186 if (typeDefinition instanceof ExtendedType) {
187 returnType = javaTypeForExtendedType(typeDefinition);
189 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
190 if (returnType == null) {
191 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
195 // TODO: add throw exception when we will be able to resolve ALL yang
197 // if (returnType == null) {
198 // throw new IllegalArgumentException("Type Provider can't resolve " +
199 // "type for specified Type Definition " + typedefName);
205 * Returns JAVA <code>Type</code> for instances of the type
206 * <code>LeafrefTypeDefinition</code> or
207 * <code>IdentityrefTypeDefinition</code>.
209 * @param typeDefinition
210 * type definition which is converted to JAVA <code>Type</code>
211 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
213 private Type javaTypeForLeafrefOrIdentityRef(TypeDefinition<?> typeDefinition, SchemaNode parentNode) {
214 if (typeDefinition instanceof LeafrefTypeDefinition) {
215 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
216 return provideTypeForLeafref(leafref, parentNode);
217 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
218 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
219 return provideTypeForIdentityref(idref);
226 * Returns JAVA <code>Type</code> for instances of the type
227 * <code>ExtendedType</code>.
229 * @param typeDefinition
230 * type definition which is converted to JAVA <code>Type</code>
231 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
233 private Type javaTypeForExtendedType(TypeDefinition<?> typeDefinition) {
234 final String typedefName = typeDefinition.getQName().getLocalName();
235 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
236 Type returnType = null;
237 returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
238 if (returnType == null) {
239 if (baseTypeDef instanceof EnumTypeDefinition) {
240 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
241 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
243 final Module module = findParentModule(schemaContext, typeDefinition);
244 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
245 if (module != null) {
246 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
247 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
248 if (genTOs != null) {
249 returnType = genTOs.get(typedefName);
251 if (returnType == null) {
252 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
253 baseTypeDef, typeDefinition, r);
259 // TODO: add throw exception when we will be able to resolve ALL yang
261 // if (returnType == null) {
262 // throw new IllegalArgumentException("Type Provider can't resolve " +
263 // "type for specified Type Definition " + typedefName);
268 * Seeks for identity reference <code>idref</code> the JAVA
269 * <code>type</code>.<br />
273 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
274 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
277 * identityref type definition for which JAVA <code>Type</code>
279 * @return JAVA <code>Type</code> of the identity which is refrenced through
282 private Type provideTypeForIdentityref(IdentityrefTypeDefinition idref) {
283 QName baseIdQName = idref.getIdentity().getQName();
284 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
285 baseIdQName.getRevision());
286 IdentitySchemaNode identity = null;
287 for (IdentitySchemaNode id : module.getIdentities()) {
288 if (id.getQName().equals(baseIdQName)) {
292 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
294 final String basePackageName = moduleNamespaceToPackageName(module);
295 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
296 final String genTypeName = parseToClassName(identity.getQName().getLocalName());
298 Type baseType = Types.typeForClass(Class.class);
299 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
300 return Types.parameterizedTypeFor(baseType, paramType);
304 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
306 * @param typeDefinition
307 * type definition which should be converted to JAVA
309 * @return JAVA <code>Type</code> which represents
310 * <code>typeDefinition</code>
311 * @throws IllegalArgumentException
313 * <li>if <code>typeDefinition</code> equal null</li>
314 * <li>if Q name of <code>typeDefinition</code></li>
315 * <li>if name of <code>typeDefinition</code></li>
318 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
319 final SchemaNode parentNode) {
320 Type returnType = null;
321 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
322 if (typeDefinition.getQName() == null) {
323 throw new IllegalArgumentException(
324 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
326 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
327 "Type Definitions Local Name cannot be NULL!");
329 final String typedefName = typeDefinition.getQName().getLocalName();
330 if (typeDefinition instanceof ExtendedType) {
331 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
333 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
334 final Module module = findParentModule(schemaContext, parentNode);
336 if (module != null) {
337 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
338 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
339 if (genTOs != null) {
340 returnType = genTOs.get(typedefName);
349 * Gets base type definition for <code>extendTypeDef</code>. The method is
350 * recursivelly called until non <code>ExtendedType</code> type is found.
352 * @param extendTypeDef
353 * type definition for which is the base type definition sought
354 * @return type definition which is base type for <code>extendTypeDef</code>
355 * @throws IllegalArgumentException
356 * if <code>extendTypeDef</code> equal null
358 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
359 Preconditions.checkArgument(extendTypeDef != null, "Type Definiition reference cannot be NULL!");
360 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
361 if (baseTypeDef == null) {
362 return extendTypeDef;
363 } else if (baseTypeDef instanceof ExtendedType) {
364 return baseTypeDefForExtendedType(baseTypeDef);
372 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
374 * The path of <code>leafrefType</code> is followed to find referenced node
375 * and its <code>Type</code> is returned.
378 * leafref type definition for which is the type sought
379 * @return JAVA <code>Type</code> of data schema node which is referenced in
380 * <code>leafrefType</code>
381 * @throws IllegalArgumentException
383 * <li>if <code>leafrefType</code> equal null</li>
384 * <li>if path statement of <code>leafrefType</code> equal null</li>
388 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
389 Type returnType = null;
390 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
392 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
393 "The Path Statement for Leafref Type Definition cannot be NULL!");
395 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
396 final String strXPath = xpath.toString();
398 if (strXPath != null) {
399 if (strXPath.contains("[")) {
400 returnType = Types.typeForClass(Object.class);
402 final Module module = findParentModule(schemaContext, parentNode);
403 if (module != null) {
404 final SchemaNode dataNode;
405 if (xpath.isAbsolute()) {
406 dataNode = findDataSchemaNode(schemaContext, module, xpath);
408 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
411 if (leafContainsEnumDefinition(dataNode)) {
412 returnType = referencedTypes.get(dataNode.getPath());
413 } else if (leafListContainsEnumDefinition(dataNode)) {
414 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
416 returnType = resolveTypeFromDataSchemaNode(dataNode);
425 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
426 * so then checks if it is of type <code>EnumTypeDefinition</code>.
429 * data schema node for which is checked if it is leaf and if it
431 * @return boolean value
433 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
434 * <li>false - other cases</li>
437 private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
438 if (dataNode instanceof LeafSchemaNode) {
439 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
440 if (leaf.getType() instanceof EnumTypeDefinition) {
448 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
449 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
452 * data schema node for which is checked if it is leaflist and if
454 * @return boolean value
456 * <li>true - if <code>dataNode</code> is leaflist of type
458 * <li>false - other cases</li>
461 private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
462 if (dataNode instanceof LeafListSchemaNode) {
463 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
464 if (leafList.getType() instanceof EnumTypeDefinition) {
472 * Converts <code>enumTypeDef</code> to
473 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
477 * enumeration type definition which is converted to enumeration
479 * string with name which is used as the enumeration name
480 * @return enumeration type which is built with data (name, enum values)
481 * from <code>enumTypeDef</code>
482 * @throws IllegalArgumentException
484 * <li>if <code>enumTypeDef</code> equals null</li>
485 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
486 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
487 * <li>if name of <code>enumTypeDef</code> equal null</li>
490 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
491 final SchemaNode parentNode) {
492 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
493 Preconditions.checkArgument(enumTypeDef.getValues() != null,
494 "EnumTypeDefinition MUST contain at least ONE value definition!");
495 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
496 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
497 "Local Name in EnumTypeDefinition QName cannot be NULL!");
499 final String enumerationName = parseToClassName(enumName);
501 Module module = findParentModule(schemaContext, parentNode);
502 final String basePackageName = moduleNamespaceToPackageName(module);
504 final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
505 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
506 return enumBuilder.toInstance(null);
510 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
511 * taken from <code>enumTypeDef</code>.
514 * enumeration type definition is source of enumeration data for
515 * <code>typeBuilder</code>
517 * string with the name of enumeration
519 * generated type builder to which is enumeration added
520 * @return enumeration type which contains enumeration data form
521 * <code>enumTypeDef</code>
522 * @throws IllegalArgumentException
524 * <li>if <code>enumTypeDef</code> equals null</li>
525 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
526 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
527 * <li>if name of <code>enumTypeDef</code> equal null</li>
528 * <li>if name of <code>typeBuilder</code> equal null</li>
532 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
533 final GeneratedTypeBuilderBase<?> typeBuilder) {
534 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
535 Preconditions.checkArgument(enumTypeDef.getValues() != null,
536 "EnumTypeDefinition MUST contain at least ONE value definition!");
537 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
538 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
539 "Local Name in EnumTypeDefinition QName cannot be NULL!");
540 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
542 final String enumerationName = parseToClassName(enumName);
544 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
545 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
546 return enumBuilder.toInstance(enumBuilder);
550 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
553 * contains information about YANG type
554 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
556 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
557 Type returnType = null;
558 if (dataNode != null) {
559 if (dataNode instanceof LeafSchemaNode) {
560 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
561 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
562 } else if (dataNode instanceof LeafListSchemaNode) {
563 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
564 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
571 * Passes through all modules and through all its type definitions and
572 * convert it to generated types.
574 * The modules are firstly sorted by mutual dependencies. The modules are
575 * sequentially passed. All type definitions of a module are at the
576 * beginning sorted so that type definition with less amount of references
577 * to other type definition are processed first.<br />
578 * For each module is created mapping record in the map
579 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
580 * which map current module name to the map which maps type names to
581 * returned types (generated types).
584 private void resolveTypeDefsFromContext() {
585 final Set<Module> modules = schemaContext.getModules();
586 Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
587 final Module[] modulesArray = new Module[modules.size()];
589 for (Module modul : modules) {
590 modulesArray[i++] = modul;
592 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modulesArray);
594 for (final Module module : modulesSortedByDependency) {
595 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
596 if (dateTypeMap == null) {
597 dateTypeMap = new HashMap<>();
599 final Map<String, Type> typeMap = new HashMap<>();
600 dateTypeMap.put(module.getRevision(), typeMap);
601 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
604 for (final Module module : modulesSortedByDependency) {
605 if (module == null) {
608 final String moduleName = module.getName();
609 final String basePackageName = moduleNamespaceToPackageName(module);
611 final DataNodeIterator it = new DataNodeIterator(module);
612 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
613 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
615 if ((listTypeDefinitions != null) && (basePackageName != null)) {
616 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
617 typedefToGeneratedType(basePackageName, moduleName, module.getRevision(), typedef);
625 * @param basePackageName
626 * string with name of package to which the module belongs
628 * string with the name of the module for to which the
629 * <code>typedef</code> belongs
631 * type definition of the node for which should be creted JAVA
632 * <code>Type</code> (usually generated TO)
633 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
634 * <code>null</code> value if <code>basePackageName</code> or
635 * <code>modulName</code> or <code>typedef</code> or Q name of
636 * <code>typedef</code> equals <code>null</code>
638 private Type typedefToGeneratedType(final String basePackageName, final String moduleName,
639 final Date moduleRevision, final TypeDefinition<?> typedef) {
640 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
642 final String typedefName = typedef.getQName().getLocalName();
643 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
644 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
645 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
646 Type returnType = null;
647 if (innerTypeDefinition instanceof ExtendedType) {
648 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
649 returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName);
650 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
651 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
652 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
653 genTOBuilder.setTypedef(true);
654 genTOBuilder.setIsUnion(true);
655 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
656 returnType = genTOBuilder.toInstance();
657 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
658 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
659 // TODO units for typedef enum
660 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
661 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
662 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
663 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
664 basePackageName, bitsTypeDefinition, typedefName);
665 genTOBuilder.setTypedef(true);
666 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
667 returnType = genTOBuilder.toInstance();
669 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
670 innerTypeDefinition, typedef);
671 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
673 if (returnType != null) {
674 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
675 final Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
677 if (typeMap != null) {
678 typeMap.put(typedefName, returnType);
688 * Wraps base YANG type to generated TO.
690 * @param basePackageName
691 * string with name of package to which the module belongs
693 * type definition which is converted to the TO
695 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
696 * @return generated transfer object which represent<code>javaType</code>
698 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
699 final Type javaType) {
700 Preconditions.checkNotNull(javaType, "javaType cannot be null");
701 final String propertyName = "value";
703 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
704 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
705 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
706 genPropBuilder.setReturnType(javaType);
707 genTOBuilder.addEqualsIdentity(genPropBuilder);
708 genTOBuilder.addHashIdentity(genPropBuilder);
709 genTOBuilder.addToStringProperty(genPropBuilder);
710 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef instanceof ExtendedType) {
711 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
712 addStringRegExAsConstant(genTOBuilder, regExps);
714 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
715 genTOBuilder.setTypedef(true);
716 return genTOBuilder.toInstance();
720 * Converts output list of generated TO builders to one TO builder (first
721 * from list) which contains the remaining builders as its enclosing TO.
723 * @param basePackageName
724 * string with name of package to which the module belongs
726 * type definition which should be of type
727 * <code>UnionTypeDefinition</code>
729 * string with name for generated TO
730 * @return generated TO builder with the list of enclosed generated TO
733 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
734 final UnionTypeDefinition typedef, String typeDefName, SchemaNode parentNode) {
735 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
736 typedef, typeDefName, parentNode);
737 GeneratedTOBuilder resultTOBuilder = null;
738 if (!genTOBuilders.isEmpty()) {
739 resultTOBuilder = genTOBuilders.remove(0);
740 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
741 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
744 return resultTOBuilder;
748 * Converts <code>typedef</code> to generated TO with
749 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
750 * added to generated TO builder as property.
752 * @param basePackageName
753 * string with name of package to which the module belongs
755 * type definition which should be of type
756 * <code>UnionTypeDefinition</code>
758 * string with name for generated TO
759 * @return generated TO builder which represents <code>typedef</code>
760 * @throws IllegalArgumentException
762 * <li>if <code>basePackageName</code> equals null</li>
763 * <li>if <code>typedef</code> equals null</li>
764 * <li>if Q name of <code>typedef</code> equals null</li>
767 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
768 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
769 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
770 Preconditions.checkArgument(typedef != null, "Type Definition cannot be NULL!");
771 Preconditions.checkArgument(typedef.getQName() != null,
772 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
774 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
776 if (typedef != null) {
777 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
779 final GeneratedTOBuilder unionGenTOBuilder;
780 if (typeDefName != null && !typeDefName.isEmpty()) {
781 final String typeName = parseToClassName(typeDefName);
782 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
784 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
786 generatedTOBuilders.add(unionGenTOBuilder);
787 unionGenTOBuilder.setIsUnion(true);
788 final List<String> regularExpressions = new ArrayList<String>();
789 for (final TypeDefinition<?> unionType : unionTypes) {
790 final String unionTypeName = unionType.getQName().getLocalName();
791 if (unionType instanceof UnionType) {
792 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
793 basePackageName, parentNode));
794 } else if (unionType instanceof ExtendedType) {
795 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, unionTypeName,
796 regularExpressions, parentNode);
797 } else if (unionType instanceof EnumTypeDefinition) {
798 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
799 unionTypeName, unionGenTOBuilder);
800 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
802 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
803 unionType, parentNode);
804 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
807 if (!regularExpressions.isEmpty()) {
808 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
811 storeGenTO(typedef, unionGenTOBuilder, parentNode);
813 return generatedTOBuilders;
817 * Wraps code which handle case when union subtype is also of the type
818 * <code>UnionType</code>.
820 * In this case the new generated TO is created for union subtype (recursive
822 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, TypeDefinition, String)
823 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
824 * <code>parentUnionGenTOBuilder</code> is created property which type is
825 * equal to new generated TO.
827 * @param parentUnionGenTOBuilder
828 * generated TO builder to which is the property with the child
829 * union subtype added
830 * @param basePackageName
831 * string with the name of the module package
832 * @param unionSubtype
833 * type definition which represents union subtype
834 * @return list of generated TO builders. The number of the builders can be
835 * bigger one due to recursive call of
836 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
838 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
839 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
840 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
841 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
842 basePackageName, unionSubtype, newTOBuilderName, parentNode);
844 final GeneratedPropertyBuilder propertyBuilder;
845 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
846 .parseToValidParamName(newTOBuilderName));
847 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
848 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
849 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
851 return subUnionGenTOBUilders;
855 * Wraps code which handle case when union subtype is of the type
856 * <code>ExtendedType</code>.
858 * If TO for this type already exists it is used for the creation of the
859 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
860 * type is used for the property creation.
862 * @param parentUnionGenTOBuilder
863 * generated TO builder in which new property is created
864 * @param unionSubtype
865 * type definition of the <code>ExtendedType</code> type which
866 * represents union subtype
867 * @param unionTypeName
868 * string with the name for <code>unionSubtype</code>
869 * @param regularExpressions
870 * list of strings with the regular expressions
872 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
873 final ExtendedType unionSubtype, final String unionTypeName, final List<String> regularExpressions,
874 final SchemaNode parentNode) {
875 final Type genTO = findGenTO(unionTypeName, parentNode);
877 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
879 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
880 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
881 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
883 if (javaType != null) {
884 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
887 if (baseType instanceof StringType) {
888 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
894 * Searches for generated TO for <code>searchedTypeDef</code> type
895 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
897 * @param searchedTypeName
898 * string with name of <code>searchedTypeDef</code>
899 * @return generated TO for <code>searchedTypeDef</code> or
900 * <code>null</code> it it doesn't exist
902 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
903 final Module typeModule = findParentModule(schemaContext, parentNode);
904 if (typeModule != null && typeModule.getName() != null) {
905 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
906 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
907 if (genTOs != null) {
908 return genTOs.get(searchedTypeName);
915 * Stores generated TO created from <code>genTOBuilder</code> for
916 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
917 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
920 * type definition for which is <code>genTOBuilder</code> created
921 * @param genTOBuilder
922 * generated TO builder which is converted to generated TO and
925 private void storeGenTO(TypeDefinition<?> newTypeDef, GeneratedTOBuilder genTOBuilder, SchemaNode parentNode) {
926 if (!(newTypeDef instanceof UnionType)) {
928 final Module parentModule = findParentModule(schemaContext, parentNode);
929 if (parentModule != null && parentModule.getName() != null) {
930 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
931 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
932 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
938 * Adds a new property with the name <code>propertyName</code> and with type
939 * <code>type</code> to <code>unonGenTransObject</code>.
941 * @param unionGenTransObject
942 * generated TO to which should be property added
944 * JAVA <code>type</code> of the property which should be added
945 * to <code>unionGentransObject</code>
946 * @param propertyName
947 * string with name of property which should be added to
948 * <code>unionGentransObject</code>
950 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
951 final String propertyName) {
952 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
953 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
954 .addProperty(parseToValidParamName(propertyName));
955 propBuilder.setReturnType(type);
957 unionGenTransObject.addEqualsIdentity(propBuilder);
958 unionGenTransObject.addHashIdentity(propBuilder);
959 unionGenTransObject.addToStringProperty(propBuilder);
964 * Converts <code>typedef</code> to the generated TO builder.
966 * @param basePackageName
967 * string with name of package to which the module belongs
969 * type definition from which is the generated TO builder created
970 * @return generated TO builder which contains data from
971 * <code>typedef</code> and <code>basePackageName</code>
973 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
975 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
976 final String typeDefTOName = typedef.getQName().getLocalName();
978 if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
979 final String genTOName = parseToClassName(typeDefTOName);
980 final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
981 newType.addComment(typedef.getDescription());
988 * Converts <code>typeDef</code> which should be of the type
989 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
991 * All the bits of the typeDef are added to returning generated TO as
994 * @param basePackageName
995 * string with name of package to which the module belongs
997 * type definition from which is the generated TO builder created
999 * string with the name for generated TO builder
1000 * @return generated TO builder which represents <code>typeDef</code>
1001 * @throws IllegalArgumentException
1003 * <li>if <code>typeDef</code> equals null</li>
1004 * <li>if <code>basePackageName</code> equals null</li>
1007 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1008 final TypeDefinition<?> typeDef, String typeDefName) {
1010 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1011 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1013 if (typeDef instanceof BitsTypeDefinition) {
1014 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1016 final String typeName = parseToClassName(typeDefName);
1017 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1019 final List<Bit> bitList = bitsTypeDefinition.getBits();
1020 GeneratedPropertyBuilder genPropertyBuilder;
1021 for (final Bit bit : bitList) {
1022 String name = bit.getName();
1023 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
1024 genPropertyBuilder.setReadOnly(true);
1025 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1027 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1028 genTOBuilder.addHashIdentity(genPropertyBuilder);
1029 genTOBuilder.addToStringProperty(genPropertyBuilder);
1032 return genTOBuilder;
1038 * Converts the pattern constraints from <code>typedef</code> to the list of
1039 * the strings which represents these constraints.
1042 * extended type in which are the pattern constraints sought
1043 * @return list of strings which represents the constraint patterns
1044 * @throws IllegalArgumentException
1045 * if <code>typedef</code> equals null
1048 private List<String> resolveRegExpressionsFromTypedef(ExtendedType typedef) {
1049 final List<String> regExps = new ArrayList<String>();
1050 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1051 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1052 if (strTypeDef instanceof StringType) {
1053 final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1054 if (!patternConstraints.isEmpty()) {
1056 String modifiedRegEx;
1057 for (PatternConstraint patternConstraint : patternConstraints) {
1058 regEx = patternConstraint.getRegularExpression();
1059 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1060 regExps.add(modifiedRegEx);
1069 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1070 * expressions from the <code>regularExpressions</code>
1072 * @param genTOBuilder
1073 * generated TO builder to which are
1074 * <code>regular expressions</code> added
1075 * @param regularExpressions
1076 * list of string which represent regular expressions
1077 * @throws IllegalArgumentException
1079 * <li>if <code>genTOBuilder</code> equals null</li>
1080 * <li>if <code>regularExpressions</code> equals null</li>
1083 private void addStringRegExAsConstant(GeneratedTOBuilder genTOBuilder, List<String> regularExpressions) {
1084 if (genTOBuilder == null) {
1085 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1087 if (regularExpressions == null) {
1088 throw new IllegalArgumentException("List of regular expressions can't be null");
1090 if (!regularExpressions.isEmpty()) {
1091 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1092 regularExpressions);
1097 * Creates generated TO with data about inner extended type
1098 * <code>innerExtendedType</code>, about the package name
1099 * <code>typedefName</code> and about the generated TO name
1100 * <code>typedefName</code>.
1102 * It is supposed that <code>innerExtendedType</code> is already present in
1103 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1104 * be possible set it as extended type for the returning generated TO.
1106 * @param innerExtendedType
1107 * extended type which is part of some other extended type
1108 * @param basePackageName
1109 * string with the package name of the module
1110 * @param typedefName
1111 * string with the name for the generated TO
1112 * @return generated TO which extends generated TO for
1113 * <code>innerExtendedType</code>
1114 * @throws IllegalArgumentException
1116 * <li>if <code>extendedType</code> equals null</li>
1117 * <li>if <code>basePackageName</code> equals null</li>
1118 * <li>if <code>typedefName</code> equals null</li>
1121 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1122 final ExtendedType innerExtendedType, final String basePackageName) {
1123 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1124 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1126 final String typedefName = typedef.getQName().getLocalName();
1127 final String classTypedefName = parseToClassName(typedefName);
1128 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1129 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1130 genTOBuilder.setTypedef(true);
1131 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1132 genTOBuilder.setRestrictions(r);
1134 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1135 genTOBuilder.setIsUnion(true);
1138 Map<Date, Map<String, Type>> modulesByDate = null;
1139 Map<String, Type> typeMap = null;
1140 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1141 if (parentModule != null) {
1142 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1143 typeMap = modulesByDate.get(parentModule.getRevision());
1146 if (typeMap != null) {
1147 Type type = typeMap.get(innerTypeDef);
1148 if (type instanceof GeneratedTransferObject) {
1149 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1152 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1154 return genTOBuilder.toInstance();
1158 * Finds out for each type definition how many immersion (depth) is
1159 * necessary to get to the base type. Every type definition is inserted to
1160 * the map which key is depth and value is list of type definitions with
1161 * equal depth. In next step are lists from this map concatenated to one
1162 * list in ascending order according to their depth. All type definitions
1163 * are in the list behind all type definitions on which depends.
1165 * @param unsortedTypeDefinitions
1166 * list of type definitions which should be sorted by depth
1167 * @return list of type definitions sorted according their each other
1168 * dependencies (type definitions which are depend on other type
1169 * definitions are in list behind them).
1171 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1172 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1173 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1175 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1176 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1177 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1178 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1179 if (typeDefinitionsConcreteDepth == null) {
1180 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1181 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1183 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1185 // keys are in ascending order
1186 Set<Integer> depths = typeDefinitionsDepths.keySet();
1187 for (Integer depth : depths) {
1188 sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1191 return sortedTypeDefinition;
1195 * Returns how many immersion is necessary to get from the type definition
1198 * @param typeDefinition
1199 * type definition for which is depth sought.
1200 * @return number of immersions which are necessary to get from the type
1201 * definition to the base type
1203 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1204 if (typeDefinition == null) {
1208 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1210 if (baseType instanceof ExtendedType) {
1211 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1212 } else if (baseType instanceof UnionType) {
1213 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1214 int maxChildDepth = 0;
1216 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1217 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1218 if (childDepth > maxChildDepth) {
1219 maxChildDepth = childDepth;
1222 return maxChildDepth;
1228 * Returns string which contains the same value as <code>name</code> but
1229 * integer suffix is incremented by one. If <code>name</code> contains no
1230 * number suffix then number 1 is added.
1233 * string with name of augmented node
1234 * @return string with the number suffix incremented by one (or 1 is added)
1236 private String provideAvailableNameForGenTOBuilder(String name) {
1237 Pattern searchedPattern = Pattern.compile("[0-9]+\\z");
1238 Matcher mtch = searchedPattern.matcher(name);
1240 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1241 return name.substring(0, mtch.start()) + newSuffix;
1247 private void addUnitsToGenTO(GeneratedTOBuilder to, String units) {
1248 if (units != null && !units.isEmpty()) {
1249 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1250 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1251 prop.setReturnType(Types.STRING);
1252 to.addToStringProperty(prop);
1257 public String getTypeDefaultConstruction(LeafSchemaNode node) {
1258 return getTypeDefaultConstruction(node, node.getDefault());
1261 public String getTypeDefaultConstruction(LeafSchemaNode node, String defaultValue) {
1262 TypeDefinition<?> type = node.getType();
1263 QName typeQName = type.getQName();
1264 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1265 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of " + node);
1266 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of "
1269 StringBuilder sb = new StringBuilder();
1270 String result = null;
1271 if (base instanceof BinaryTypeDefinition) {
1272 result = binaryToDef(defaultValue);
1273 } else if (base instanceof BitsTypeDefinition) {
1276 YangNode parent = node.getParent();
1277 if (parent instanceof Module) {
1278 parentName = parseToClassName(((Module) parent).getName()) + "Data";
1279 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName((Module) parent);
1280 className = basePackageName + "." + parentName + "." + parseToClassName(node.getQName().getLocalName());
1282 Module parentModule = getParentModule(node);
1283 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1284 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1285 parentName = parseToClassName(((SchemaNode) parent).getQName().getLocalName());
1286 className = packageName + "." + parentName + "." + parseToClassName(node.getQName().getLocalName());
1288 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1289 } else if (base instanceof BooleanTypeDefinition) {
1290 result = typeToDef(Boolean.class, defaultValue);
1291 } else if (base instanceof DecimalTypeDefinition) {
1292 result = typeToDef(BigDecimal.class, defaultValue);
1293 } else if (base instanceof EmptyTypeDefinition) {
1294 result = typeToDef(Boolean.class, defaultValue);
1295 } else if (base instanceof EnumTypeDefinition) {
1296 char[] defValArray = defaultValue.toCharArray();
1297 char first = Character.toUpperCase(defaultValue.charAt(0));
1298 defValArray[0] = first;
1299 String newDefVal = new String(defValArray);
1301 if (type instanceof ExtendedType) {
1302 QName qname = type.getPath().getPath().get(0);
1303 Module m = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
1304 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1305 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1306 className = packageName + "." + parseToClassName(typeQName.getLocalName());
1308 Module parentModule = getParentModule(node);
1309 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1310 String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
1311 className = packageName + "." + parseToClassName(node.getQName().getLocalName());
1313 result = className + "." + newDefVal;
1314 } else if (base instanceof IdentityrefTypeDefinition) {
1315 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1316 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1317 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1318 } else if (base instanceof Int8) {
1319 result = typeToDef(Byte.class, defaultValue);
1320 } else if (base instanceof Int16) {
1321 result = typeToDef(Short.class, defaultValue);
1322 } else if (base instanceof Int32) {
1323 result = typeToDef(Integer.class, defaultValue);
1324 } else if (base instanceof Int64) {
1325 result = typeToDef(Long.class, defaultValue);
1326 } else if (base instanceof LeafrefTypeDefinition) {
1327 result = leafrefToDef(node, (LeafrefTypeDefinition) base);
1328 } else if (base instanceof StringTypeDefinition) {
1329 result = "\"" + defaultValue + "\"";
1330 } else if (base instanceof Uint8) {
1331 result = typeToDef(Short.class, defaultValue);
1332 } else if (base instanceof Uint16) {
1333 result = typeToDef(Integer.class, defaultValue);
1334 } else if (base instanceof Uint32) {
1335 result = typeToDef(Long.class, defaultValue);
1336 } else if (base instanceof Uint64) {
1337 result = typeToDef(BigInteger.class, defaultValue);
1338 } else if (base instanceof UnionTypeDefinition) {
1339 throw new UnsupportedOperationException("Cannot get default construction for union type");
1345 if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)) {
1346 QName qname = type.getPath().getPath().get(0);
1347 Module m = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
1348 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1349 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1350 String className = packageName + "." + parseToClassName(typeQName.getLocalName());
1351 sb.insert(0, "new " + className + "(");
1352 sb.insert(sb.length(), ")");
1355 return sb.toString();
1358 private String typeToDef(Class<?> clazz, String defaultValue) {
1359 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1362 private String binaryToDef(String defaultValue) {
1363 StringBuilder sb = new StringBuilder();
1364 BaseEncoding en = BaseEncoding.base64();
1365 byte[] encoded = en.decode(defaultValue);
1366 sb.append("new byte[] {");
1367 for (int i = 0; i < encoded.length; i++) {
1368 sb.append(encoded[i]);
1369 if (i != encoded.length - 1) {
1374 return sb.toString();
1377 private String bitsToDef(BitsTypeDefinition type, String className, String defaultValue, boolean isExt) {
1378 List<Bit> bits = new ArrayList<>(type.getBits());
1379 Collections.sort(bits, new Comparator<Bit>() {
1381 public int compare(Bit o1, Bit o2) {
1382 return o1.getName().compareTo(o2.getName());
1385 StringBuilder sb = new StringBuilder();
1386 sb.append(isExt ? "" : "new " + className + "(");
1387 for (int i = 0; i < bits.size(); i++) {
1388 if (bits.get(i).getName().equals(defaultValue)) {
1393 if (i != bits.size() - 1) {
1397 sb.append(isExt ? "" : ")");
1398 return sb.toString();
1401 private Module getParentModule(YangNode node) {
1402 if (node instanceof Module) {
1403 return (Module) node;
1406 YangNode parent = null;
1407 if (node instanceof DataSchemaNode) {
1408 parent = ((DataSchemaNode) node).getParent();
1409 } else if (node instanceof DataNodeContainer) {
1410 parent = ((DataNodeContainer) node).getParent();
1415 while (parent != null && !(parent instanceof Module)) {
1416 if (parent instanceof DataSchemaNode) {
1417 parent = ((DataSchemaNode) parent).getParent();
1418 } else if (parent instanceof DataNodeContainer) {
1419 parent = ((DataNodeContainer) parent).getParent();
1424 return (Module) parent;
1427 private String leafrefToDef(LeafSchemaNode parentNode, LeafrefTypeDefinition leafrefType) {
1428 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1429 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1430 "The Path Statement for Leafref Type Definition cannot be NULL!");
1432 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1433 final String strXPath = xpath.toString();
1435 if (strXPath != null) {
1436 if (strXPath.contains("[")) {
1437 return "new java.lang.Object()";
1439 final Module module = findParentModule(schemaContext, parentNode);
1440 if (module != null) {
1441 final SchemaNode dataNode;
1442 if (xpath.isAbsolute()) {
1443 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1445 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1447 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, parentNode.getDefault());
1457 public String getConstructorPropertyName(SchemaNode node) {
1458 if (node instanceof TypeDefinition<?>) {