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.BindingGeneratorUtil;
24 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
25 import org.opendaylight.yangtools.binding.generator.util.Types;
26 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
27 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
28 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
29 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
30 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
31 import org.opendaylight.yangtools.sal.binding.model.api.Type;
32 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
33 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
34 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
35 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
36 import org.opendaylight.yangtools.yang.common.QName;
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.SchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
45 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
48 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
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,
111 "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, final SchemaNode parentNode) {
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,
153 "Type Definitions Local Name cannot be NULL!");
155 if (typeDefinition instanceof ExtendedType) {
156 returnType = javaTypeForExtendedType(typeDefinition);
158 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
159 if (returnType == null) {
160 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
164 // TODO: add throw exception when we will be able to resolve ALL yang
166 // if (returnType == null) {
167 // throw new IllegalArgumentException("Type Provider can't resolve " +
168 // "type for specified Type Definition " + typedefName);
174 * Returns JAVA <code>Type</code> for instances of the type
175 * <code>LeafrefTypeDefinition</code> or
176 * <code>IdentityrefTypeDefinition</code>.
178 * @param typeDefinition
179 * type definition which is converted to JAVA <code>Type</code>
180 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
182 private Type javaTypeForLeafrefOrIdentityRef(TypeDefinition<?> typeDefinition, SchemaNode parentNode) {
183 if (typeDefinition instanceof LeafrefTypeDefinition) {
184 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
185 return provideTypeForLeafref(leafref, parentNode);
186 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
187 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
188 return provideTypeForIdentityref(idref);
195 * Returns JAVA <code>Type</code> for instances of the type
196 * <code>ExtendedType</code>.
198 * @param typeDefinition
199 * type definition which is converted to JAVA <code>Type</code>
200 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
202 private Type javaTypeForExtendedType(TypeDefinition<?> typeDefinition) {
203 final String typedefName = typeDefinition.getQName().getLocalName();
204 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
205 Type returnType = null;
206 returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
207 if (returnType == null) {
208 if (baseTypeDef instanceof EnumTypeDefinition) {
209 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
210 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
212 final Module module = findParentModule(schemaContext, typeDefinition);
213 if (module != null) {
214 final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
215 if (genTOs != null) {
216 returnType = genTOs.get(typedefName);
218 if (returnType == null) {
219 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
220 baseTypeDef, typeDefinition);
226 // TODO: add throw exception when we will be able to resolve ALL yang
228 // if (returnType == null) {
229 // throw new IllegalArgumentException("Type Provider can't resolve " +
230 // "type for specified Type Definition " + typedefName);
235 * Seeks for identity reference <code>idref</code> the JAVA
236 * <code>type</code>.<br />
240 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
241 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
244 * identityref type definition for which JAVA <code>Type</code>
246 * @return JAVA <code>Type</code> of the identity which is refrenced through
249 private Type provideTypeForIdentityref(IdentityrefTypeDefinition idref) {
250 QName baseIdQName = idref.getIdentity();
251 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
252 baseIdQName.getRevision());
253 IdentitySchemaNode identity = null;
254 for (IdentitySchemaNode id : module.getIdentities()) {
255 if (id.getQName().equals(baseIdQName)) {
259 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
261 final String basePackageName = moduleNamespaceToPackageName(module);
262 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
263 final String genTypeName = parseToClassName(identity.getQName().getLocalName());
265 Type baseType = Types.typeForClass(Class.class);
266 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
267 return Types.parameterizedTypeFor(baseType, paramType);
271 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
273 * @param typeDefinition
274 * type definition which should be converted to JAVA
276 * @return JAVA <code>Type</code> which represents
277 * <code>typeDefinition</code>
278 * @throws IllegalArgumentException
280 * <li>if <code>typeDefinition</code> equal null</li>
281 * <li>if Q name of <code>typeDefinition</code></li>
282 * <li>if name of <code>typeDefinition</code></li>
285 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
286 final SchemaNode parentNode) {
287 Type returnType = null;
288 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
289 if (typeDefinition.getQName() == null) {
290 throw new IllegalArgumentException(
291 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
293 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
294 "Type Definitions Local Name cannot be NULL!");
296 final String typedefName = typeDefinition.getQName().getLocalName();
297 if (typeDefinition instanceof ExtendedType) {
298 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
300 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
301 final Module module = findParentModule(schemaContext, parentNode);
303 if (module != null) {
304 final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
305 if (genTOs != null) {
306 returnType = genTOs.get(typedefName);
315 * Gets base type definition for <code>extendTypeDef</code>. The method is
316 * recursivelly called until non <code>ExtendedType</code> type is found.
318 * @param extendTypeDef
319 * type definition for which is the base type definition sought
320 * @return type definition which is base type for <code>extendTypeDef</code>
321 * @throws IllegalArgumentException
322 * if <code>extendTypeDef</code> equal null
324 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
325 Preconditions.checkArgument(extendTypeDef != null, "Type Definiition reference cannot be NULL!");
326 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
327 if (baseTypeDef instanceof ExtendedType) {
328 return baseTypeDefForExtendedType(baseTypeDef);
336 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
338 * The path of <code>leafrefType</code> is followed to find referenced node
339 * and its <code>Type</code> is returned.
342 * leafref type definition for which is the type sought
343 * @return JAVA <code>Type</code> of data schema node which is referenced in
344 * <code>leafrefType</code>
345 * @throws IllegalArgumentException
347 * <li>if <code>leafrefType</code> equal null</li>
348 * <li>if path statement of <code>leafrefType</code> equal null</li>
352 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
353 Type returnType = null;
354 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
356 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
357 "The Path Statement for Leafref Type Definition cannot be NULL!");
359 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
360 final String strXPath = xpath.toString();
362 if (strXPath != null) {
363 if (strXPath.contains("[")) {
364 returnType = Types.typeForClass(Object.class);
366 final Module module = findParentModule(schemaContext, parentNode);
367 if (module != null) {
368 final SchemaNode dataNode;
369 if (xpath.isAbsolute()) {
370 dataNode = findDataSchemaNode(schemaContext, module, xpath);
372 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
375 if (leafContainsEnumDefinition(dataNode)) {
376 returnType = referencedTypes.get(dataNode.getPath());
377 } else if (leafListContainsEnumDefinition(dataNode)) {
378 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
380 returnType = resolveTypeFromDataSchemaNode(dataNode);
389 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
390 * so then checks if it is of type <code>EnumTypeDefinition</code>.
393 * data schema node for which is checked if it is leaf and if it
395 * @return boolean value
397 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
398 * <li>false - other cases</li>
401 private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
402 if (dataNode instanceof LeafSchemaNode) {
403 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
404 if (leaf.getType() instanceof EnumTypeDefinition) {
412 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
413 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
416 * data schema node for which is checked if it is leaflist and if
418 * @return boolean value
420 * <li>true - if <code>dataNode</code> is leaflist of type
422 * <li>false - other cases</li>
425 private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
426 if (dataNode instanceof LeafListSchemaNode) {
427 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
428 if (leafList.getType() instanceof EnumTypeDefinition) {
436 * Converts <code>enumTypeDef</code> to
437 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
441 * enumeration type definition which is converted to enumeration
443 * string with name which is used as the enumeration name
444 * @return enumeration type which is built with data (name, enum values)
445 * from <code>enumTypeDef</code>
446 * @throws IllegalArgumentException
448 * <li>if <code>enumTypeDef</code> equals null</li>
449 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
450 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
451 * <li>if name of <code>enumTypeDef</code> equal null</li>
454 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
455 final SchemaNode parentNode) {
456 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
457 Preconditions.checkArgument(enumTypeDef.getValues() != null,
458 "EnumTypeDefinition MUST contain at least ONE value definition!");
459 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
460 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
461 "Local Name in EnumTypeDefinition QName cannot be NULL!");
463 final String enumerationName = parseToClassName(enumName);
465 Module module = findParentModule(schemaContext, parentNode);
466 final String basePackageName = moduleNamespaceToPackageName(module);
468 final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
469 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
470 return enumBuilder.toInstance(null);
474 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
475 * taken from <code>enumTypeDef</code>.
478 * enumeration type definition is source of enumeration data for
479 * <code>typeBuilder</code>
481 * string with the name of enumeration
483 * generated type builder to which is enumeration added
484 * @return enumeration type which contains enumeration data form
485 * <code>enumTypeDef</code>
486 * @throws IllegalArgumentException
488 * <li>if <code>enumTypeDef</code> equals null</li>
489 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
490 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
491 * <li>if name of <code>enumTypeDef</code> equal null</li>
492 * <li>if name of <code>typeBuilder</code> equal null</li>
496 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
497 final GeneratedTypeBuilderBase<?> typeBuilder) {
498 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
499 Preconditions.checkArgument(enumTypeDef.getValues() != null,
500 "EnumTypeDefinition MUST contain at least ONE value definition!");
501 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
502 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
503 "Local Name in EnumTypeDefinition QName cannot be NULL!");
504 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
506 final String enumerationName = parseToClassName(enumName);
508 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
509 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
510 return enumBuilder.toInstance(enumBuilder);
514 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
517 * contains information about YANG type
518 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
520 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
521 Type returnType = null;
522 if (dataNode != null) {
523 if (dataNode instanceof LeafSchemaNode) {
524 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
525 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
526 } else if (dataNode instanceof LeafListSchemaNode) {
527 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
528 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
535 * Passes through all modules and through all its type definitions and
536 * convert it to generated types.
538 * The modules are firstly sorted by mutual dependencies. The modules are
539 * sequentially passed. All type definitions of a module are at the
540 * beginning sorted so that type definition with less amount of references
541 * to other type definition are processed first.<br />
542 * For each module is created mapping record in the map
543 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
544 * which map current module name to the map which maps type names to
545 * returned types (generated types).
548 private void resolveTypeDefsFromContext() {
549 final Set<Module> modules = schemaContext.getModules();
550 Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
551 final Module[] modulesArray = new Module[modules.size()];
553 for (Module modul : modules) {
554 modulesArray[i++] = modul;
556 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modulesArray);
558 for (final Module module : modulesSortedByDependency) {
559 if (module == null) {
562 final String moduleName = module.getName();
563 final String basePackageName = moduleNamespaceToPackageName(module);
565 final Set<TypeDefinition<?>> typeDefinitions = module.getTypeDefinitions();
566 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
568 final Map<String, Type> typeMap = new HashMap<>();
569 genTypeDefsContextMap.put(moduleName, typeMap);
571 if ((listTypeDefinitions != null) && (basePackageName != null)) {
572 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
573 typedefToGeneratedType(basePackageName, moduleName, typedef);
581 * @param basePackageName
582 * string with name of package to which the module belongs
584 * string with the name of the module for to which the
585 * <code>typedef</code> belongs
587 * type definition of the node for which should be creted JAVA
588 * <code>Type</code> (usually generated TO)
589 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
590 * <code>null</code> value if <code>basePackageName</code> or
591 * <code>modulName</code> or <code>typedef</code> or Q name of
592 * <code>typedef</code> equals <code>null</code>
594 private Type typedefToGeneratedType(final String basePackageName, final String moduleName,
595 final TypeDefinition<?> typedef) {
596 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
598 final String typedefName = typedef.getQName().getLocalName();
599 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
600 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
601 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
602 Type returnType = null;
603 if (innerTypeDefinition instanceof ExtendedType) {
604 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
605 returnType = provideGeneratedTOFromExtendedType(innerExtendedType, basePackageName, typedefName);
606 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
607 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
608 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
609 returnType = genTOBuilder.toInstance();
610 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
611 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
612 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
614 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
615 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
616 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
617 basePackageName, bitsTypeDefinition, typedefName);
618 returnType = genTOBuilder.toInstance();
621 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
622 innerTypeDefinition, typedef);
624 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
626 if (returnType != null) {
627 final Map<String, Type> typeMap = genTypeDefsContextMap.get(moduleName);
628 if (typeMap != null) {
629 typeMap.put(typedefName, returnType);
639 * Wraps base YANG type to generated TO.
641 * @param basePackageName
642 * string with name of package to which the module belongs
644 * type definition which is converted to the TO
646 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
647 * @return generated transfer object which represent<code>javaType</code>
649 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
650 final Type javaType) {
651 if (javaType != null) {
652 final String propertyName = "value";
654 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
655 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
656 genPropBuilder.setReturnType(javaType);
657 genTOBuilder.addEqualsIdentity(genPropBuilder);
658 genTOBuilder.addHashIdentity(genPropBuilder);
659 genTOBuilder.addToStringProperty(genPropBuilder);
660 if (javaType == BaseYangTypes.STRING_TYPE && typedef instanceof ExtendedType) {
661 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
662 addStringRegExAsConstant(genTOBuilder, regExps);
664 return genTOBuilder.toInstance();
670 * Converts output list of generated TO builders to one TO builder (first
671 * from list) which contains the remaining builders as its enclosing TO.
673 * @param basePackageName
674 * string with name of package to which the module belongs
676 * type definition which should be of type
677 * <code>UnionTypeDefinition</code>
679 * string with name for generated TO
680 * @return generated TO builder with the list of enclosed generated TO
683 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
684 final UnionTypeDefinition typedef, String typeDefName, SchemaNode parentNode) {
685 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
686 typedef, typeDefName, parentNode);
687 GeneratedTOBuilder resultTOBuilder = null;
688 if (!genTOBuilders.isEmpty()) {
689 resultTOBuilder = genTOBuilders.get(0);
690 genTOBuilders.remove(0);
691 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
692 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
695 return resultTOBuilder;
699 * Converts <code>typedef</code> to generated TO with
700 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
701 * added to generated TO builder as property.
703 * @param basePackageName
704 * string with name of package to which the module belongs
706 * type definition which should be of type
707 * <code>UnionTypeDefinition</code>
709 * string with name for generated TO
710 * @return generated TO builder which represents <code>typedef</code>
711 * @throws IllegalArgumentException
713 * <li>if <code>basePackageName</code> equals null</li>
714 * <li>if <code>typedef</code> equals null</li>
715 * <li>if Q name of <code>typedef</code> equals null</li>
718 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
719 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
720 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
721 Preconditions.checkArgument(typedef != null, "Type Definition cannot be NULL!");
722 Preconditions.checkArgument(typedef.getQName() != null,
723 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
725 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
727 if (typedef != null) {
728 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
730 final GeneratedTOBuilder unionGenTOBuilder;
731 if (typeDefName != null && !typeDefName.isEmpty()) {
732 final String typeName = parseToClassName(typeDefName);
733 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
735 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
737 generatedTOBuilders.add(unionGenTOBuilder);
738 unionGenTOBuilder.setIsUnion(true);
739 final List<String> regularExpressions = new ArrayList<String>();
740 for (final TypeDefinition<?> unionType : unionTypes) {
741 final String unionTypeName = unionType.getQName().getLocalName();
742 if (unionType instanceof UnionType) {
743 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
744 basePackageName, parentNode));
745 } else if (unionType instanceof ExtendedType) {
746 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, unionTypeName,
747 regularExpressions, parentNode);
748 } else if (unionType instanceof EnumTypeDefinition) {
749 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
750 unionTypeName, unionGenTOBuilder);
751 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
753 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
754 unionType, parentNode);
755 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
758 if (!regularExpressions.isEmpty()) {
759 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
762 storeGenTO(typedef, unionGenTOBuilder, parentNode);
764 return generatedTOBuilders;
768 * Wraps code which handle case when union subtype is also of the type
769 * <code>UnionType</code>.
771 * In this case the new generated TO is created for union subtype (recursive
773 * {@link #provideGeneratedTOBuilderForUnionTypeDef(String, TypeDefinition, String)
774 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
775 * <code>parentUnionGenTOBuilder</code> is created property which type is
776 * equal to new generated TO.
778 * @param parentUnionGenTOBuilder
779 * generated TO builder to which is the property with the child
780 * union subtype added
781 * @param basePackageName
782 * string with the name of the module package
783 * @param unionSubtype
784 * type definition which represents union subtype
785 * @return list of generated TO builders. The number of the builders can be
786 * bigger one due to recursive call of
787 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
789 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
790 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
791 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
792 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
793 basePackageName, unionSubtype, newTOBuilderName, parentNode);
795 final GeneratedPropertyBuilder propertyBuilder;
796 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
797 .parseToValidParamName(newTOBuilderName));
798 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
799 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
800 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
802 return subUnionGenTOBUilders;
806 * Wraps code which handle case when union subtype is of the type
807 * <code>ExtendedType</code>.
809 * If TO for this type already exists it is used for the creation of the
810 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
811 * type is used for the property creation.
813 * @param parentUnionGenTOBuilder
814 * generated TO builder in which new property is created
815 * @param unionSubtype
816 * type definition of the <code>ExtendedType</code> type which
817 * represents union subtype
818 * @param unionTypeName
819 * string with the name for <code>unionSubtype</code>
820 * @param regularExpressions
821 * list of strings with the regular expressions
823 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
824 final ExtendedType unionSubtype, final String unionTypeName, final List<String> regularExpressions,
825 final SchemaNode parentNode) {
826 final Type genTO = findGenTO(unionTypeName, parentNode);
828 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
830 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
831 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
832 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
834 if (javaType != null) {
835 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
838 if (baseType instanceof StringType) {
839 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
845 * Searches for generated TO for <code>searchedTypeDef</code> type
846 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
848 * @param searchedTypeName
849 * string with name of <code>searchedTypeDef</code>
850 * @return generated TO for <code>searchedTypeDef</code> or
851 * <code>null</code> it it doesn't exist
853 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
854 final Module typeModule = findParentModule(schemaContext, parentNode);
855 if (typeModule != null && typeModule.getName() != null) {
856 final Map<String, Type> genTOs = genTypeDefsContextMap.get(typeModule.getName());
857 if (genTOs != null) {
858 return genTOs.get(searchedTypeName);
865 * Stores generated TO created from <code>genTOBuilder</code> for
866 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
867 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
870 * type definition for which is <code>genTOBuilder</code> created
871 * @param genTOBuilder
872 * generated TO builder which is converted to generated TO and
875 private void storeGenTO(TypeDefinition<?> newTypeDef, GeneratedTOBuilder genTOBuilder, SchemaNode parentNode) {
876 if (!(newTypeDef instanceof UnionType)) {
877 Map<String, Type> genTOsMap = null;
878 final Module parentModule = findParentModule(schemaContext, parentNode);
879 if (parentModule != null && parentModule.getName() != null) {
880 genTOsMap = genTypeDefsContextMap.get(parentModule.getName());
881 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
887 * Adds a new property with the name <code>propertyName</code> and with type
888 * <code>type</code> to <code>unonGenTransObject</code>.
890 * @param unionGenTransObject
891 * generated TO to which should be property added
893 * JAVA <code>type</code> of the property which should be added
894 * to <code>unionGentransObject</code>
895 * @param propertyName
896 * string with name of property which should be added to
897 * <code>unionGentransObject</code>
899 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
900 final String propertyName) {
901 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
902 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
903 .addProperty(parseToValidParamName(propertyName));
904 propBuilder.setReturnType(type);
906 unionGenTransObject.addEqualsIdentity(propBuilder);
907 unionGenTransObject.addHashIdentity(propBuilder);
908 unionGenTransObject.addToStringProperty(propBuilder);
913 * Converts <code>typedef</code> to the generated TO builder.
915 * @param basePackageName
916 * string with name of package to which the module belongs
918 * type definition from which is the generated TO builder created
919 * @return generated TO builder which contains data from
920 * <code>typedef</code> and <code>basePackageName</code>
922 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
924 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
925 final String typeDefTOName = typedef.getQName().getLocalName();
927 if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
928 final String genTOName = parseToClassName(typeDefTOName);
929 final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
930 newType.addComment(typedef.getDescription());
937 * Converts <code>typeDef</code> which should be of the type
938 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
940 * All the bits of the typeDef are added to returning generated TO as
943 * @param basePackageName
944 * string with name of package to which the module belongs
946 * type definition from which is the generated TO builder created
948 * string with the name for generated TO builder
949 * @return generated TO builder which represents <code>typeDef</code>
950 * @throws IllegalArgumentException
952 * <li>if <code>typeDef</code> equals null</li>
953 * <li>if <code>basePackageName</code> equals null</li>
956 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
957 final TypeDefinition<?> typeDef, String typeDefName) {
959 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
960 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
962 if (typeDef instanceof BitsTypeDefinition) {
963 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
965 final String typeName = parseToClassName(typeDefName);
966 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
968 final List<Bit> bitList = bitsTypeDefinition.getBits();
969 GeneratedPropertyBuilder genPropertyBuilder;
970 for (final Bit bit : bitList) {
971 String name = bit.getName();
972 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
973 genPropertyBuilder.setReadOnly(true);
974 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
976 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
977 genTOBuilder.addHashIdentity(genPropertyBuilder);
978 genTOBuilder.addToStringProperty(genPropertyBuilder);
987 * Converts the pattern constraints from <code>typedef</code> to the list of
988 * the strings which represents these constraints.
991 * extended type in which are the pattern constraints sought
992 * @return list of strings which represents the constraint patterns
993 * @throws IllegalArgumentException
994 * if <code>typedef</code> equals null
997 private List<String> resolveRegExpressionsFromTypedef(ExtendedType typedef) {
998 final List<String> regExps = new ArrayList<String>();
999 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1000 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1001 if (strTypeDef instanceof StringType) {
1002 final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1003 if (!patternConstraints.isEmpty()) {
1005 String modifiedRegEx;
1006 for (PatternConstraint patternConstraint : patternConstraints) {
1007 regEx = patternConstraint.getRegularExpression();
1008 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1009 regExps.add(modifiedRegEx);
1018 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1019 * expressions from the <code>regularExpressions</code>
1021 * @param genTOBuilder
1022 * generated TO builder to which are
1023 * <code>regular expressions</code> added
1024 * @param regularExpressions
1025 * list of string which represent regular expressions
1026 * @throws IllegalArgumentException
1028 * <li>if <code>genTOBuilder</code> equals null</li>
1029 * <li>if <code>regularExpressions</code> equals null</li>
1032 private void addStringRegExAsConstant(GeneratedTOBuilder genTOBuilder, List<String> regularExpressions) {
1033 if (genTOBuilder == null) {
1034 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1036 if (regularExpressions == null) {
1037 throw new IllegalArgumentException("List of regular expressions can't be null");
1039 if (!regularExpressions.isEmpty()) {
1040 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1041 regularExpressions);
1046 * Creates generated TO with data about inner extended type
1047 * <code>innerExtendedType</code>, about the package name
1048 * <code>typedefName</code> and about the generated TO name
1049 * <code>typedefName</code>.
1051 * It is supposed that <code>innerExtendedType</code> is already present in
1052 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1053 * be possible set it as extended type for the returning generated TO.
1055 * @param innerExtendedType
1056 * extended type which is part of some other extended type
1057 * @param basePackageName
1058 * string with the package name of the module
1059 * @param typedefName
1060 * string with the name for the generated TO
1061 * @return generated TO which extends generated TO for
1062 * <code>innerExtendedType</code>
1063 * @throws IllegalArgumentException
1065 * <li>if <code>extendedType</code> equals null</li>
1066 * <li>if <code>basePackageName</code> equals null</li>
1067 * <li>if <code>typedefName</code> equals null</li>
1070 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final ExtendedType innerExtendedType,
1071 final String basePackageName, final String typedefName) {
1073 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1074 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1075 Preconditions.checkArgument(typedefName != null, "String with type definition name cannot be NULL!");
1077 final String classTypedefName = parseToClassName(typedefName);
1078 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1079 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1081 Map<String, Type> typeMap = null;
1082 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1083 if (parentModule != null) {
1084 typeMap = genTypeDefsContextMap.get(parentModule.getName());
1087 if (typeMap != null) {
1088 Type type = typeMap.get(innerTypeDef);
1089 if (type instanceof GeneratedTransferObject) {
1090 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1094 return genTOBuilder.toInstance();
1098 * Finds out for each type definition how many immersion (depth) is
1099 * necessary to get to the base type. Every type definition is inserted to
1100 * the map which key is depth and value is list of type definitions with
1101 * equal depth. In next step are lists from this map concatenated to one
1102 * list in ascending order according to their depth. All type definitions
1103 * are in the list behind all type definitions on which depends.
1105 * @param unsortedTypeDefinitions
1106 * list of type definitions which should be sorted by depth
1107 * @return list of type definitions sorted according their each other
1108 * dependencies (type definitions which are depend on other type
1109 * definitions are in list behind them).
1111 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1112 final Set<TypeDefinition<?>> unsortedTypeDefinitions) {
1113 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1115 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1116 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1117 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1118 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1119 if (typeDefinitionsConcreteDepth == null) {
1120 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1121 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1123 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1125 // keys are in ascending order
1126 Set<Integer> depths = typeDefinitionsDepths.keySet();
1127 for (Integer depth : depths) {
1128 sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1131 return sortedTypeDefinition;
1135 * Returns how many immersion is necessary to get from the type definition
1138 * @param typeDefinition
1139 * type definition for which is depth sought.
1140 * @return number of immersions which are necessary to get from the type
1141 * definition to the base type
1143 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1144 if (typeDefinition == null) {
1148 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1150 if (baseType instanceof ExtendedType) {
1151 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1152 } else if (baseType instanceof UnionType) {
1153 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1154 int maxChildDepth = 0;
1156 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1157 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition.getBaseType());
1158 if (childDepth > maxChildDepth) {
1159 maxChildDepth = childDepth;
1162 return maxChildDepth;
1168 * Returns string which contains the same value as <code>name</code> but
1169 * integer suffix is incremented by one. If <code>name</code> contains no
1170 * number suffix then number 1 is added.
1173 * string with name of augmented node
1174 * @return string with the number suffix incremented by one (or 1 is added)
1176 private String provideAvailableNameForGenTOBuilder(String name) {
1177 Pattern searchedPattern = Pattern.compile("[0-9]+\\z");
1178 Matcher mtch = searchedPattern.matcher(name);
1180 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1181 return name.substring(0, mtch.start()) + newSuffix;