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.HashMap;
15 import java.util.List;
18 import java.util.TreeMap;
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
22 import org.apache.commons.lang.StringEscapeUtils;
23 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
24 import org.opendaylight.yangtools.binding.generator.util.Types;
25 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
26 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
27 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
28 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
29 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
30 import org.opendaylight.yangtools.sal.binding.model.api.Type;
31 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
32 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
33 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
34 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.Module;
41 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
44 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
47 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
49 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
52 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
53 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
54 import org.opendaylight.yangtools.yang.model.util.StringType;
55 import org.opendaylight.yangtools.yang.model.util.UnionType;
56 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
58 import com.google.common.base.Preconditions;
60 public final class TypeProviderImpl implements TypeProvider {
62 * Contains the schema data red from YANG files.
64 private final SchemaContext schemaContext;
67 * The outter map maps module names to the map of the types for the module.
68 * The inner map maps the name of the concrete type to the JAVA
69 * <code>Type</code> (usually it is generated TO).
71 private Map<String, Map<String, Type>> genTypeDefsContextMap;
74 * The map which maps schema paths to JAVA <code>Type</code>.
76 private final Map<SchemaPath, Type> referencedTypes;
79 * Creates new instance of class <code>TypeProviderImpl</code>.
81 * @param schemaContext
82 * contains the schema data red from YANG files
83 * @throws IllegalArgumentException
84 * if <code>schemaContext</code> equal null.
86 public TypeProviderImpl(final SchemaContext schemaContext) {
87 Preconditions.checkArgument(schemaContext != null,"Schema Context cannot be null!");
89 this.schemaContext = schemaContext;
90 this.genTypeDefsContextMap = new HashMap<>();
91 this.referencedTypes = new HashMap<>();
92 resolveTypeDefsFromContext();
96 * Puts <code>refType</code> to map with key <code>refTypePath</code>
99 * schema path used as the map key
101 * type which represents the map value
102 * @throws IllegalArgumentException
104 * <li>if <code>refTypePath</code> equal null</li>
105 * <li>if <code>refType</code> equal null</li>
109 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
110 Preconditions.checkArgument(refTypePath != null,"Path reference of Enumeration Type Definition cannot be NULL!");
112 Preconditions.checkArgument(refType != null,"Reference to Enumeration Type cannot be NULL!");
113 referencedTypes.put(refTypePath, refType);
118 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
121 * string with YANG name of type
122 * @returns JAVA <code>Type</code> for YANG type <code>type</code>
123 * @see org.opendaylight.controller.yang.model.type.provider.TypeProvider#
124 * javaTypeForYangType(java.lang.String)
127 public Type javaTypeForYangType(String type) {
128 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
132 * Converts schema definition type <code>typeDefinition</code> to JAVA
135 * @param typeDefinition
136 * type definition which is converted to JAVA type
137 * @throws IllegalArgumentException
139 * <li>if <code>typeDefinition</code> equal null</li>
140 * <li>if Q name of <code>typeDefinition</code> equal null</li>
141 * <li>if name of <code>typeDefinition</code> equal null</li>
145 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition) {
146 Type returnType = null;
147 Preconditions.checkArgument(typeDefinition != null,"Type Definition cannot be NULL!");
148 if (typeDefinition.getQName() == null) {
149 throw new IllegalArgumentException(
150 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
152 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,"Type Definitions Local Name cannot be NULL!");
154 if (typeDefinition instanceof ExtendedType) {
155 returnType = javaTypeForExtendedType(typeDefinition);
157 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition);
158 if (returnType == null) {
159 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition);
162 // TODO: add throw exception when we will be able to resolve ALL yang
164 // if (returnType == null) {
165 // throw new IllegalArgumentException("Type Provider can't resolve " +
166 // "type for specified Type Definition " + typedefName);
172 * Returns JAVA <code>Type</code> for instances of the type
173 * <code>LeafrefTypeDefinition</code> or
174 * <code>IdentityrefTypeDefinition</code>.
176 * @param typeDefinition
177 * type definition which is converted to JAVA <code>Type</code>
178 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
180 private Type javaTypeForLeafrefOrIdentityRef(TypeDefinition<?> typeDefinition) {
181 if (typeDefinition instanceof LeafrefTypeDefinition) {
182 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
183 return provideTypeForLeafref(leafref);
184 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
185 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
186 return provideTypeForIdentityref(idref);
193 * Returns JAVA <code>Type</code> for instances of the type
194 * <code>ExtendedType</code>.
196 * @param typeDefinition
197 * type definition which is converted to JAVA <code>Type</code>
198 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
200 private Type javaTypeForExtendedType(TypeDefinition<?> typeDefinition) {
201 final String typedefName = typeDefinition.getQName().getLocalName();
202 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
203 Type returnType = null;
204 returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef);
205 if (returnType == null) {
206 if (baseTypeDef instanceof EnumTypeDefinition) {
207 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
208 returnType = provideTypeForEnum(enumTypeDef, typedefName);
210 final Module module = findParentModuleForTypeDefinition(schemaContext, typeDefinition);
211 if (module != null) {
212 final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
213 if (genTOs != null) {
214 returnType = genTOs.get(typedefName);
216 if (returnType == null) {
217 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
218 .javaTypeForSchemaDefinitionType(baseTypeDef);
227 * Seeks for identity reference <code>idref</code> the JAVA
228 * <code>type</code>.<br />
232 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
233 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
236 * identityref type definition for which JAVA <code>Type</code>
238 * @return JAVA <code>Type</code> of the identity which is refrenced through
241 private Type provideTypeForIdentityref(IdentityrefTypeDefinition idref) {
242 QName baseIdQName = idref.getIdentity();
243 Module module = schemaContext.findModuleByNamespace(baseIdQName.getNamespace());
244 IdentitySchemaNode identity = null;
245 for (IdentitySchemaNode id : module.getIdentities()) {
246 if (id.getQName().equals(baseIdQName)) {
250 Preconditions.checkArgument(identity != null,"Target identity '" + baseIdQName + "' do not exists");
252 final String basePackageName = moduleNamespaceToPackageName(module);
253 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
254 final String genTypeName = parseToClassName(identity.getQName().getLocalName());
256 Type baseType = Types.typeForClass(Class.class);
257 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
258 return Types.parameterizedTypeFor(baseType, paramType);
262 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
264 * @param typeDefinition
265 * type definition which should be converted to JAVA
267 * @return JAVA <code>Type</code> which represents
268 * <code>typeDefinition</code>
269 * @throws IllegalArgumentException
271 * <li>if <code>typeDefinition</code> equal null</li>
272 * <li>if Q name of <code>typeDefinition</code></li>
273 * <li>if name of <code>typeDefinition</code></li>
276 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition) {
277 Type returnType = null;
278 Preconditions.checkArgument(typeDefinition != null,"Type Definition cannot be NULL!");
279 if (typeDefinition.getQName() == null) {
280 throw new IllegalArgumentException(
281 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
283 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,"Type Definitions Local Name cannot be NULL!");
285 final String typedefName = typeDefinition.getQName().getLocalName();
286 if (typeDefinition instanceof ExtendedType) {
287 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
289 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
290 final Module module = findParentModuleForTypeDefinition(schemaContext, typeDefinition);
292 if (module != null) {
293 final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
294 if (genTOs != null) {
295 returnType = genTOs.get(typedefName);
304 * Gets base type definition for <code>extendTypeDef</code>. The method is
305 * recursivelly called until non <code>ExtendedType</code> type is found.
307 * @param extendTypeDef
308 * type definition for which is the base type definition sought
309 * @return type definition which is base type for <code>extendTypeDef</code>
310 * @throws IllegalArgumentException
311 * if <code>extendTypeDef</code> equal null
313 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
314 Preconditions.checkArgument(extendTypeDef != null,"Type Definiition reference cannot be NULL!");
315 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
316 if (baseTypeDef instanceof ExtendedType) {
317 return baseTypeDefForExtendedType(baseTypeDef);
325 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
327 * The path of <code>leafrefType</code> is followed to find referenced node
328 * and its <code>Type</code> is returned.
331 * leafref type definition for which is the type sought
332 * @return JAVA <code>Type</code> of data schema node which is referenced in
333 * <code>leafrefType</code>
334 * @throws IllegalArgumentException
336 * <li>if <code>leafrefType</code> equal null</li>
337 * <li>if path statement of <code>leafrefType</code> equal null</li>
341 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType) {
342 Type returnType = null;
343 Preconditions.checkArgument(leafrefType != null,"Leafref Type Definition reference cannot be NULL!");
345 Preconditions.checkArgument(leafrefType.getPathStatement() != null,"The Path Statement for Leafref Type Definition cannot be NULL!");
347 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
348 final String strXPath = xpath.toString();
350 if (strXPath != null) {
351 if (strXPath.contains("[")) {
352 returnType = Types.typeForClass(Object.class);
354 final Module module = findParentModuleForTypeDefinition(schemaContext, leafrefType);
355 if (module != null) {
356 final DataSchemaNode dataNode;
357 if (xpath.isAbsolute()) {
358 dataNode = findDataSchemaNode(schemaContext, module, xpath);
360 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, leafrefType, xpath);
363 if (leafContainsEnumDefinition(dataNode)) {
364 returnType = referencedTypes.get(dataNode.getPath());
365 } else if (leafListContainsEnumDefinition(dataNode)) {
366 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
368 returnType = resolveTypeFromDataSchemaNode(dataNode);
377 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
378 * so then checks if it is of type <code>EnumTypeDefinition</code>.
381 * data schema node for which is checked if it is leaf and if it
383 * @return boolean value
385 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
386 * <li>false - other cases</li>
389 private boolean leafContainsEnumDefinition(final DataSchemaNode dataNode) {
390 if (dataNode instanceof LeafSchemaNode) {
391 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
392 if (leaf.getType() instanceof EnumTypeDefinition) {
400 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
401 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
404 * data schema node for which is checked if it is leaflist and if
406 * @return boolean value
408 * <li>true - if <code>dataNode</code> is leaflist of type
410 * <li>false - other cases</li>
413 private boolean leafListContainsEnumDefinition(final DataSchemaNode dataNode) {
414 if (dataNode instanceof LeafListSchemaNode) {
415 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
416 if (leafList.getType() instanceof EnumTypeDefinition) {
424 * Converts <code>enumTypeDef</code> to
425 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
429 * enumeration type definition which is converted to enumeration
431 * string with name which is used as the enumeration name
432 * @return enumeration type which is built with data (name, enum values)
433 * from <code>enumTypeDef</code>
434 * @throws IllegalArgumentException
436 * <li>if <code>enumTypeDef</code> equals null</li>
437 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
438 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
439 * <li>if name of <code>enumTypeDef</code> equal null</li>
442 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName) {
443 Preconditions.checkArgument(enumTypeDef != null,"EnumTypeDefinition reference cannot be NULL!");
444 Preconditions.checkArgument(enumTypeDef.getValues() != null,"EnumTypeDefinition MUST contain at least ONE value definition!");
445 Preconditions.checkArgument(enumTypeDef.getQName() != null,"EnumTypeDefinition MUST contain NON-NULL QName!");
446 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,"Local Name in EnumTypeDefinition QName cannot be NULL!");
448 final String enumerationName = parseToClassName(enumName);
450 Module module = findParentModuleForTypeDefinition(schemaContext, enumTypeDef);
451 final String basePackageName = moduleNamespaceToPackageName(module);
453 final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
454 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
455 return enumBuilder.toInstance(null);
459 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
460 * taken from <code>enumTypeDef</code>.
463 * enumeration type definition is source of enumeration data for
464 * <code>typeBuilder</code>
466 * string with the name of enumeration
468 * generated type builder to which is enumeration added
469 * @return enumeration type which contains enumeration data form
470 * <code>enumTypeDef</code>
471 * @throws IllegalArgumentException
473 * <li>if <code>enumTypeDef</code> equals null</li>
474 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
475 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
476 * <li>if name of <code>enumTypeDef</code> equal null</li>
477 * <li>if name of <code>typeBuilder</code> equal null</li>
481 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
482 final GeneratedTypeBuilder typeBuilder) {
483 Preconditions.checkArgument(enumTypeDef != null,"EnumTypeDefinition reference cannot be NULL!");
484 Preconditions.checkArgument(enumTypeDef.getValues() != null,"EnumTypeDefinition MUST contain at least ONE value definition!");
485 Preconditions.checkArgument(enumTypeDef.getQName() != null,"EnumTypeDefinition MUST contain NON-NULL QName!");
486 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,"Local Name in EnumTypeDefinition QName cannot be NULL!");
487 Preconditions.checkArgument(typeBuilder != null,"Generated Type Builder reference cannot be NULL!");
489 final String enumerationName = parseToClassName(enumName);
491 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
492 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
493 return enumBuilder.toInstance(enumBuilder);
497 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
500 * contains information about YANG type
501 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
503 private Type resolveTypeFromDataSchemaNode(final DataSchemaNode dataNode) {
504 Type returnType = null;
505 if (dataNode != null) {
506 if (dataNode instanceof LeafSchemaNode) {
507 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
508 returnType = javaTypeForSchemaDefinitionType(leaf.getType());
509 } else if (dataNode instanceof LeafListSchemaNode) {
510 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
511 returnType = javaTypeForSchemaDefinitionType(leafList.getType());
518 * Passes through all modules and through all its type definitions and
519 * convert it to generated types.
521 * The modules are firstly sorted by mutual dependencies. The modules are
522 * sequentially passed. All type definitions of a module are at the
523 * beginning sorted so that type definition with less amount of references
524 * to other type definition are processed first.<br />
525 * For each module is created mapping record in the map
526 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
527 * which map current module name to the map which maps type names to
528 * returned types (generated types).
531 private void resolveTypeDefsFromContext() {
532 final Set<Module> modules = schemaContext.getModules();
533 Preconditions.checkArgument(modules != null,"Sef of Modules cannot be NULL!");
534 final Module[] modulesArray = new Module[modules.size()];
536 for (Module modul : modules) {
537 modulesArray[i++] = modul;
539 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modulesArray);
541 for (final Module module : modulesSortedByDependency) {
542 if (module == null) {
545 final String moduleName = module.getName();
546 final String basePackageName = moduleNamespaceToPackageName(module);
548 final Set<TypeDefinition<?>> typeDefinitions = module.getTypeDefinitions();
549 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
551 final Map<String, Type> typeMap = new HashMap<>();
552 genTypeDefsContextMap.put(moduleName, typeMap);
554 if ((listTypeDefinitions != null) && (basePackageName != null)) {
555 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
556 typedefToGeneratedType(basePackageName, moduleName, typedef);
564 * @param basePackageName
565 * string with name of package to which the module belongs
567 * string with the name of the module for to which the
568 * <code>typedef</code> belongs
570 * type definition of the node for which should be creted JAVA
571 * <code>Type</code> (usually generated TO)
572 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
573 * <code>null</code> value if <code>basePackageName</code> or
574 * <code>modulName</code> or <code>typedef</code> or Q name of
575 * <code>typedef</code> equals <code>null</code>
577 private Type typedefToGeneratedType(final String basePackageName, final String moduleName,
578 final TypeDefinition<?> typedef) {
579 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
581 final String typedefName = typedef.getQName().getLocalName();
582 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
583 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
584 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
585 Type returnType = null;
586 if (innerTypeDefinition instanceof ExtendedType) {
587 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
588 returnType = provideGeneratedTOFromExtendedType(innerExtendedType, basePackageName, typedefName);
589 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
590 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
591 typedef, typedefName);
592 returnType = genTOBuilder.toInstance();
593 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
594 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
595 returnType = provideTypeForEnum(enumTypeDef, typedefName);
597 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
598 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
599 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
600 basePackageName, bitsTypeDefinition, typedefName);
601 returnType = genTOBuilder.toInstance();
604 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
605 .javaTypeForSchemaDefinitionType(innerTypeDefinition);
607 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
609 if (returnType != null) {
610 final Map<String, Type> typeMap = genTypeDefsContextMap.get(moduleName);
611 if (typeMap != null) {
612 typeMap.put(typedefName, returnType);
622 * Wraps base YANG type to generated TO.
624 * @param basePackageName
625 * string with name of package to which the module belongs
627 * type definition which is converted to the TO
629 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
630 * @return generated transfer object which represent<code>javaType</code>
632 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
633 final Type javaType) {
634 if (javaType != null) {
635 final String typedefName = typedef.getQName().getLocalName();
636 final String propertyName = "value";
638 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
640 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
642 genPropBuilder.setReturnType(javaType);
643 genTOBuilder.addEqualsIdentity(genPropBuilder);
644 genTOBuilder.addHashIdentity(genPropBuilder);
645 genTOBuilder.addToStringProperty(genPropBuilder);
646 if (javaType == BaseYangTypes.STRING_TYPE && typedef instanceof ExtendedType) {
647 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
648 addStringRegExAsConstant(genTOBuilder, regExps);
650 return genTOBuilder.toInstance();
656 * Converts output list of generated TO builders to one TO builder (first
657 * from list) which contains the remaining builders as its enclosing TO.
659 * @param basePackageName
660 * string with name of package to which the module belongs
662 * type definition which should be of type
663 * <code>UnionTypeDefinition</code>
665 * string with name for generated TO
666 * @return generated TO builder with the list of enclosed generated TO
669 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
670 final TypeDefinition<?> typedef, String typeDefName) {
671 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
672 typedef, typeDefName);
673 GeneratedTOBuilder resultTOBuilder = null;
674 if (!genTOBuilders.isEmpty()) {
675 resultTOBuilder = genTOBuilders.get(0);
676 genTOBuilders.remove(0);
677 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
678 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
681 return resultTOBuilder;
685 * Converts <code>typedef</code> to generated TO with
686 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
687 * added to generated TO builder as property.
689 * @param basePackageName
690 * string with name of package to which the module belongs
692 * type definition which should be of type
693 * <code>UnionTypeDefinition</code>
695 * string with name for generated TO
696 * @return generated TO builder which represents <code>typedef</code>
697 * @throws IllegalArgumentException
699 * <li>if <code>basePackageName</code> equals null</li>
700 * <li>if <code>typedef</code> equals null</li>
701 * <li>if Q name of <code>typedef</code> equals null</li>
704 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
705 final TypeDefinition<?> typedef, final String typeDefName) {
706 Preconditions.checkArgument(basePackageName != null,"Base Package Name cannot be NULL!");
707 Preconditions.checkArgument(typedef != null,"Type Definition cannot be NULL!");
708 if (typedef.getQName() == null) {
709 throw new IllegalArgumentException(
710 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
713 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
715 final TypeDefinition<?> baseTypeDefinition = typedef.getBaseType();
716 if ((baseTypeDefinition != null) && (baseTypeDefinition instanceof UnionTypeDefinition)) {
717 final UnionTypeDefinition unionTypeDef = (UnionTypeDefinition) baseTypeDefinition;
718 final List<TypeDefinition<?>> unionTypes = unionTypeDef.getTypes();
720 final GeneratedTOBuilder unionGenTOBuilder;
721 if (typeDefName != null && !typeDefName.isEmpty()) {
722 final String typeName = parseToClassName(typeDefName);
723 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
725 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
727 generatedTOBuilders.add(unionGenTOBuilder);
728 unionGenTOBuilder.setIsUnion(true);
730 final List<String> regularExpressions = new ArrayList<String>();
731 for (final TypeDefinition<?> unionType : unionTypes) {
732 final String unionTypeName = unionType.getQName().getLocalName();
733 if (unionType instanceof UnionType) {
735 .addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, unionType, basePackageName));
736 } else if (unionType instanceof ExtendedType) {
737 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, unionTypeName,
739 } else if (unionType instanceof EnumTypeDefinition) {
740 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
741 unionTypeName, unionGenTOBuilder);
742 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
744 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
745 .javaTypeForSchemaDefinitionType(unionType);
746 if (javaType != null) {
747 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
751 if (!regularExpressions.isEmpty()) {
752 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
755 storeGenTO(typedef, unionGenTOBuilder);
757 return generatedTOBuilders;
761 * Wraps code which handle case when union subtype is also of the type
762 * <code>UnionType</code>.
764 * In this case the new generated TO is created for union subtype (recursive
766 * {@link #provideGeneratedTOBuilderForUnionTypeDef(String, TypeDefinition, String)
767 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
768 * <code>parentUnionGenTOBuilder</code> is created property which type is
769 * equal to new generated TO.
771 * @param parentUnionGenTOBuilder
772 * generated TO builder to which is the property with the child
773 * union subtype added
774 * @param basePackageName
775 * string with the name of the module package
776 * @param unionSubtype
777 * type definition which represents union subtype
778 * @return list of generated TO builders. The number of the builders can be
779 * bigger one due to recursive call of
780 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
782 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
783 final TypeDefinition<?> unionSubtype, final String basePackageName) {
784 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
785 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
786 basePackageName, unionSubtype, newTOBuilderName);
788 GeneratedPropertyBuilder propertyBuilder = parentUnionGenTOBuilder.addProperty(newTOBuilderName);
789 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
790 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
791 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
793 return subUnionGenTOBUilders;
797 * Wraps code which handle case when union subtype is of the type
798 * <code>ExtendedType</code>.
800 * If TO for this type already exists it is used for the creation of the
801 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
802 * type is used for the property creation.
804 * @param parentUnionGenTOBuilder
805 * generated TO builder in which new property is created
806 * @param unionSubtype
807 * type definition of the <code>ExtendedType</code> type which
808 * represents union subtype
809 * @param unionTypeName
810 * string with the name for <code>unionSubtype</code>
811 * @param regularExpressions
812 * list of strings with the regular expressions
814 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
815 final ExtendedType unionSubtype, final String unionTypeName, final List<String> regularExpressions) {
816 final Type genTO = findGenTO(unionSubtype, unionTypeName);
818 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
820 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
821 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
822 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType);
823 if (javaType != null) {
824 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
827 if (baseType instanceof StringType) {
828 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
834 * Searches for generated TO for <code>searchedTypeDef</code> type
835 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
837 * @param searchedTypeDef
838 * type definition for which is generatet TO sought
839 * @param searchedTypeName
840 * string with name of <code>searchedTypeDef</code>
841 * @return generated TO for <code>searchedTypeDef</code> or
842 * <code>null</code> it it doesn't exist
844 private Type findGenTO(final TypeDefinition<?> searchedTypeDef, final String searchedTypeName) {
845 final Module typeModule = findParentModuleForTypeDefinition(schemaContext, searchedTypeDef);
846 if (typeModule != null && typeModule.getName() != null) {
847 final Map<String, Type> genTOs = genTypeDefsContextMap.get(typeModule.getName());
848 if (genTOs != null) {
849 return genTOs.get(searchedTypeName);
856 * Stores generated TO created from <code>genTOBuilder</code> for
857 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
858 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
861 * type definition for which is <code>genTOBuilder</code> created
862 * @param genTOBuilder
863 * generated TO builder which is converted to generated TO and
866 private void storeGenTO(TypeDefinition<?> newTypeDef, GeneratedTOBuilder genTOBuilder) {
867 if (!(newTypeDef instanceof UnionType)) {
868 Map<String, Type> genTOsMap = null;
869 final Module parentModule = findParentModuleForTypeDefinition(schemaContext, newTypeDef);
870 if (parentModule != null && parentModule.getName() != null) {
871 genTOsMap = genTypeDefsContextMap.get(parentModule.getName());
872 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
878 * Adds a new property with the name <code>propertyName</code> and with type
879 * <code>type</code> to <code>unonGenTransObject</code>.
881 * @param unionGenTransObject
882 * generated TO to which should be property added
884 * JAVA <code>type</code> of the property which should be added
885 * to <code>unionGentransObject</code>
886 * @param propertyName
887 * string with name of property which should be added to
888 * <code>unionGentransObject</code>
890 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
891 final String propertyName) {
892 if (unionGenTransObject != null && type != null) {
893 if (!unionGenTransObject.containsProperty(propertyName)) {
894 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
895 .addProperty(parseToValidParamName(propertyName));
896 propBuilder.setReturnType(type);
898 unionGenTransObject.addEqualsIdentity(propBuilder);
899 unionGenTransObject.addHashIdentity(propBuilder);
900 unionGenTransObject.addToStringProperty(propBuilder);
906 * Converts <code>typedef</code> to the generated TO builder.
908 * @param basePackageName
909 * string with name of package to which the module belongs
911 * type definition from which is the generated TO builder created
912 * @return generated TO builder which contains data from
913 * <code>typedef</code> and <code>basePackageName</code>
915 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
917 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
918 final String typeDefTOName = typedef.getQName().getLocalName();
920 if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
921 final String genTOName = parseToClassName(typeDefTOName);
922 final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
930 * Converts <code>typeDef</code> which should be of the type
931 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
933 * All the bits of the typeDef are added to returning generated TO as
936 * @param basePackageName
937 * string with name of package to which the module belongs
939 * type definition from which is the generated TO builder created
941 * string with the name for generated TO builder
942 * @return generated TO builder which represents <code>typeDef</code>
943 * @throws IllegalArgumentException
945 * <li>if <code>typeDef</code> equals null</li>
946 * <li>if <code>basePackageName</code> equals null</li>
949 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
950 final TypeDefinition<?> typeDef, String typeDefName) {
952 Preconditions.checkArgument(typeDef != null,"typeDef cannot be NULL!");
953 Preconditions.checkArgument(basePackageName != null,"Base Package Name cannot be NULL!");
955 if (typeDef instanceof BitsTypeDefinition) {
956 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
958 final String typeName = parseToClassName(typeDefName);
959 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
961 final List<Bit> bitList = bitsTypeDefinition.getBits();
962 GeneratedPropertyBuilder genPropertyBuilder;
963 for (final Bit bit : bitList) {
964 String name = bit.getName();
965 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
966 genPropertyBuilder.setReadOnly(true);
967 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
969 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
970 genTOBuilder.addHashIdentity(genPropertyBuilder);
971 genTOBuilder.addToStringProperty(genPropertyBuilder);
980 * Converts the pattern constraints from <code>typedef</code> to the list of
981 * the strings which represents these constraints.
984 * extended type in which are the pattern constraints sought
985 * @return list of strings which represents the constraint patterns
986 * @throws IllegalArgumentException
987 * if <code>typedef</code> equals null
990 private List<String> resolveRegExpressionsFromTypedef(ExtendedType typedef) {
991 final List<String> regExps = new ArrayList<String>();
992 Preconditions.checkArgument(typedef != null,"typedef can't be null");
993 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
994 if (strTypeDef instanceof StringType) {
995 final List<PatternConstraint> patternConstraints = typedef.getPatterns();
996 if (!patternConstraints.isEmpty()) {
998 String modifiedRegEx;
999 for (PatternConstraint patternConstraint : patternConstraints) {
1000 regEx = patternConstraint.getRegularExpression();
1001 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1002 regExps.add(modifiedRegEx);
1011 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1012 * expressions from the <code>regularExpressions</code>
1014 * @param genTOBuilder
1015 * generated TO builder to which are
1016 * <code>regular expressions</code> added
1017 * @param regularExpressions
1018 * list of string which represent regular expressions
1019 * @throws IllegalArgumentException
1021 * <li>if <code>genTOBuilder</code> equals null</li>
1022 * <li>if <code>regularExpressions</code> equals null</li>
1025 private void addStringRegExAsConstant(GeneratedTOBuilder genTOBuilder, List<String> regularExpressions) {
1026 if (genTOBuilder == null)
1027 throw new IllegalArgumentException("genTOBuilder can't be null");
1028 if (regularExpressions == null)
1029 throw new IllegalArgumentException("regularExpressions can't be null");
1031 if (!regularExpressions.isEmpty()) {
1032 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1033 regularExpressions);
1038 * Creates generated TO with data about inner extended type
1039 * <code>innerExtendedType</code>, about the package name
1040 * <code>typedefName</code> and about the generated TO name
1041 * <code>typedefName</code>.
1043 * It is supposed that <code>innerExtendedType</code> is already present in
1044 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1045 * be possible set it as extended type for the returning generated TO.
1047 * @param innerExtendedType
1048 * extended type which is part of some other extended type
1049 * @param basePackageName
1050 * string with the package name of the module
1051 * @param typedefName
1052 * string with the name for the generated TO
1053 * @return generated TO which extends generated TO for
1054 * <code>innerExtendedType</code>
1055 * @throws IllegalArgumentException
1057 * <li>if <code>extendedType</code> equals null</li>
1058 * <li>if <code>basePackageName</code> equals null</li>
1059 * <li>if <code>typedefName</code> equals null</li>
1062 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final ExtendedType innerExtendedType,
1063 final String basePackageName, final String typedefName) {
1065 Preconditions.checkArgument(innerExtendedType != null,"Extended type cannot be NULL!");
1066 Preconditions.checkArgument(basePackageName != null,"String with base package name cannot be NULL!");
1067 Preconditions.checkArgument(typedefName != null,"String with type definition name cannot be NULL!");
1069 final String classTypedefName = parseToClassName(typedefName);
1070 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1071 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1073 Map<String, Type> typeMap = null;
1074 final Module parentModule = findParentModuleForTypeDefinition(schemaContext, innerExtendedType);
1075 if (parentModule != null) {
1076 typeMap = genTypeDefsContextMap.get(parentModule.getName());
1079 if (typeMap != null) {
1080 Type type = typeMap.get(innerTypeDef);
1081 if (type instanceof GeneratedTransferObject) {
1082 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1086 return genTOBuilder.toInstance();
1090 * Finds out for each type definition how many immersion (depth) is
1091 * necessary to get to the base type. Every type definition is inserted to
1092 * the map which key is depth and value is list of type definitions with
1093 * equal depth. In next step are lists from this map concatenated to one
1094 * list in ascending order according to their depth. All type definitions
1095 * are in the list behind all type definitions on which depends.
1097 * @param unsortedTypeDefinitions
1098 * list of type definitions which should be sorted by depth
1099 * @return list of type definitions sorted according their each other
1100 * dependencies (type definitions which are depend on other type
1101 * definitions are in list behind them).
1103 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1104 final Set<TypeDefinition<?>> unsortedTypeDefinitions) {
1105 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1107 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1108 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1109 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1110 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1111 if (typeDefinitionsConcreteDepth == null) {
1112 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1113 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1115 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1118 Set<Integer> depths = typeDefinitionsDepths.keySet(); // keys are in
1120 for (Integer depth : depths) {
1121 sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1124 return sortedTypeDefinition;
1128 * Returns how many immersion is necessary to get from the type definition
1131 * @param typeDefinition
1132 * type definition for which is depth sought.
1133 * @return number of immersions which are necessary to get from the type
1134 * definition to the base type
1136 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1137 Preconditions.checkArgument(typeDefinition != null,"Type definition can't be null");
1139 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1141 if (baseType instanceof ExtendedType) {
1142 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1143 } else if (baseType instanceof UnionType) {
1144 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1145 int maxChildDepth = 0;
1147 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1148 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition.getBaseType());
1149 if (childDepth > maxChildDepth) {
1150 maxChildDepth = childDepth;
1153 return maxChildDepth;
1159 * Returns string which contains the same value as <code>name</code> but
1160 * integer suffix is incremented by one. If <code>name</code> contains no
1161 * number suffix then number 1 is added.
1164 * string with name of augmented node
1165 * @return string with the number suffix incremented by one (or 1 is added)
1167 private String provideAvailableNameForGenTOBuilder(String name) {
1168 Pattern searchedPattern = Pattern.compile("[0-9]+\\z");
1169 Matcher mtch = searchedPattern.matcher(name);
1171 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1172 return name.substring(0, mtch.start()) + newSuffix;