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.util.ArrayList;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.List;
19 import java.util.TreeMap;
20 import java.util.regex.Matcher;
21 import java.util.regex.Pattern;
23 import org.apache.commons.lang.StringEscapeUtils;
24 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
25 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
26 import org.opendaylight.yangtools.binding.generator.util.Types;
27 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
28 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
29 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
30 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
31 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
32 import org.opendaylight.yangtools.sal.binding.model.api.Type;
33 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
34 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
35 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
36 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.Module;
42 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
46 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
49 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
53 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
54 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
55 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
56 import org.opendaylight.yangtools.yang.model.util.StringType;
57 import org.opendaylight.yangtools.yang.model.util.UnionType;
58 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
60 import com.google.common.base.Preconditions;
62 public final class TypeProviderImpl implements TypeProvider {
64 * Contains the schema data red from YANG files.
66 private final SchemaContext schemaContext;
69 * The outter map maps module names to the map of the types for the module.
70 * The inner map maps the name of the concrete type to the JAVA
71 * <code>Type</code> (usually it is generated TO).
73 private Map<String, Map<String, Type>> genTypeDefsContextMap;
76 * The map which maps schema paths to JAVA <code>Type</code>.
78 private final Map<SchemaPath, Type> referencedTypes;
81 * Creates new instance of class <code>TypeProviderImpl</code>.
83 * @param schemaContext
84 * contains the schema data red from YANG files
85 * @throws IllegalArgumentException
86 * if <code>schemaContext</code> equal null.
88 public TypeProviderImpl(final SchemaContext schemaContext) {
89 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
91 this.schemaContext = schemaContext;
92 this.genTypeDefsContextMap = new HashMap<>();
93 this.referencedTypes = new HashMap<>();
94 resolveTypeDefsFromContext();
98 * Puts <code>refType</code> to map with key <code>refTypePath</code>
101 * schema path used as the map key
103 * type which represents the map value
104 * @throws IllegalArgumentException
106 * <li>if <code>refTypePath</code> equal null</li>
107 * <li>if <code>refType</code> equal null</li>
111 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
112 Preconditions.checkArgument(refTypePath != null,
113 "Path reference of Enumeration Type Definition cannot be NULL!");
114 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
115 referencedTypes.put(refTypePath, refType);
120 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
123 * string with YANG name of type
124 * @return JAVA <code>Type</code> for YANG type <code>type</code>
125 * @see TypeProvider#javaTypeForYangType(String)
128 public Type javaTypeForYangType(String type) {
129 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
133 * Converts schema definition type <code>typeDefinition</code> to JAVA
136 * @param typeDefinition
137 * type definition which is converted to JAVA type
138 * @throws IllegalArgumentException
140 * <li>if <code>typeDefinition</code> equal null</li>
141 * <li>if Q name of <code>typeDefinition</code> equal null</li>
142 * <li>if name of <code>typeDefinition</code> equal null</li>
146 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
147 Type returnType = null;
148 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
149 if (typeDefinition.getQName() == null) {
150 throw new IllegalArgumentException(
151 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
153 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
154 "Type Definitions Local Name cannot be NULL!");
156 if (typeDefinition instanceof ExtendedType) {
157 returnType = javaTypeForExtendedType(typeDefinition);
159 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
160 if (returnType == null) {
161 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
165 // TODO: add throw exception when we will be able to resolve ALL yang
167 // if (returnType == null) {
168 // throw new IllegalArgumentException("Type Provider can't resolve " +
169 // "type for specified Type Definition " + typedefName);
175 * Returns JAVA <code>Type</code> for instances of the type
176 * <code>LeafrefTypeDefinition</code> or
177 * <code>IdentityrefTypeDefinition</code>.
179 * @param typeDefinition
180 * type definition which is converted to JAVA <code>Type</code>
181 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
183 private Type javaTypeForLeafrefOrIdentityRef(TypeDefinition<?> typeDefinition, SchemaNode parentNode) {
184 if (typeDefinition instanceof LeafrefTypeDefinition) {
185 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
186 return provideTypeForLeafref(leafref, parentNode);
187 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
188 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
189 return provideTypeForIdentityref(idref);
196 * Returns JAVA <code>Type</code> for instances of the type
197 * <code>ExtendedType</code>.
199 * @param typeDefinition
200 * type definition which is converted to JAVA <code>Type</code>
201 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
203 private Type javaTypeForExtendedType(TypeDefinition<?> typeDefinition) {
204 final String typedefName = typeDefinition.getQName().getLocalName();
205 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
206 Type returnType = null;
207 returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
208 if (returnType == null) {
209 if (baseTypeDef instanceof EnumTypeDefinition) {
210 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
211 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
213 final Module module = findParentModule(schemaContext, typeDefinition);
214 if (module != null) {
215 final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
216 if (genTOs != null) {
217 returnType = genTOs.get(typedefName);
219 if (returnType == null) {
220 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
221 baseTypeDef, typeDefinition);
227 // TODO: add throw exception when we will be able to resolve ALL yang
229 // if (returnType == null) {
230 // throw new IllegalArgumentException("Type Provider can't resolve " +
231 // "type for specified Type Definition " + typedefName);
236 * Seeks for identity reference <code>idref</code> the JAVA
237 * <code>type</code>.<br />
241 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
242 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
245 * identityref type definition for which JAVA <code>Type</code>
247 * @return JAVA <code>Type</code> of the identity which is refrenced through
250 private Type provideTypeForIdentityref(IdentityrefTypeDefinition idref) {
251 QName baseIdQName = idref.getIdentity().getQName();
252 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
253 baseIdQName.getRevision());
254 IdentitySchemaNode identity = null;
255 for (IdentitySchemaNode id : module.getIdentities()) {
256 if (id.getQName().equals(baseIdQName)) {
260 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
262 final String basePackageName = moduleNamespaceToPackageName(module);
263 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
264 final String genTypeName = parseToClassName(identity.getQName().getLocalName());
266 Type baseType = Types.typeForClass(Class.class);
267 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
268 return Types.parameterizedTypeFor(baseType, paramType);
272 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
274 * @param typeDefinition
275 * type definition which should be converted to JAVA
277 * @return JAVA <code>Type</code> which represents
278 * <code>typeDefinition</code>
279 * @throws IllegalArgumentException
281 * <li>if <code>typeDefinition</code> equal null</li>
282 * <li>if Q name of <code>typeDefinition</code></li>
283 * <li>if name of <code>typeDefinition</code></li>
286 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
287 final SchemaNode parentNode) {
288 Type returnType = null;
289 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
290 if (typeDefinition.getQName() == null) {
291 throw new IllegalArgumentException(
292 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
294 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
295 "Type Definitions Local Name cannot be NULL!");
297 final String typedefName = typeDefinition.getQName().getLocalName();
298 if (typeDefinition instanceof ExtendedType) {
299 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
301 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
302 final Module module = findParentModule(schemaContext, parentNode);
304 if (module != null) {
305 final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
306 if (genTOs != null) {
307 returnType = genTOs.get(typedefName);
316 * Gets base type definition for <code>extendTypeDef</code>. The method is
317 * recursivelly called until non <code>ExtendedType</code> type is found.
319 * @param extendTypeDef
320 * type definition for which is the base type definition sought
321 * @return type definition which is base type for <code>extendTypeDef</code>
322 * @throws IllegalArgumentException
323 * if <code>extendTypeDef</code> equal null
325 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
326 Preconditions.checkArgument(extendTypeDef != null, "Type Definiition reference cannot be NULL!");
327 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
328 if (baseTypeDef instanceof ExtendedType) {
329 return baseTypeDefForExtendedType(baseTypeDef);
337 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
339 * The path of <code>leafrefType</code> is followed to find referenced node
340 * and its <code>Type</code> is returned.
343 * leafref type definition for which is the type sought
344 * @return JAVA <code>Type</code> of data schema node which is referenced in
345 * <code>leafrefType</code>
346 * @throws IllegalArgumentException
348 * <li>if <code>leafrefType</code> equal null</li>
349 * <li>if path statement of <code>leafrefType</code> equal null</li>
353 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
354 Type returnType = null;
355 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
357 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
358 "The Path Statement for Leafref Type Definition cannot be NULL!");
360 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
361 final String strXPath = xpath.toString();
363 if (strXPath != null) {
364 if (strXPath.contains("[")) {
365 returnType = Types.typeForClass(Object.class);
367 final Module module = findParentModule(schemaContext, parentNode);
368 if (module != null) {
369 final SchemaNode dataNode;
370 if (xpath.isAbsolute()) {
371 dataNode = findDataSchemaNode(schemaContext, module, xpath);
373 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
376 if (leafContainsEnumDefinition(dataNode)) {
377 returnType = referencedTypes.get(dataNode.getPath());
378 } else if (leafListContainsEnumDefinition(dataNode)) {
379 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
381 returnType = resolveTypeFromDataSchemaNode(dataNode);
390 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
391 * so then checks if it is of type <code>EnumTypeDefinition</code>.
394 * data schema node for which is checked if it is leaf and if it
396 * @return boolean value
398 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
399 * <li>false - other cases</li>
402 private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
403 if (dataNode instanceof LeafSchemaNode) {
404 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
405 if (leaf.getType() instanceof EnumTypeDefinition) {
413 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
414 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
417 * data schema node for which is checked if it is leaflist and if
419 * @return boolean value
421 * <li>true - if <code>dataNode</code> is leaflist of type
423 * <li>false - other cases</li>
426 private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
427 if (dataNode instanceof LeafListSchemaNode) {
428 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
429 if (leafList.getType() instanceof EnumTypeDefinition) {
437 * Converts <code>enumTypeDef</code> to
438 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
442 * enumeration type definition which is converted to enumeration
444 * string with name which is used as the enumeration name
445 * @return enumeration type which is built with data (name, enum values)
446 * from <code>enumTypeDef</code>
447 * @throws IllegalArgumentException
449 * <li>if <code>enumTypeDef</code> equals null</li>
450 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
451 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
452 * <li>if name of <code>enumTypeDef</code> equal null</li>
455 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
456 final SchemaNode parentNode) {
457 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
458 Preconditions.checkArgument(enumTypeDef.getValues() != null,
459 "EnumTypeDefinition MUST contain at least ONE value definition!");
460 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
461 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
462 "Local Name in EnumTypeDefinition QName cannot be NULL!");
464 final String enumerationName = parseToClassName(enumName);
466 Module module = findParentModule(schemaContext, parentNode);
467 final String basePackageName = moduleNamespaceToPackageName(module);
469 final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
470 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
471 return enumBuilder.toInstance(null);
475 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
476 * taken from <code>enumTypeDef</code>.
479 * enumeration type definition is source of enumeration data for
480 * <code>typeBuilder</code>
482 * string with the name of enumeration
484 * generated type builder to which is enumeration added
485 * @return enumeration type which contains enumeration data form
486 * <code>enumTypeDef</code>
487 * @throws IllegalArgumentException
489 * <li>if <code>enumTypeDef</code> equals null</li>
490 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
491 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
492 * <li>if name of <code>enumTypeDef</code> equal null</li>
493 * <li>if name of <code>typeBuilder</code> equal null</li>
497 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
498 final GeneratedTypeBuilderBase<?> typeBuilder) {
499 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
500 Preconditions.checkArgument(enumTypeDef.getValues() != null,
501 "EnumTypeDefinition MUST contain at least ONE value definition!");
502 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
503 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
504 "Local Name in EnumTypeDefinition QName cannot be NULL!");
505 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
507 final String enumerationName = parseToClassName(enumName);
509 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
510 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
511 return enumBuilder.toInstance(enumBuilder);
515 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
518 * contains information about YANG type
519 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
521 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
522 Type returnType = null;
523 if (dataNode != null) {
524 if (dataNode instanceof LeafSchemaNode) {
525 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
526 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
527 } else if (dataNode instanceof LeafListSchemaNode) {
528 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
529 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
536 * Passes through all modules and through all its type definitions and
537 * convert it to generated types.
539 * The modules are firstly sorted by mutual dependencies. The modules are
540 * sequentially passed. All type definitions of a module are at the
541 * beginning sorted so that type definition with less amount of references
542 * to other type definition are processed first.<br />
543 * For each module is created mapping record in the map
544 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
545 * which map current module name to the map which maps type names to
546 * returned types (generated types).
549 private void resolveTypeDefsFromContext() {
550 final Set<Module> modules = schemaContext.getModules();
551 Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
552 final Module[] modulesArray = new Module[modules.size()];
554 for (Module modul : modules) {
555 modulesArray[i++] = modul;
557 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modulesArray);
559 for (final Module module : modulesSortedByDependency) {
560 if (module == null) {
563 final String moduleName = module.getName();
564 final String basePackageName = moduleNamespaceToPackageName(module);
566 final DataNodeIterator it = new DataNodeIterator(module);
567 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
568 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
570 final Map<String, Type> typeMap = new HashMap<>();
571 genTypeDefsContextMap.put(moduleName, typeMap);
573 if ((listTypeDefinitions != null) && (basePackageName != null)) {
574 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
575 typedefToGeneratedType(basePackageName, moduleName, typedef);
583 * @param basePackageName
584 * string with name of package to which the module belongs
586 * string with the name of the module for to which the
587 * <code>typedef</code> belongs
589 * type definition of the node for which should be creted JAVA
590 * <code>Type</code> (usually generated TO)
591 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
592 * <code>null</code> value if <code>basePackageName</code> or
593 * <code>modulName</code> or <code>typedef</code> or Q name of
594 * <code>typedef</code> equals <code>null</code>
596 private Type typedefToGeneratedType(final String basePackageName, final String moduleName,
597 final TypeDefinition<?> typedef) {
598 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
600 final String typedefName = typedef.getQName().getLocalName();
601 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
602 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
603 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
604 Type returnType = null;
605 if (innerTypeDefinition instanceof ExtendedType) {
606 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
607 returnType = provideGeneratedTOFromExtendedType(innerExtendedType, basePackageName, typedefName);
608 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
609 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
610 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
611 returnType = genTOBuilder.toInstance();
612 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
613 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
614 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
616 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
617 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
618 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
619 basePackageName, bitsTypeDefinition, typedefName);
620 returnType = genTOBuilder.toInstance();
623 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
624 innerTypeDefinition, typedef);
626 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
628 if (returnType != null) {
629 final Map<String, Type> typeMap = genTypeDefsContextMap.get(moduleName);
630 if (typeMap != null) {
631 typeMap.put(typedefName, returnType);
641 * Wraps base YANG type to generated TO.
643 * @param basePackageName
644 * string with name of package to which the module belongs
646 * type definition which is converted to the TO
648 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
649 * @return generated transfer object which represent<code>javaType</code>
651 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
652 final Type javaType) {
653 if (javaType != null) {
654 final String propertyName = "value";
656 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
657 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
658 genPropBuilder.setReturnType(javaType);
659 genTOBuilder.addEqualsIdentity(genPropBuilder);
660 genTOBuilder.addHashIdentity(genPropBuilder);
661 genTOBuilder.addToStringProperty(genPropBuilder);
662 if (javaType == BaseYangTypes.STRING_TYPE && typedef instanceof ExtendedType) {
663 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
664 addStringRegExAsConstant(genTOBuilder, regExps);
666 return genTOBuilder.toInstance();
672 * Converts output list of generated TO builders to one TO builder (first
673 * from list) which contains the remaining builders as its enclosing TO.
675 * @param basePackageName
676 * string with name of package to which the module belongs
678 * type definition which should be of type
679 * <code>UnionTypeDefinition</code>
681 * string with name for generated TO
682 * @return generated TO builder with the list of enclosed generated TO
685 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
686 final UnionTypeDefinition typedef, String typeDefName, SchemaNode parentNode) {
687 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
688 typedef, typeDefName, parentNode);
689 GeneratedTOBuilder resultTOBuilder = null;
690 if (!genTOBuilders.isEmpty()) {
691 resultTOBuilder = genTOBuilders.get(0);
692 genTOBuilders.remove(0);
693 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
694 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
697 return resultTOBuilder;
701 * Converts <code>typedef</code> to generated TO with
702 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
703 * added to generated TO builder as property.
705 * @param basePackageName
706 * string with name of package to which the module belongs
708 * type definition which should be of type
709 * <code>UnionTypeDefinition</code>
711 * string with name for generated TO
712 * @return generated TO builder which represents <code>typedef</code>
713 * @throws IllegalArgumentException
715 * <li>if <code>basePackageName</code> equals null</li>
716 * <li>if <code>typedef</code> equals null</li>
717 * <li>if Q name of <code>typedef</code> equals null</li>
720 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
721 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
722 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
723 Preconditions.checkArgument(typedef != null, "Type Definition cannot be NULL!");
724 Preconditions.checkArgument(typedef.getQName() != null,
725 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
727 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
729 if (typedef != null) {
730 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
732 final GeneratedTOBuilder unionGenTOBuilder;
733 if (typeDefName != null && !typeDefName.isEmpty()) {
734 final String typeName = parseToClassName(typeDefName);
735 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
737 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
739 generatedTOBuilders.add(unionGenTOBuilder);
740 unionGenTOBuilder.setIsUnion(true);
741 final List<String> regularExpressions = new ArrayList<String>();
742 for (final TypeDefinition<?> unionType : unionTypes) {
743 final String unionTypeName = unionType.getQName().getLocalName();
744 if (unionType instanceof UnionType) {
745 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
746 basePackageName, parentNode));
747 } else if (unionType instanceof ExtendedType) {
748 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, unionTypeName,
749 regularExpressions, parentNode);
750 } else if (unionType instanceof EnumTypeDefinition) {
751 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
752 unionTypeName, unionGenTOBuilder);
753 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
755 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
756 unionType, parentNode);
757 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
760 if (!regularExpressions.isEmpty()) {
761 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
764 storeGenTO(typedef, unionGenTOBuilder, parentNode);
766 return generatedTOBuilders;
770 * Wraps code which handle case when union subtype is also of the type
771 * <code>UnionType</code>.
773 * In this case the new generated TO is created for union subtype (recursive
775 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, TypeDefinition, String)
776 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
777 * <code>parentUnionGenTOBuilder</code> is created property which type is
778 * equal to new generated TO.
780 * @param parentUnionGenTOBuilder
781 * generated TO builder to which is the property with the child
782 * union subtype added
783 * @param basePackageName
784 * string with the name of the module package
785 * @param unionSubtype
786 * type definition which represents union subtype
787 * @return list of generated TO builders. The number of the builders can be
788 * bigger one due to recursive call of
789 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
791 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
792 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
793 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
794 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
795 basePackageName, unionSubtype, newTOBuilderName, parentNode);
797 final GeneratedPropertyBuilder propertyBuilder;
798 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
799 .parseToValidParamName(newTOBuilderName));
800 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
801 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
802 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
804 return subUnionGenTOBUilders;
808 * Wraps code which handle case when union subtype is of the type
809 * <code>ExtendedType</code>.
811 * If TO for this type already exists it is used for the creation of the
812 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
813 * type is used for the property creation.
815 * @param parentUnionGenTOBuilder
816 * generated TO builder in which new property is created
817 * @param unionSubtype
818 * type definition of the <code>ExtendedType</code> type which
819 * represents union subtype
820 * @param unionTypeName
821 * string with the name for <code>unionSubtype</code>
822 * @param regularExpressions
823 * list of strings with the regular expressions
825 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
826 final ExtendedType unionSubtype, final String unionTypeName, final List<String> regularExpressions,
827 final SchemaNode parentNode) {
828 final Type genTO = findGenTO(unionTypeName, parentNode);
830 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
832 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
833 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
834 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
836 if (javaType != null) {
837 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
840 if (baseType instanceof StringType) {
841 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
847 * Searches for generated TO for <code>searchedTypeDef</code> type
848 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
850 * @param searchedTypeName
851 * string with name of <code>searchedTypeDef</code>
852 * @return generated TO for <code>searchedTypeDef</code> or
853 * <code>null</code> it it doesn't exist
855 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
856 final Module typeModule = findParentModule(schemaContext, parentNode);
857 if (typeModule != null && typeModule.getName() != null) {
858 final Map<String, Type> genTOs = genTypeDefsContextMap.get(typeModule.getName());
859 if (genTOs != null) {
860 return genTOs.get(searchedTypeName);
867 * Stores generated TO created from <code>genTOBuilder</code> for
868 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
869 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
872 * type definition for which is <code>genTOBuilder</code> created
873 * @param genTOBuilder
874 * generated TO builder which is converted to generated TO and
877 private void storeGenTO(TypeDefinition<?> newTypeDef, GeneratedTOBuilder genTOBuilder, SchemaNode parentNode) {
878 if (!(newTypeDef instanceof UnionType)) {
879 Map<String, Type> genTOsMap = null;
880 final Module parentModule = findParentModule(schemaContext, parentNode);
881 if (parentModule != null && parentModule.getName() != null) {
882 genTOsMap = genTypeDefsContextMap.get(parentModule.getName());
883 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
889 * Adds a new property with the name <code>propertyName</code> and with type
890 * <code>type</code> to <code>unonGenTransObject</code>.
892 * @param unionGenTransObject
893 * generated TO to which should be property added
895 * JAVA <code>type</code> of the property which should be added
896 * to <code>unionGentransObject</code>
897 * @param propertyName
898 * string with name of property which should be added to
899 * <code>unionGentransObject</code>
901 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
902 final String propertyName) {
903 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
904 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
905 .addProperty(parseToValidParamName(propertyName));
906 propBuilder.setReturnType(type);
908 unionGenTransObject.addEqualsIdentity(propBuilder);
909 unionGenTransObject.addHashIdentity(propBuilder);
910 unionGenTransObject.addToStringProperty(propBuilder);
915 * Converts <code>typedef</code> to the generated TO builder.
917 * @param basePackageName
918 * string with name of package to which the module belongs
920 * type definition from which is the generated TO builder created
921 * @return generated TO builder which contains data from
922 * <code>typedef</code> and <code>basePackageName</code>
924 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
926 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
927 final String typeDefTOName = typedef.getQName().getLocalName();
929 if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
930 final String genTOName = parseToClassName(typeDefTOName);
931 final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
932 newType.addComment(typedef.getDescription());
939 * Converts <code>typeDef</code> which should be of the type
940 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
942 * All the bits of the typeDef are added to returning generated TO as
945 * @param basePackageName
946 * string with name of package to which the module belongs
948 * type definition from which is the generated TO builder created
950 * string with the name for generated TO builder
951 * @return generated TO builder which represents <code>typeDef</code>
952 * @throws IllegalArgumentException
954 * <li>if <code>typeDef</code> equals null</li>
955 * <li>if <code>basePackageName</code> equals null</li>
958 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
959 final TypeDefinition<?> typeDef, String typeDefName) {
961 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
962 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
964 if (typeDef instanceof BitsTypeDefinition) {
965 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
967 final String typeName = parseToClassName(typeDefName);
968 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
970 final List<Bit> bitList = bitsTypeDefinition.getBits();
971 GeneratedPropertyBuilder genPropertyBuilder;
972 for (final Bit bit : bitList) {
973 String name = bit.getName();
974 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
975 genPropertyBuilder.setReadOnly(true);
976 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
978 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
979 genTOBuilder.addHashIdentity(genPropertyBuilder);
980 genTOBuilder.addToStringProperty(genPropertyBuilder);
989 * Converts the pattern constraints from <code>typedef</code> to the list of
990 * the strings which represents these constraints.
993 * extended type in which are the pattern constraints sought
994 * @return list of strings which represents the constraint patterns
995 * @throws IllegalArgumentException
996 * if <code>typedef</code> equals null
999 private List<String> resolveRegExpressionsFromTypedef(ExtendedType typedef) {
1000 final List<String> regExps = new ArrayList<String>();
1001 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1002 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1003 if (strTypeDef instanceof StringType) {
1004 final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1005 if (!patternConstraints.isEmpty()) {
1007 String modifiedRegEx;
1008 for (PatternConstraint patternConstraint : patternConstraints) {
1009 regEx = patternConstraint.getRegularExpression();
1010 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1011 regExps.add(modifiedRegEx);
1020 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1021 * expressions from the <code>regularExpressions</code>
1023 * @param genTOBuilder
1024 * generated TO builder to which are
1025 * <code>regular expressions</code> added
1026 * @param regularExpressions
1027 * list of string which represent regular expressions
1028 * @throws IllegalArgumentException
1030 * <li>if <code>genTOBuilder</code> equals null</li>
1031 * <li>if <code>regularExpressions</code> equals null</li>
1034 private void addStringRegExAsConstant(GeneratedTOBuilder genTOBuilder, List<String> regularExpressions) {
1035 if (genTOBuilder == null) {
1036 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1038 if (regularExpressions == null) {
1039 throw new IllegalArgumentException("List of regular expressions can't be null");
1041 if (!regularExpressions.isEmpty()) {
1042 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1043 regularExpressions);
1048 * Creates generated TO with data about inner extended type
1049 * <code>innerExtendedType</code>, about the package name
1050 * <code>typedefName</code> and about the generated TO name
1051 * <code>typedefName</code>.
1053 * It is supposed that <code>innerExtendedType</code> is already present in
1054 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1055 * be possible set it as extended type for the returning generated TO.
1057 * @param innerExtendedType
1058 * extended type which is part of some other extended type
1059 * @param basePackageName
1060 * string with the package name of the module
1061 * @param typedefName
1062 * string with the name for the generated TO
1063 * @return generated TO which extends generated TO for
1064 * <code>innerExtendedType</code>
1065 * @throws IllegalArgumentException
1067 * <li>if <code>extendedType</code> equals null</li>
1068 * <li>if <code>basePackageName</code> equals null</li>
1069 * <li>if <code>typedefName</code> equals null</li>
1072 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final ExtendedType innerExtendedType,
1073 final String basePackageName, final String typedefName) {
1075 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1076 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1077 Preconditions.checkArgument(typedefName != null, "String with type definition name cannot be NULL!");
1079 final String classTypedefName = parseToClassName(typedefName);
1080 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1081 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1083 Map<String, Type> typeMap = null;
1084 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1085 if (parentModule != null) {
1086 typeMap = genTypeDefsContextMap.get(parentModule.getName());
1089 if (typeMap != null) {
1090 Type type = typeMap.get(innerTypeDef);
1091 if (type instanceof GeneratedTransferObject) {
1092 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1096 return genTOBuilder.toInstance();
1100 * Finds out for each type definition how many immersion (depth) is
1101 * necessary to get to the base type. Every type definition is inserted to
1102 * the map which key is depth and value is list of type definitions with
1103 * equal depth. In next step are lists from this map concatenated to one
1104 * list in ascending order according to their depth. All type definitions
1105 * are in the list behind all type definitions on which depends.
1107 * @param unsortedTypeDefinitions
1108 * list of type definitions which should be sorted by depth
1109 * @return list of type definitions sorted according their each other
1110 * dependencies (type definitions which are depend on other type
1111 * definitions are in list behind them).
1113 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1114 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1115 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1117 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1118 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1119 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1120 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1121 if (typeDefinitionsConcreteDepth == null) {
1122 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1123 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1125 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1127 // keys are in ascending order
1128 Set<Integer> depths = typeDefinitionsDepths.keySet();
1129 for (Integer depth : depths) {
1130 sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1133 return sortedTypeDefinition;
1137 * Returns how many immersion is necessary to get from the type definition
1140 * @param typeDefinition
1141 * type definition for which is depth sought.
1142 * @return number of immersions which are necessary to get from the type
1143 * definition to the base type
1145 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1146 if (typeDefinition == null) {
1150 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1152 if (baseType instanceof ExtendedType) {
1153 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1154 } else if (baseType instanceof UnionType) {
1155 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1156 int maxChildDepth = 0;
1158 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1159 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition.getBaseType());
1160 if (childDepth > maxChildDepth) {
1161 maxChildDepth = childDepth;
1164 return maxChildDepth;
1170 * Returns string which contains the same value as <code>name</code> but
1171 * integer suffix is incremented by one. If <code>name</code> contains no
1172 * number suffix then number 1 is added.
1175 * string with name of augmented node
1176 * @return string with the number suffix incremented by one (or 1 is added)
1178 private String provideAvailableNameForGenTOBuilder(String name) {
1179 Pattern searchedPattern = Pattern.compile("[0-9]+\\z");
1180 Matcher mtch = searchedPattern.matcher(name);
1182 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1183 return name.substring(0, mtch.start()) + newSuffix;