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.AugmentationSchema;
47 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
48 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
49 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
52 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.Module;
56 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
57 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
58 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
60 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.UsesNode;
62 import org.opendaylight.yangtools.yang.model.api.YangNode;
63 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
66 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
69 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
74 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
77 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
78 import org.opendaylight.yangtools.yang.model.util.Int16;
79 import org.opendaylight.yangtools.yang.model.util.Int32;
80 import org.opendaylight.yangtools.yang.model.util.Int64;
81 import org.opendaylight.yangtools.yang.model.util.Int8;
82 import org.opendaylight.yangtools.yang.model.util.StringType;
83 import org.opendaylight.yangtools.yang.model.util.Uint16;
84 import org.opendaylight.yangtools.yang.model.util.Uint32;
85 import org.opendaylight.yangtools.yang.model.util.Uint64;
86 import org.opendaylight.yangtools.yang.model.util.Uint8;
87 import org.opendaylight.yangtools.yang.model.util.UnionType;
88 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
90 import com.google.common.base.Preconditions;
91 import com.google.common.io.BaseEncoding;
93 public final class TypeProviderImpl implements TypeProvider {
95 * Contains the schema data red from YANG files.
97 private final SchemaContext schemaContext;
100 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
102 private Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
105 * The map which maps schema paths to JAVA <code>Type</code>.
107 private final Map<SchemaPath, Type> referencedTypes;
110 * Creates new instance of class <code>TypeProviderImpl</code>.
112 * @param schemaContext
113 * contains the schema data red from YANG files
114 * @throws IllegalArgumentException
115 * if <code>schemaContext</code> equal null.
117 public TypeProviderImpl(final SchemaContext schemaContext) {
118 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
120 this.schemaContext = schemaContext;
121 this.genTypeDefsContextMap = new HashMap<>();
122 this.referencedTypes = new HashMap<>();
123 resolveTypeDefsFromContext();
127 * Puts <code>refType</code> to map with key <code>refTypePath</code>
130 * schema path used as the map key
132 * type which represents the map value
133 * @throws IllegalArgumentException
135 * <li>if <code>refTypePath</code> equal null</li>
136 * <li>if <code>refType</code> equal null</li>
140 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
141 Preconditions.checkArgument(refTypePath != null,
142 "Path reference of Enumeration Type Definition cannot be NULL!");
143 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
144 referencedTypes.put(refTypePath, refType);
149 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
152 * string with YANG name of type
153 * @return JAVA <code>Type</code> for YANG type <code>type</code>
154 * @see TypeProvider#javaTypeForYangType(String)
157 public Type javaTypeForYangType(String type) {
158 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
162 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
163 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
167 * Converts schema definition type <code>typeDefinition</code> to JAVA
170 * @param typeDefinition
171 * type definition which is converted to JAVA type
172 * @throws IllegalArgumentException
174 * <li>if <code>typeDefinition</code> equal null</li>
175 * <li>if Q name of <code>typeDefinition</code> equal null</li>
176 * <li>if name of <code>typeDefinition</code> equal null</li>
180 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode, Restrictions r) {
181 Type returnType = null;
182 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
183 if (typeDefinition.getQName() == null) {
184 throw new IllegalArgumentException(
185 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
187 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
188 "Type Definitions Local Name cannot be NULL!");
190 if (typeDefinition instanceof ExtendedType) {
191 returnType = javaTypeForExtendedType(typeDefinition);
193 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
194 if (returnType == null) {
195 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
199 // TODO: add throw exception when we will be able to resolve ALL yang
201 // if (returnType == null) {
202 // throw new IllegalArgumentException("Type Provider can't resolve " +
203 // "type for specified Type Definition " + typedefName);
209 * Returns JAVA <code>Type</code> for instances of the type
210 * <code>LeafrefTypeDefinition</code> or
211 * <code>IdentityrefTypeDefinition</code>.
213 * @param typeDefinition
214 * type definition which is converted to JAVA <code>Type</code>
215 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
217 private Type javaTypeForLeafrefOrIdentityRef(TypeDefinition<?> typeDefinition, SchemaNode parentNode) {
218 if (typeDefinition instanceof LeafrefTypeDefinition) {
219 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
220 return provideTypeForLeafref(leafref, parentNode);
221 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
222 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
223 return provideTypeForIdentityref(idref);
230 * Returns JAVA <code>Type</code> for instances of the type
231 * <code>ExtendedType</code>.
233 * @param typeDefinition
234 * type definition which is converted to JAVA <code>Type</code>
235 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
237 private Type javaTypeForExtendedType(TypeDefinition<?> typeDefinition) {
238 final String typedefName = typeDefinition.getQName().getLocalName();
239 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
240 Type returnType = null;
241 returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
242 if (returnType == null) {
243 if (baseTypeDef instanceof EnumTypeDefinition) {
244 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
245 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
247 final Module module = findParentModule(schemaContext, typeDefinition);
248 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
249 if (module != null) {
250 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
251 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
252 if (genTOs != null) {
253 returnType = genTOs.get(typedefName);
255 if (returnType == null) {
256 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
257 baseTypeDef, typeDefinition, r);
263 // TODO: add throw exception when we will be able to resolve ALL yang
265 // if (returnType == null) {
266 // throw new IllegalArgumentException("Type Provider can't resolve " +
267 // "type for specified Type Definition " + typedefName);
272 * Seeks for identity reference <code>idref</code> the JAVA
273 * <code>type</code>.<br />
277 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
278 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
281 * identityref type definition for which JAVA <code>Type</code>
283 * @return JAVA <code>Type</code> of the identity which is refrenced through
286 private Type provideTypeForIdentityref(IdentityrefTypeDefinition idref) {
287 QName baseIdQName = idref.getIdentity().getQName();
288 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
289 baseIdQName.getRevision());
290 IdentitySchemaNode identity = null;
291 for (IdentitySchemaNode id : module.getIdentities()) {
292 if (id.getQName().equals(baseIdQName)) {
296 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
298 final String basePackageName = moduleNamespaceToPackageName(module);
299 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
300 final String genTypeName = parseToClassName(identity.getQName().getLocalName());
302 Type baseType = Types.typeForClass(Class.class);
303 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
304 return Types.parameterizedTypeFor(baseType, paramType);
308 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
310 * @param typeDefinition
311 * type definition which should be converted to JAVA
313 * @return JAVA <code>Type</code> which represents
314 * <code>typeDefinition</code>
315 * @throws IllegalArgumentException
317 * <li>if <code>typeDefinition</code> equal null</li>
318 * <li>if Q name of <code>typeDefinition</code></li>
319 * <li>if name of <code>typeDefinition</code></li>
322 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
323 final SchemaNode parentNode) {
324 Type returnType = null;
325 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
326 if (typeDefinition.getQName() == null) {
327 throw new IllegalArgumentException(
328 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
330 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
331 "Type Definitions Local Name cannot be NULL!");
333 final String typedefName = typeDefinition.getQName().getLocalName();
334 if (typeDefinition instanceof ExtendedType) {
335 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
337 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
338 final Module module = findParentModule(schemaContext, parentNode);
340 if (module != null) {
341 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
342 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
343 if (genTOs != null) {
344 returnType = genTOs.get(typedefName);
353 * Gets base type definition for <code>extendTypeDef</code>. The method is
354 * recursivelly called until non <code>ExtendedType</code> type is found.
356 * @param extendTypeDef
357 * type definition for which is the base type definition sought
358 * @return type definition which is base type for <code>extendTypeDef</code>
359 * @throws IllegalArgumentException
360 * if <code>extendTypeDef</code> equal null
362 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
363 Preconditions.checkArgument(extendTypeDef != null, "Type Definiition reference cannot be NULL!");
364 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
365 if (baseTypeDef instanceof ExtendedType) {
366 return baseTypeDefForExtendedType(baseTypeDef);
374 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
376 * The path of <code>leafrefType</code> is followed to find referenced node
377 * and its <code>Type</code> is returned.
380 * leafref type definition for which is the type sought
381 * @return JAVA <code>Type</code> of data schema node which is referenced in
382 * <code>leafrefType</code>
383 * @throws IllegalArgumentException
385 * <li>if <code>leafrefType</code> equal null</li>
386 * <li>if path statement of <code>leafrefType</code> equal null</li>
390 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
391 Type returnType = null;
392 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
394 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
395 "The Path Statement for Leafref Type Definition cannot be NULL!");
397 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
398 final String strXPath = xpath.toString();
400 if (strXPath != null) {
401 if (strXPath.contains("[")) {
402 returnType = Types.typeForClass(Object.class);
404 final Module module = findParentModule(schemaContext, parentNode);
405 if (module != null) {
406 final SchemaNode dataNode;
407 if (xpath.isAbsolute()) {
408 dataNode = findDataSchemaNode(schemaContext, module, xpath);
410 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
413 if (leafContainsEnumDefinition(dataNode)) {
414 returnType = referencedTypes.get(dataNode.getPath());
415 } else if (leafListContainsEnumDefinition(dataNode)) {
416 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
418 returnType = resolveTypeFromDataSchemaNode(dataNode);
427 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
428 * so then checks if it is of type <code>EnumTypeDefinition</code>.
431 * data schema node for which is checked if it is leaf and if it
433 * @return boolean value
435 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
436 * <li>false - other cases</li>
439 private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
440 if (dataNode instanceof LeafSchemaNode) {
441 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
442 if (leaf.getType() instanceof EnumTypeDefinition) {
450 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
451 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
454 * data schema node for which is checked if it is leaflist and if
456 * @return boolean value
458 * <li>true - if <code>dataNode</code> is leaflist of type
460 * <li>false - other cases</li>
463 private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
464 if (dataNode instanceof LeafListSchemaNode) {
465 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
466 if (leafList.getType() instanceof EnumTypeDefinition) {
474 * Converts <code>enumTypeDef</code> to
475 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
479 * enumeration type definition which is converted to enumeration
481 * string with name which is used as the enumeration name
482 * @return enumeration type which is built with data (name, enum values)
483 * from <code>enumTypeDef</code>
484 * @throws IllegalArgumentException
486 * <li>if <code>enumTypeDef</code> equals null</li>
487 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
488 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
489 * <li>if name of <code>enumTypeDef</code> equal null</li>
492 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
493 final SchemaNode parentNode) {
494 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
495 Preconditions.checkArgument(enumTypeDef.getValues() != null,
496 "EnumTypeDefinition MUST contain at least ONE value definition!");
497 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
498 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
499 "Local Name in EnumTypeDefinition QName cannot be NULL!");
501 final String enumerationName = parseToClassName(enumName);
503 Module module = findParentModule(schemaContext, parentNode);
504 final String basePackageName = moduleNamespaceToPackageName(module);
506 final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
507 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
508 return enumBuilder.toInstance(null);
512 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
513 * taken from <code>enumTypeDef</code>.
516 * enumeration type definition is source of enumeration data for
517 * <code>typeBuilder</code>
519 * string with the name of enumeration
521 * generated type builder to which is enumeration added
522 * @return enumeration type which contains enumeration data form
523 * <code>enumTypeDef</code>
524 * @throws IllegalArgumentException
526 * <li>if <code>enumTypeDef</code> equals null</li>
527 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
528 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
529 * <li>if name of <code>enumTypeDef</code> equal null</li>
530 * <li>if name of <code>typeBuilder</code> equal null</li>
534 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
535 final GeneratedTypeBuilderBase<?> typeBuilder) {
536 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
537 Preconditions.checkArgument(enumTypeDef.getValues() != null,
538 "EnumTypeDefinition MUST contain at least ONE value definition!");
539 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
540 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
541 "Local Name in EnumTypeDefinition QName cannot be NULL!");
542 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
544 final String enumerationName = parseToClassName(enumName);
546 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
547 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
548 return enumBuilder.toInstance(enumBuilder);
552 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
555 * contains information about YANG type
556 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
558 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
559 Type returnType = null;
560 if (dataNode != null) {
561 if (dataNode instanceof LeafSchemaNode) {
562 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
563 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
564 } else if (dataNode instanceof LeafListSchemaNode) {
565 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
566 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
573 * Passes through all modules and through all its type definitions and
574 * convert it to generated types.
576 * The modules are firstly sorted by mutual dependencies. The modules are
577 * sequentially passed. All type definitions of a module are at the
578 * beginning sorted so that type definition with less amount of references
579 * to other type definition are processed first.<br />
580 * For each module is created mapping record in the map
581 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
582 * which map current module name to the map which maps type names to
583 * returned types (generated types).
586 private void resolveTypeDefsFromContext() {
587 final Set<Module> modules = schemaContext.getModules();
588 Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
589 final Module[] modulesArray = new Module[modules.size()];
591 for (Module modul : modules) {
592 modulesArray[i++] = modul;
594 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modulesArray);
596 for (final Module module : modulesSortedByDependency) {
597 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
598 if (dateTypeMap == null) {
599 dateTypeMap = new HashMap<>();
601 final Map<String, Type> typeMap = new HashMap<>();
602 dateTypeMap.put(module.getRevision(), typeMap);
603 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
606 for (final Module module : modulesSortedByDependency) {
607 if (module == null) {
610 final String moduleName = module.getName();
611 final String basePackageName = moduleNamespaceToPackageName(module);
613 final DataNodeIterator it = new DataNodeIterator(module);
614 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
615 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
617 if ((listTypeDefinitions != null) && (basePackageName != null)) {
618 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
619 typedefToGeneratedType(basePackageName, moduleName, module.getRevision(), typedef);
627 * @param basePackageName
628 * string with name of package to which the module belongs
630 * string with the name of the module for to which the
631 * <code>typedef</code> belongs
633 * type definition of the node for which should be creted JAVA
634 * <code>Type</code> (usually generated TO)
635 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
636 * <code>null</code> value if <code>basePackageName</code> or
637 * <code>modulName</code> or <code>typedef</code> or Q name of
638 * <code>typedef</code> equals <code>null</code>
640 private Type typedefToGeneratedType(final String basePackageName, final String moduleName, final Date moduleRevision,
641 final TypeDefinition<?> typedef) {
642 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
644 final String typedefName = typedef.getQName().getLocalName();
645 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
646 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
647 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
648 Type returnType = null;
649 if (innerTypeDefinition instanceof ExtendedType) {
650 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
651 returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName);
652 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
653 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
654 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
655 genTOBuilder.setTypedef(true);
656 genTOBuilder.setIsUnion(true);
657 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
658 returnType = genTOBuilder.toInstance();
659 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
660 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
661 // TODO units for typedef enum
662 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
663 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
664 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
665 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
666 basePackageName, bitsTypeDefinition, typedefName);
667 genTOBuilder.setTypedef(true);
668 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
669 returnType = genTOBuilder.toInstance();
671 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
672 innerTypeDefinition, typedef);
673 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
675 if (returnType != null) {
676 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
677 final Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
680 if (typeMap != null) {
681 typeMap.put(typedefName, returnType);
691 * Wraps base YANG type to generated TO.
693 * @param basePackageName
694 * string with name of package to which the module belongs
696 * type definition which is converted to the TO
698 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
699 * @return generated transfer object which represent<code>javaType</code>
701 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
702 final Type javaType) {
703 Preconditions.checkNotNull(javaType, "javaType cannot be null");
704 final String propertyName = "value";
706 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
707 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
708 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
709 genPropBuilder.setReturnType(javaType);
710 genTOBuilder.addEqualsIdentity(genPropBuilder);
711 genTOBuilder.addHashIdentity(genPropBuilder);
712 genTOBuilder.addToStringProperty(genPropBuilder);
713 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef instanceof ExtendedType) {
714 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
715 addStringRegExAsConstant(genTOBuilder, regExps);
717 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
718 genTOBuilder.setTypedef(true);
719 return genTOBuilder.toInstance();
723 * Converts output list of generated TO builders to one TO builder (first
724 * from list) which contains the remaining builders as its enclosing TO.
726 * @param basePackageName
727 * string with name of package to which the module belongs
729 * type definition which should be of type
730 * <code>UnionTypeDefinition</code>
732 * string with name for generated TO
733 * @return generated TO builder with the list of enclosed generated TO
736 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
737 final UnionTypeDefinition typedef, String typeDefName, SchemaNode parentNode) {
738 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
739 typedef, typeDefName, parentNode);
740 GeneratedTOBuilder resultTOBuilder = null;
741 if (!genTOBuilders.isEmpty()) {
742 resultTOBuilder = genTOBuilders.remove(0);
743 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
744 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
747 return resultTOBuilder;
751 * Converts <code>typedef</code> to generated TO with
752 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
753 * added to generated TO builder as property.
755 * @param basePackageName
756 * string with name of package to which the module belongs
758 * type definition which should be of type
759 * <code>UnionTypeDefinition</code>
761 * string with name for generated TO
762 * @return generated TO builder which represents <code>typedef</code>
763 * @throws IllegalArgumentException
765 * <li>if <code>basePackageName</code> equals null</li>
766 * <li>if <code>typedef</code> equals null</li>
767 * <li>if Q name of <code>typedef</code> equals null</li>
770 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
771 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
772 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
773 Preconditions.checkArgument(typedef != null, "Type Definition cannot be NULL!");
774 Preconditions.checkArgument(typedef.getQName() != null,
775 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
777 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
779 if (typedef != null) {
780 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
782 final GeneratedTOBuilder unionGenTOBuilder;
783 if (typeDefName != null && !typeDefName.isEmpty()) {
784 final String typeName = parseToClassName(typeDefName);
785 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
787 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
789 generatedTOBuilders.add(unionGenTOBuilder);
790 unionGenTOBuilder.setIsUnion(true);
791 final List<String> regularExpressions = new ArrayList<String>();
792 for (final TypeDefinition<?> unionType : unionTypes) {
793 final String unionTypeName = unionType.getQName().getLocalName();
794 if (unionType instanceof UnionType) {
795 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
796 basePackageName, parentNode));
797 } else if (unionType instanceof ExtendedType) {
798 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, unionTypeName,
799 regularExpressions, parentNode);
800 } else if (unionType instanceof EnumTypeDefinition) {
801 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
802 unionTypeName, unionGenTOBuilder);
803 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
805 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
806 unionType, parentNode);
807 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
810 if (!regularExpressions.isEmpty()) {
811 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
814 storeGenTO(typedef, unionGenTOBuilder, parentNode);
816 return generatedTOBuilders;
820 * Wraps code which handle case when union subtype is also of the type
821 * <code>UnionType</code>.
823 * In this case the new generated TO is created for union subtype (recursive
825 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, TypeDefinition, String)
826 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
827 * <code>parentUnionGenTOBuilder</code> is created property which type is
828 * equal to new generated TO.
830 * @param parentUnionGenTOBuilder
831 * generated TO builder to which is the property with the child
832 * union subtype added
833 * @param basePackageName
834 * string with the name of the module package
835 * @param unionSubtype
836 * type definition which represents union subtype
837 * @return list of generated TO builders. The number of the builders can be
838 * bigger one due to recursive call of
839 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
841 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
842 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
843 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
844 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
845 basePackageName, unionSubtype, newTOBuilderName, parentNode);
847 final GeneratedPropertyBuilder propertyBuilder;
848 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
849 .parseToValidParamName(newTOBuilderName));
850 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
851 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
852 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
854 return subUnionGenTOBUilders;
858 * Wraps code which handle case when union subtype is of the type
859 * <code>ExtendedType</code>.
861 * If TO for this type already exists it is used for the creation of the
862 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
863 * type is used for the property creation.
865 * @param parentUnionGenTOBuilder
866 * generated TO builder in which new property is created
867 * @param unionSubtype
868 * type definition of the <code>ExtendedType</code> type which
869 * represents union subtype
870 * @param unionTypeName
871 * string with the name for <code>unionSubtype</code>
872 * @param regularExpressions
873 * list of strings with the regular expressions
875 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
876 final ExtendedType unionSubtype, final String unionTypeName, final List<String> regularExpressions,
877 final SchemaNode parentNode) {
878 final Type genTO = findGenTO(unionTypeName, parentNode);
880 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
882 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
883 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
884 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
886 if (javaType != null) {
887 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
890 if (baseType instanceof StringType) {
891 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
897 * Searches for generated TO for <code>searchedTypeDef</code> type
898 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
900 * @param searchedTypeName
901 * string with name of <code>searchedTypeDef</code>
902 * @return generated TO for <code>searchedTypeDef</code> or
903 * <code>null</code> it it doesn't exist
905 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
906 final Module typeModule = findParentModule(schemaContext, parentNode);
907 if (typeModule != null && typeModule.getName() != null) {
908 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
909 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
910 if (genTOs != null) {
911 return genTOs.get(searchedTypeName);
918 * Stores generated TO created from <code>genTOBuilder</code> for
919 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
920 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
923 * type definition for which is <code>genTOBuilder</code> created
924 * @param genTOBuilder
925 * generated TO builder which is converted to generated TO and
928 private void storeGenTO(TypeDefinition<?> newTypeDef, GeneratedTOBuilder genTOBuilder, SchemaNode parentNode) {
929 if (!(newTypeDef instanceof UnionType)) {
931 final Module parentModule = findParentModule(schemaContext, parentNode);
932 if (parentModule != null && parentModule.getName() != null) {
933 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
934 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
935 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
941 * Adds a new property with the name <code>propertyName</code> and with type
942 * <code>type</code> to <code>unonGenTransObject</code>.
944 * @param unionGenTransObject
945 * generated TO to which should be property added
947 * JAVA <code>type</code> of the property which should be added
948 * to <code>unionGentransObject</code>
949 * @param propertyName
950 * string with name of property which should be added to
951 * <code>unionGentransObject</code>
953 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
954 final String propertyName) {
955 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
956 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
957 .addProperty(parseToValidParamName(propertyName));
958 propBuilder.setReturnType(type);
960 unionGenTransObject.addEqualsIdentity(propBuilder);
961 unionGenTransObject.addHashIdentity(propBuilder);
962 unionGenTransObject.addToStringProperty(propBuilder);
967 * Converts <code>typedef</code> to the generated TO builder.
969 * @param basePackageName
970 * string with name of package to which the module belongs
972 * type definition from which is the generated TO builder created
973 * @return generated TO builder which contains data from
974 * <code>typedef</code> and <code>basePackageName</code>
976 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
978 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
979 final String typeDefTOName = typedef.getQName().getLocalName();
981 if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
982 final String genTOName = parseToClassName(typeDefTOName);
983 final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
984 newType.addComment(typedef.getDescription());
991 * Converts <code>typeDef</code> which should be of the type
992 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
994 * All the bits of the typeDef are added to returning generated TO as
997 * @param basePackageName
998 * string with name of package to which the module belongs
1000 * type definition from which is the generated TO builder created
1001 * @param typeDefName
1002 * string with the name for generated TO builder
1003 * @return generated TO builder which represents <code>typeDef</code>
1004 * @throws IllegalArgumentException
1006 * <li>if <code>typeDef</code> equals null</li>
1007 * <li>if <code>basePackageName</code> equals null</li>
1010 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1011 final TypeDefinition<?> typeDef, String typeDefName) {
1013 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1014 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1016 if (typeDef instanceof BitsTypeDefinition) {
1017 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1019 final String typeName = parseToClassName(typeDefName);
1020 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1022 final List<Bit> bitList = bitsTypeDefinition.getBits();
1023 GeneratedPropertyBuilder genPropertyBuilder;
1024 for (final Bit bit : bitList) {
1025 String name = bit.getName();
1026 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
1027 genPropertyBuilder.setReadOnly(true);
1028 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1030 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1031 genTOBuilder.addHashIdentity(genPropertyBuilder);
1032 genTOBuilder.addToStringProperty(genPropertyBuilder);
1035 return genTOBuilder;
1041 * Converts the pattern constraints from <code>typedef</code> to the list of
1042 * the strings which represents these constraints.
1045 * extended type in which are the pattern constraints sought
1046 * @return list of strings which represents the constraint patterns
1047 * @throws IllegalArgumentException
1048 * if <code>typedef</code> equals null
1051 private List<String> resolveRegExpressionsFromTypedef(ExtendedType typedef) {
1052 final List<String> regExps = new ArrayList<String>();
1053 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1054 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1055 if (strTypeDef instanceof StringType) {
1056 final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1057 if (!patternConstraints.isEmpty()) {
1059 String modifiedRegEx;
1060 for (PatternConstraint patternConstraint : patternConstraints) {
1061 regEx = patternConstraint.getRegularExpression();
1062 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1063 regExps.add(modifiedRegEx);
1072 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1073 * expressions from the <code>regularExpressions</code>
1075 * @param genTOBuilder
1076 * generated TO builder to which are
1077 * <code>regular expressions</code> added
1078 * @param regularExpressions
1079 * list of string which represent regular expressions
1080 * @throws IllegalArgumentException
1082 * <li>if <code>genTOBuilder</code> equals null</li>
1083 * <li>if <code>regularExpressions</code> equals null</li>
1086 private void addStringRegExAsConstant(GeneratedTOBuilder genTOBuilder, List<String> regularExpressions) {
1087 if (genTOBuilder == null) {
1088 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1090 if (regularExpressions == null) {
1091 throw new IllegalArgumentException("List of regular expressions can't be null");
1093 if (!regularExpressions.isEmpty()) {
1094 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1095 regularExpressions);
1100 * Creates generated TO with data about inner extended type
1101 * <code>innerExtendedType</code>, about the package name
1102 * <code>typedefName</code> and about the generated TO name
1103 * <code>typedefName</code>.
1105 * It is supposed that <code>innerExtendedType</code> is already present in
1106 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1107 * be possible set it as extended type for the returning generated TO.
1109 * @param innerExtendedType
1110 * extended type which is part of some other extended type
1111 * @param basePackageName
1112 * string with the package name of the module
1113 * @param typedefName
1114 * string with the name for the generated TO
1115 * @return generated TO which extends generated TO for
1116 * <code>innerExtendedType</code>
1117 * @throws IllegalArgumentException
1119 * <li>if <code>extendedType</code> equals null</li>
1120 * <li>if <code>basePackageName</code> equals null</li>
1121 * <li>if <code>typedefName</code> equals null</li>
1124 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef, final ExtendedType innerExtendedType,
1125 final String basePackageName) {
1126 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1127 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1129 final String typedefName = typedef.getQName().getLocalName();
1130 final String classTypedefName = parseToClassName(typedefName);
1131 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1132 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1133 genTOBuilder.setTypedef(true);
1134 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1135 genTOBuilder.setRestrictions(r);
1137 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1138 genTOBuilder.setIsUnion(true);
1141 Map<Date, Map<String, Type>> modulesByDate = null;
1142 Map<String, Type> typeMap = null;
1143 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1144 if (parentModule != null) {
1145 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1146 typeMap = modulesByDate.get(parentModule.getRevision());
1149 if (typeMap != null) {
1150 Type type = typeMap.get(innerTypeDef);
1151 if (type instanceof GeneratedTransferObject) {
1152 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1155 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1157 return genTOBuilder.toInstance();
1161 * Finds out for each type definition how many immersion (depth) is
1162 * necessary to get to the base type. Every type definition is inserted to
1163 * the map which key is depth and value is list of type definitions with
1164 * equal depth. In next step are lists from this map concatenated to one
1165 * list in ascending order according to their depth. All type definitions
1166 * are in the list behind all type definitions on which depends.
1168 * @param unsortedTypeDefinitions
1169 * list of type definitions which should be sorted by depth
1170 * @return list of type definitions sorted according their each other
1171 * dependencies (type definitions which are depend on other type
1172 * definitions are in list behind them).
1174 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1175 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1176 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1178 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1179 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1180 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1181 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1182 if (typeDefinitionsConcreteDepth == null) {
1183 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1184 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1186 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1188 // keys are in ascending order
1189 Set<Integer> depths = typeDefinitionsDepths.keySet();
1190 for (Integer depth : depths) {
1191 sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1194 return sortedTypeDefinition;
1198 * Returns how many immersion is necessary to get from the type definition
1201 * @param typeDefinition
1202 * type definition for which is depth sought.
1203 * @return number of immersions which are necessary to get from the type
1204 * definition to the base type
1206 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1207 if (typeDefinition == null) {
1211 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1213 if (baseType instanceof ExtendedType) {
1214 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1215 } else if (baseType instanceof UnionType) {
1216 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1217 int maxChildDepth = 0;
1219 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1220 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1221 if (childDepth > maxChildDepth) {
1222 maxChildDepth = childDepth;
1225 return maxChildDepth;
1231 * Returns string which contains the same value as <code>name</code> but
1232 * integer suffix is incremented by one. If <code>name</code> contains no
1233 * number suffix then number 1 is added.
1236 * string with name of augmented node
1237 * @return string with the number suffix incremented by one (or 1 is added)
1239 private String provideAvailableNameForGenTOBuilder(String name) {
1240 Pattern searchedPattern = Pattern.compile("[0-9]+\\z");
1241 Matcher mtch = searchedPattern.matcher(name);
1243 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1244 return name.substring(0, mtch.start()) + newSuffix;
1250 private void addUnitsToGenTO(GeneratedTOBuilder to, String units) {
1251 if (units != null && !units.isEmpty()) {
1252 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1253 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1254 prop.setReturnType(Types.STRING);
1255 to.addToStringProperty(prop);
1260 public String getTypeDefaultConstruction(LeafSchemaNode node) {
1261 return getTypeDefaultConstruction(node, node.getDefault());
1264 public String getTypeDefaultConstruction(LeafSchemaNode node, String defaultValue) {
1265 TypeDefinition<?> type = node.getType();
1266 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of " + node);
1267 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of "
1270 Module module = getParentModule(node);
1271 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
1272 String packageName = packageNameForGeneratedType(basePackageName, node.getType().getPath());
1273 String className = packageName + "." + parseToClassName(node.getType().getQName().getLocalName());
1275 StringBuilder sb = new StringBuilder();
1276 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1277 final boolean isBaseNull = base == null;
1283 String result = null;
1284 if (base instanceof BinaryTypeDefinition) {
1285 result = binaryToDef(defaultValue);
1286 } else if (base instanceof BitsTypeDefinition) {
1288 YangNode parent = node.getParent();
1289 if (parent instanceof Module) {
1290 parentName = parseToClassName(((Module)parent).getName()) + "Data";
1291 className = basePackageName + "." + parentName + "." + parseToClassName(node.getQName().getLocalName());
1293 parentName = parseToClassName(((SchemaNode)parent).getQName().getLocalName());
1294 className = packageName + "." + parentName + "." + parseToClassName(node.getQName().getLocalName());
1296 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, isBaseNull);
1297 } else if (base instanceof BooleanTypeDefinition) {
1298 result = typeToDef(Boolean.class, defaultValue);
1299 } else if (base instanceof DecimalTypeDefinition) {
1300 result = typeToDef(BigDecimal.class, defaultValue);
1301 } else if (base instanceof EmptyTypeDefinition) {
1302 result = typeToDef(Boolean.class, defaultValue);
1303 } else if (base instanceof EnumTypeDefinition) {
1304 char[] defValArray = defaultValue.toCharArray();
1305 char first = Character.toUpperCase(defaultValue.charAt(0));
1306 defValArray[0] = first;
1307 String newDefVal = new String(defValArray);
1308 if (type instanceof ExtendedType) {
1309 className = packageName + "." + parseToClassName(node.getType().getQName().getLocalName());
1311 result = className + "." + newDefVal;
1312 } else if (base instanceof IdentityrefTypeDefinition) {
1313 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1314 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1315 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1316 } else if (base instanceof Int8) {
1317 result = typeToDef(Byte.class, defaultValue);
1318 } else if (base instanceof Int16) {
1319 result = typeToDef(Short.class, defaultValue);
1320 } else if (base instanceof Int32) {
1321 result = typeToDef(Integer.class, defaultValue);
1322 } else if (base instanceof Int64) {
1323 result = typeToDef(Long.class, defaultValue);
1324 } else if (base instanceof LeafrefTypeDefinition) {
1325 result = leafrefToDef(node, (LeafrefTypeDefinition)base);
1326 } else if (base instanceof StringTypeDefinition) {
1327 result = "\"" + defaultValue + "\"";
1328 } else if (base instanceof Uint8) {
1329 result = typeToDef(Short.class, defaultValue);
1330 } else if (base instanceof Uint16) {
1331 result = typeToDef(Integer.class, defaultValue);
1332 } else if (base instanceof Uint32) {
1333 result = typeToDef(Long.class, defaultValue);
1334 } else if (base instanceof Uint64) {
1335 result = typeToDef(BigInteger.class, defaultValue);
1336 } else if (base instanceof UnionTypeDefinition) {
1337 throw new UnsupportedOperationException("Cannot get default construction for union type");
1343 if (result != null && !result.isEmpty() && type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)) {
1344 className = packageName + "." + parseToClassName(node.getType().getQName().getLocalName());
1345 sb.insert(0, "new " + className + "(");
1346 sb.insert(sb.length(), ")");
1349 return sb.toString();
1353 private String typeToDef(Class<?> clazz, String defaultValue) {
1354 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1357 private String binaryToDef(String defaultValue) {
1358 StringBuilder sb = new StringBuilder();
1359 BaseEncoding en = BaseEncoding.base64();
1360 byte[] encoded = en.decode(defaultValue);
1361 sb.append("new byte[] {");
1362 for (int i = 0; i < encoded.length; i++) {
1363 sb.append(encoded[i]);
1364 if (i != encoded.length - 1) {
1369 return sb.toString();
1372 private String bitsToDef(BitsTypeDefinition type, String className, String defaultValue, boolean isBase) {
1373 List<Bit> bits = new ArrayList<>(type.getBits());
1374 Collections.sort(bits, new Comparator<Bit>() {
1376 public int compare(Bit o1, Bit o2) {
1377 return o1.getName().compareTo(o2.getName());
1380 StringBuilder sb = new StringBuilder();
1381 sb.append(isBase ? "new " + className + "(" : "");
1382 for (int i = 0; i < bits.size(); i++) {
1383 if (bits.get(i).getName().equals(defaultValue)) {
1388 if (i != bits.size() - 1) {
1392 sb.append(isBase ? ")" : "");
1393 return sb.toString();
1396 private Module getParentModule(YangNode node) {
1397 if (node instanceof Module) {
1398 return (Module) node;
1401 YangNode parent = null;
1402 if (node instanceof DataSchemaNode) {
1403 parent = ((DataSchemaNode) node).getParent();
1404 } else if (node instanceof DataNodeContainer) {
1405 parent = ((DataNodeContainer) node).getParent();
1410 while (parent != null && !(parent instanceof Module)) {
1411 if (parent instanceof DataSchemaNode) {
1412 parent = ((DataSchemaNode) parent).getParent();
1413 } else if (parent instanceof DataNodeContainer) {
1414 parent = ((DataNodeContainer) parent).getParent();
1419 return (Module) parent;
1422 private String leafrefToDef(LeafSchemaNode parentNode, LeafrefTypeDefinition leafrefType) {
1423 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1424 Preconditions.checkArgument(leafrefType.getPathStatement() != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
1426 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1427 final String strXPath = xpath.toString();
1429 if (strXPath != null) {
1430 if (strXPath.contains("[")) {
1431 return "new java.lang.Object()";
1433 final Module module = findParentModule(schemaContext, parentNode);
1434 if (module != null) {
1435 final SchemaNode dataNode;
1436 if (xpath.isAbsolute()) {
1437 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1439 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1441 return getTypeDefaultConstruction((LeafSchemaNode)dataNode, parentNode.getDefault());
1466 * Utility method which search for original node defined in grouping.
1468 private DataSchemaNode findOriginal(DataSchemaNode node) {
1469 DataSchemaNode result = findCorrectTargetFromGrouping(node);
1470 if (result == null) {
1471 result = findCorrectTargetFromAugment(node);
1472 if (result != null) {
1473 if (result.isAddedByUses()) {
1474 result = findOriginal(result);
1481 private DataSchemaNode findCorrectTargetFromAugment(DataSchemaNode node) {
1482 if (!node.isAugmenting()) {
1486 String currentName = node.getQName().getLocalName();
1487 List<String> tmpPath = new ArrayList<>();
1488 YangNode parent = node;
1489 AugmentationSchema augment = null;
1491 parent = ((DataSchemaNode)parent).getParent();
1492 if (parent instanceof AugmentationTarget) {
1493 tmpPath.add(currentName);
1494 augment = findNodeInAugment(((AugmentationTarget)parent).getAvailableAugmentations(), currentName);
1495 if (augment == null) {
1496 currentName = ((DataSchemaNode)parent).getQName().getLocalName();
1499 } while (((DataSchemaNode)parent).isAugmenting() && augment == null);
1501 if (augment == null) {
1504 Collections.reverse(tmpPath);
1505 Object actualParent = augment;
1506 DataSchemaNode result = null;
1507 for (String name : tmpPath) {
1508 if (actualParent instanceof DataNodeContainer) {
1509 result = ((DataNodeContainer)actualParent).getDataChildByName(name);
1510 actualParent = ((DataNodeContainer)actualParent).getDataChildByName(name);
1512 if (actualParent instanceof ChoiceNode) {
1513 result = ((ChoiceNode)actualParent).getCaseNodeByName(name);
1514 actualParent = ((ChoiceNode)actualParent).getCaseNodeByName(name);
1519 if (result.isAddedByUses()) {
1520 result = findCorrectTargetFromGrouping(result);
1527 private AugmentationSchema findNodeInAugment(Collection<AugmentationSchema> augments, String name) {
1528 for (AugmentationSchema augment : augments) {
1529 if (augment.getDataChildByName(name) != null) {
1536 private DataSchemaNode findCorrectTargetFromGrouping(DataSchemaNode node) {
1537 if (node.getPath().getPath().size() == 1) {
1539 // uses is under module statement
1540 Module m = findParentModule(schemaContext, node);
1541 DataSchemaNode result = null;
1542 for (UsesNode u : m.getUses()) {
1543 SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, u.getGroupingPath().getPath());
1544 if (!(targetGrouping instanceof GroupingDefinition)) {
1545 throw new IllegalArgumentException("Failed to generate code for augment in " + u);
1547 GroupingDefinition gr = (GroupingDefinition)targetGrouping;
1548 result = gr.getDataChildByName(node.getQName().getLocalName());
1550 if (result == null) {
1551 throw new IllegalArgumentException("Failed to generate code for augment");
1555 DataSchemaNode result = null;
1556 String currentName = node.getQName().getLocalName();
1557 List<String> tmpPath = new ArrayList<>();
1558 YangNode parent = node.getParent();
1560 tmpPath.add(currentName);
1561 DataNodeContainer dataNodeParent = (DataNodeContainer)parent;
1562 for (UsesNode u : dataNodeParent.getUses()) {
1563 if (result == null) {
1564 SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, u.getGroupingPath().getPath());
1565 if (!(targetGrouping instanceof GroupingDefinition)) {
1566 throw new IllegalArgumentException("Failed to generate code for augment in " + u);
1568 GroupingDefinition gr = (GroupingDefinition)targetGrouping;
1569 result = gr.getDataChildByName(currentName);
1572 if (result == null) {
1573 currentName = ((SchemaNode)parent).getQName().getLocalName();
1574 if (parent instanceof DataSchemaNode) {
1575 parent = ((DataSchemaNode)parent).getParent();
1577 parent = ((DataNodeContainer)parent).getParent();
1580 } while (result == null && !(parent instanceof Module));
1582 if (result != null) {
1583 if (tmpPath.size() == 1) {
1584 if (result != null && result.isAddedByUses()) {
1585 result = findOriginal(result);
1589 DataSchemaNode newParent = result;
1590 Collections.reverse(tmpPath);
1592 for (String name : tmpPath) {
1593 newParent = ((DataNodeContainer)newParent).getDataChildByName(name);
1595 if (newParent != null && newParent.isAddedByUses()) {
1596 newParent = findOriginal(newParent);
1607 public String getConstructorPropertyName(SchemaNode node) {
1608 if (node instanceof TypeDefinition<?>) {