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.moduleNamespaceToPackageName;
11 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
12 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.parseToClassName;
13 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.parseToValidParamName;
14 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
15 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
16 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
18 import java.math.BigDecimal;
19 import java.math.BigInteger;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
25 import org.apache.commons.lang3.StringEscapeUtils;
26 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
27 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
28 import org.opendaylight.yangtools.binding.generator.util.Types;
29 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
30 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
31 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
32 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
33 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
34 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
35 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
36 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
37 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
38 import org.opendaylight.yangtools.sal.binding.model.api.Type;
39 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
40 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
41 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
42 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
43 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
44 import org.opendaylight.yangtools.yang.binding.BindingMapping;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.Module;
50 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
51 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
52 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
54 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.*;
56 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
57 import org.opendaylight.yangtools.yang.model.util.*;
58 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
60 import com.google.common.base.Preconditions;
61 import com.google.common.collect.Sets;
62 import com.google.common.io.BaseEncoding;
64 public final class TypeProviderImpl implements TypeProvider {
66 * Contains the schema data red from YANG files.
68 private final SchemaContext schemaContext;
71 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
73 private Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
76 * The map which maps schema paths to JAVA <code>Type</code>.
78 private final Map<SchemaPath, Type> referencedTypes;
79 private final Map<Module, Set<Type>> additionalTypes;
82 * Creates new instance of class <code>TypeProviderImpl</code>.
84 * @param schemaContext
85 * contains the schema data red from YANG files
86 * @throws IllegalArgumentException
87 * if <code>schemaContext</code> equal null.
89 public TypeProviderImpl(final SchemaContext schemaContext) {
90 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
92 this.schemaContext = schemaContext;
93 this.genTypeDefsContextMap = new HashMap<>();
94 this.referencedTypes = new HashMap<>();
95 this.additionalTypes = new HashMap<>();
96 resolveTypeDefsFromContext();
100 * Puts <code>refType</code> to map with key <code>refTypePath</code>
103 * schema path used as the map key
105 * type which represents the map value
106 * @throws IllegalArgumentException
108 * <li>if <code>refTypePath</code> equal null</li>
109 * <li>if <code>refType</code> equal null</li>
113 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
114 Preconditions.checkArgument(refTypePath != null,
115 "Path reference of Enumeration Type Definition cannot be NULL!");
116 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
117 referencedTypes.put(refTypePath, refType);
120 public Map<Module, Set<Type>> getAdditionalTypes() {
121 return additionalTypes;
126 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
129 * string with YANG name of type
130 * @return JAVA <code>Type</code> for YANG type <code>type</code>
131 * @see TypeProvider#javaTypeForYangType(String)
134 public Type javaTypeForYangType(String type) {
135 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
139 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
140 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
144 * Converts schema definition type <code>typeDefinition</code> to JAVA
147 * @param typeDefinition
148 * type definition which is converted to JAVA type
149 * @throws IllegalArgumentException
151 * <li>if <code>typeDefinition</code> equal null</li>
152 * <li>if Qname of <code>typeDefinition</code> equal null</li>
153 * <li>if name of <code>typeDefinition</code> equal null</li>
157 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
159 Type returnType = null;
160 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
161 if (typeDefinition.getQName() == null) {
162 throw new IllegalArgumentException(
163 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
165 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
166 "Type Definitions Local Name cannot be NULL!");
168 if (typeDefinition instanceof ExtendedType) {
169 returnType = javaTypeForExtendedType(typeDefinition);
171 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
172 if (returnType == null) {
173 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
177 // TODO: add throw exception when we will be able to resolve ALL yang
179 // if (returnType == null) {
180 // throw new IllegalArgumentException("Type Provider can't resolve " +
181 // "type for specified Type Definition " + typedefName);
187 * Returns JAVA <code>Type</code> for instances of the type
188 * <code>LeafrefTypeDefinition</code> or
189 * <code>IdentityrefTypeDefinition</code>.
191 * @param typeDefinition
192 * type definition which is converted to JAVA <code>Type</code>
193 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
195 private Type javaTypeForLeafrefOrIdentityRef(TypeDefinition<?> typeDefinition, SchemaNode parentNode) {
196 if (typeDefinition instanceof LeafrefTypeDefinition) {
197 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
198 return provideTypeForLeafref(leafref, parentNode);
199 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
200 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
201 return provideTypeForIdentityref(idref);
208 * Returns JAVA <code>Type</code> for instances of the type
209 * <code>ExtendedType</code>.
211 * @param typeDefinition
212 * type definition which is converted to JAVA <code>Type</code>
213 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
215 private Type javaTypeForExtendedType(TypeDefinition<?> typeDefinition) {
216 final String typedefName = typeDefinition.getQName().getLocalName();
217 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
218 Type returnType = null;
219 returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
220 if (returnType == null) {
221 if (baseTypeDef instanceof EnumTypeDefinition) {
222 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
223 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
225 final Module module = findParentModule(schemaContext, typeDefinition);
226 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
227 if (module != null) {
228 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
229 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
230 if (genTOs != null) {
231 returnType = genTOs.get(typedefName);
233 if (returnType == null) {
234 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
235 baseTypeDef, typeDefinition, r);
241 // TODO: add throw exception when we will be able to resolve ALL yang
243 // if (returnType == null) {
244 // throw new IllegalArgumentException("Type Provider can't resolve " +
245 // "type for specified Type Definition " + typedefName);
250 * Seeks for identity reference <code>idref</code> the JAVA
251 * <code>type</code>.<br />
255 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
256 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
259 * identityref type definition for which JAVA <code>Type</code>
261 * @return JAVA <code>Type</code> of the identity which is refrenced through
264 private Type provideTypeForIdentityref(IdentityrefTypeDefinition idref) {
265 QName baseIdQName = idref.getIdentity().getQName();
266 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
267 baseIdQName.getRevision());
268 IdentitySchemaNode identity = null;
269 for (IdentitySchemaNode id : module.getIdentities()) {
270 if (id.getQName().equals(baseIdQName)) {
274 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
276 final String basePackageName = moduleNamespaceToPackageName(module);
277 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
278 final String genTypeName = parseToClassName(identity.getQName().getLocalName());
280 Type baseType = Types.typeForClass(Class.class);
281 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
282 return Types.parameterizedTypeFor(baseType, paramType);
286 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
288 * @param typeDefinition
289 * type definition which should be converted to JAVA
291 * @return JAVA <code>Type</code> which represents
292 * <code>typeDefinition</code>
293 * @throws IllegalArgumentException
295 * <li>if <code>typeDefinition</code> equal null</li>
296 * <li>if Q name of <code>typeDefinition</code></li>
297 * <li>if name of <code>typeDefinition</code></li>
300 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
301 final SchemaNode parentNode) {
302 Type returnType = null;
303 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
304 if (typeDefinition.getQName() == null) {
305 throw new IllegalArgumentException(
306 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
308 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
309 "Type Definitions Local Name cannot be NULL!");
311 final String typedefName = typeDefinition.getQName().getLocalName();
312 if (typeDefinition instanceof ExtendedType) {
313 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
315 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
316 final Module module = findParentModule(schemaContext, parentNode);
318 if (module != null) {
319 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
320 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
321 if (genTOs != null) {
322 returnType = genTOs.get(typedefName);
331 * Gets base type definition for <code>extendTypeDef</code>. The method is
332 * recursivelly called until non <code>ExtendedType</code> type is found.
334 * @param extendTypeDef
335 * type definition for which is the base type definition sought
336 * @return type definition which is base type for <code>extendTypeDef</code>
337 * @throws IllegalArgumentException
338 * if <code>extendTypeDef</code> equal null
340 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
341 Preconditions.checkArgument(extendTypeDef != null, "Type Definiition reference cannot be NULL!");
342 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
343 if (baseTypeDef == null) {
344 return extendTypeDef;
345 } else if (baseTypeDef instanceof ExtendedType) {
346 return baseTypeDefForExtendedType(baseTypeDef);
354 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
356 * The path of <code>leafrefType</code> is followed to find referenced node
357 * and its <code>Type</code> is returned.
360 * leafref type definition for which is the type sought
361 * @return JAVA <code>Type</code> of data schema node which is referenced in
362 * <code>leafrefType</code>
363 * @throws IllegalArgumentException
365 * <li>if <code>leafrefType</code> equal null</li>
366 * <li>if path statement of <code>leafrefType</code> equal null</li>
370 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
371 Type returnType = null;
372 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
374 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
375 "The Path Statement for Leafref Type Definition cannot be NULL!");
377 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
378 final String strXPath = xpath.toString();
380 if (strXPath != null) {
381 if (strXPath.contains("[")) {
382 returnType = Types.typeForClass(Object.class);
384 final Module module = findParentModule(schemaContext, parentNode);
385 if (module != null) {
386 final SchemaNode dataNode;
387 if (xpath.isAbsolute()) {
388 dataNode = findDataSchemaNode(schemaContext, module, xpath);
390 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
393 if (leafContainsEnumDefinition(dataNode)) {
394 returnType = referencedTypes.get(dataNode.getPath());
395 } else if (leafListContainsEnumDefinition(dataNode)) {
396 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
398 returnType = resolveTypeFromDataSchemaNode(dataNode);
407 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
408 * so then checks if it is of type <code>EnumTypeDefinition</code>.
411 * data schema node for which is checked if it is leaf and if it
413 * @return boolean value
415 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
416 * <li>false - other cases</li>
419 private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
420 if (dataNode instanceof LeafSchemaNode) {
421 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
422 if (leaf.getType() instanceof EnumTypeDefinition) {
430 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
431 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
434 * data schema node for which is checked if it is leaflist and if
436 * @return boolean value
438 * <li>true - if <code>dataNode</code> is leaflist of type
440 * <li>false - other cases</li>
443 private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
444 if (dataNode instanceof LeafListSchemaNode) {
445 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
446 if (leafList.getType() instanceof EnumTypeDefinition) {
454 * Converts <code>enumTypeDef</code> to
455 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
459 * enumeration type definition which is converted to enumeration
461 * string with name which is used as the enumeration name
462 * @return enumeration type which is built with data (name, enum values)
463 * from <code>enumTypeDef</code>
464 * @throws IllegalArgumentException
466 * <li>if <code>enumTypeDef</code> equals null</li>
467 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
468 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
469 * <li>if name of <code>enumTypeDef</code> equal null</li>
472 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
473 final SchemaNode parentNode) {
474 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
475 Preconditions.checkArgument(enumTypeDef.getValues() != null,
476 "EnumTypeDefinition MUST contain at least ONE value definition!");
477 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
478 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
479 "Local Name in EnumTypeDefinition QName cannot be NULL!");
481 final String enumerationName = parseToClassName(enumName);
483 Module module = findParentModule(schemaContext, parentNode);
484 final String basePackageName = moduleNamespaceToPackageName(module);
486 final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
487 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
488 return enumBuilder.toInstance(null);
492 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
493 * taken from <code>enumTypeDef</code>.
496 * enumeration type definition is source of enumeration data for
497 * <code>typeBuilder</code>
499 * string with the name of enumeration
501 * generated type builder to which is enumeration added
502 * @return enumeration type which contains enumeration data form
503 * <code>enumTypeDef</code>
504 * @throws IllegalArgumentException
506 * <li>if <code>enumTypeDef</code> equals null</li>
507 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
508 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
509 * <li>if name of <code>enumTypeDef</code> equal null</li>
510 * <li>if name of <code>typeBuilder</code> equal null</li>
514 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
515 final GeneratedTypeBuilderBase<?> typeBuilder) {
516 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
517 Preconditions.checkArgument(enumTypeDef.getValues() != null,
518 "EnumTypeDefinition MUST contain at least ONE value definition!");
519 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
520 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
521 "Local Name in EnumTypeDefinition QName cannot be NULL!");
522 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
524 final String enumerationName = parseToClassName(enumName);
526 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
527 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
528 return enumBuilder.toInstance(enumBuilder);
532 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
535 * contains information about YANG type
536 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
538 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
539 Type returnType = null;
540 if (dataNode != null) {
541 if (dataNode instanceof LeafSchemaNode) {
542 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
543 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
544 } else if (dataNode instanceof LeafListSchemaNode) {
545 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
546 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
553 * Passes through all modules and through all its type definitions and
554 * convert it to generated types.
556 * The modules are firstly sorted by mutual dependencies. The modules are
557 * sequentially passed. All type definitions of a module are at the
558 * beginning sorted so that type definition with less amount of references
559 * to other type definition are processed first.<br />
560 * For each module is created mapping record in the map
561 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
562 * which map current module name to the map which maps type names to
563 * returned types (generated types).
566 private void resolveTypeDefsFromContext() {
567 final Set<Module> modules = schemaContext.getModules();
568 Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
569 final Module[] modulesArray = new Module[modules.size()];
571 for (Module modul : modules) {
572 modulesArray[i++] = modul;
574 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modulesArray);
576 for (final Module module : modulesSortedByDependency) {
577 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
578 if (dateTypeMap == null) {
579 dateTypeMap = new HashMap<>();
581 final Map<String, Type> typeMap = new HashMap<>();
582 dateTypeMap.put(module.getRevision(), typeMap);
583 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
586 for (final Module module : modulesSortedByDependency) {
587 if (module == null) {
590 final String moduleName = module.getName();
591 final String basePackageName = moduleNamespaceToPackageName(module);
593 final DataNodeIterator it = new DataNodeIterator(module);
594 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
595 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
597 if ((listTypeDefinitions != null) && (basePackageName != null)) {
598 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
599 typedefToGeneratedType(basePackageName, module, typedef);
607 * @param basePackageName
608 * string with name of package to which the module belongs
610 * string with the name of the module for to which the
611 * <code>typedef</code> belongs
613 * type definition of the node for which should be creted JAVA
614 * <code>Type</code> (usually generated TO)
615 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
616 * <code>null</code> value if <code>basePackageName</code> or
617 * <code>modulName</code> or <code>typedef</code> or Q name of
618 * <code>typedef</code> equals <code>null</code>
620 private Type typedefToGeneratedType(final String basePackageName, final Module module,
621 final TypeDefinition<?> typedef) {
622 final String moduleName = module.getName();
623 final Date moduleRevision = module.getRevision();
624 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
626 final String typedefName = typedef.getQName().getLocalName();
627 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
628 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
629 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
630 Type returnType = null;
631 if (innerTypeDefinition instanceof ExtendedType) {
632 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
633 returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName);
634 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
635 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
636 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
637 genTOBuilder.setTypedef(true);
638 genTOBuilder.setIsUnion(true);
639 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
640 returnType = genTOBuilder.toInstance();
642 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
643 genTOBuilder.getName() + "Builder");
644 unionBuilder.setIsUnionBuilder(true);
645 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
646 method.setReturnType(returnType);
647 method.addParameter(Types.STRING, "defaultValue");
648 method.setAccessModifier(AccessModifier.PUBLIC);
649 method.setStatic(true);
650 Set<Type> types = additionalTypes.get(module);
652 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
653 additionalTypes.put(module, types);
655 types.add(unionBuilder.toInstance());
657 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
658 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
659 // TODO units for typedef enum
660 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
661 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
662 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
663 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
664 basePackageName, bitsTypeDefinition, typedefName);
665 genTOBuilder.setTypedef(true);
666 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
667 returnType = genTOBuilder.toInstance();
669 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
670 innerTypeDefinition, typedef);
671 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
673 if (returnType != null) {
674 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
675 final Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
676 if (typeMap != null) {
677 typeMap.put(typedefName, returnType);
687 * Wraps base YANG type to generated TO.
689 * @param basePackageName
690 * string with name of package to which the module belongs
692 * type definition which is converted to the TO
694 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
695 * @return generated transfer object which represent<code>javaType</code>
697 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
698 final Type javaType) {
699 Preconditions.checkNotNull(javaType, "javaType cannot be null");
700 final String propertyName = "value";
702 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
703 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
704 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
705 genPropBuilder.setReturnType(javaType);
706 genTOBuilder.addEqualsIdentity(genPropBuilder);
707 genTOBuilder.addHashIdentity(genPropBuilder);
708 genTOBuilder.addToStringProperty(genPropBuilder);
709 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef instanceof ExtendedType) {
710 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
711 addStringRegExAsConstant(genTOBuilder, regExps);
713 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
714 genTOBuilder.setTypedef(true);
715 return genTOBuilder.toInstance();
719 * Converts output list of generated TO builders to one TO builder (first
720 * from list) which contains the remaining builders as its enclosing TO.
722 * @param basePackageName
723 * string with name of package to which the module belongs
725 * type definition which should be of type
726 * <code>UnionTypeDefinition</code>
728 * string with name for generated TO
729 * @return generated TO builder with the list of enclosed generated TO
732 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
733 final UnionTypeDefinition typedef, String typeDefName, SchemaNode parentNode) {
734 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
735 typedef, typeDefName, parentNode);
736 GeneratedTOBuilder resultTOBuilder = null;
737 if (!genTOBuilders.isEmpty()) {
738 resultTOBuilder = genTOBuilders.remove(0);
739 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
740 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
744 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
745 genPropBuilder.setReturnType(Types.primitiveType("char[]", null));
746 resultTOBuilder.addEqualsIdentity(genPropBuilder);
747 resultTOBuilder.addHashIdentity(genPropBuilder);
748 resultTOBuilder.addToStringProperty(genPropBuilder);
750 return resultTOBuilder;
754 * Converts <code>typedef</code> to generated TO with
755 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
756 * added to generated TO builder as property.
758 * @param basePackageName
759 * string with name of package to which the module belongs
761 * type definition which should be of type
762 * <code>UnionTypeDefinition</code>
764 * string with name for generated TO
765 * @return generated TO builder which represents <code>typedef</code>
766 * @throws NullPointerException
768 * <li>if <code>basePackageName</code> is null</li>
769 * <li>if <code>typedef</code> is null</li>
770 * <li>if Qname of <code>typedef</code> is null</li>
773 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
774 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
775 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
776 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
777 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
779 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
780 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
782 final GeneratedTOBuilder unionGenTOBuilder;
783 if (typeDefName != null && !typeDefName.isEmpty()) {
784 final String typeName = parseToClassName(typeDefName);
785 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
787 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
790 generatedTOBuilders.add(unionGenTOBuilder);
791 unionGenTOBuilder.setIsUnion(true);
792 final List<String> regularExpressions = new ArrayList<String>();
793 for (final TypeDefinition<?> unionType : unionTypes) {
794 final String unionTypeName = unionType.getQName().getLocalName();
795 if (unionType instanceof UnionType) {
796 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
797 basePackageName, parentNode));
798 } else if (unionType instanceof ExtendedType) {
799 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, regularExpressions,
801 } else if (unionType instanceof EnumTypeDefinition) {
802 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
803 unionTypeName, unionGenTOBuilder);
804 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
806 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
808 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
811 if (!regularExpressions.isEmpty()) {
812 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
815 storeGenTO(typedef, unionGenTOBuilder, parentNode);
817 return generatedTOBuilders;
821 * Wraps code which handle case when union subtype is also of the type
822 * <code>UnionType</code>.
824 * In this case the new generated TO is created for union subtype (recursive
826 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, TypeDefinition, String)
827 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
828 * <code>parentUnionGenTOBuilder</code> is created property which type is
829 * equal to new generated TO.
831 * @param parentUnionGenTOBuilder
832 * generated TO builder to which is the property with the child
833 * union subtype added
834 * @param basePackageName
835 * string with the name of the module package
836 * @param unionSubtype
837 * type definition which represents union subtype
838 * @return list of generated TO builders. The number of the builders can be
839 * bigger one due to recursive call of
840 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
842 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
843 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
844 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
845 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
846 basePackageName, unionSubtype, newTOBuilderName, parentNode);
848 final GeneratedPropertyBuilder propertyBuilder;
849 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
850 .parseToValidParamName(newTOBuilderName));
851 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
852 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
853 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
855 return subUnionGenTOBUilders;
859 * Wraps code which handle case when union subtype is of the type
860 * <code>ExtendedType</code>.
862 * If TO for this type already exists it is used for the creation of the
863 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
864 * type is used for the property creation.
866 * @param parentUnionGenTOBuilder
867 * generated TO builder in which new property is created
868 * @param unionSubtype
869 * type definition of the <code>ExtendedType</code> type which
870 * represents union subtype
871 * @param unionTypeName
872 * string with the name for <code>unionSubtype</code>
873 * @param regularExpressions
874 * list of strings with the regular expressions
876 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
877 final ExtendedType unionSubtype, final List<String> regularExpressions,
878 final SchemaNode parentNode) {
879 final String unionTypeName = unionSubtype.getQName().getLocalName();
880 final Type genTO = findGenTO(unionTypeName, unionSubtype);
882 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
884 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
885 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
886 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
888 if (javaType != null) {
889 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
892 if (baseType instanceof StringType) {
893 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
899 * Searches for generated TO for <code>searchedTypeDef</code> type
900 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
902 * @param searchedTypeName
903 * string with name of <code>searchedTypeDef</code>
904 * @return generated TO for <code>searchedTypeDef</code> or
905 * <code>null</code> it it doesn't exist
907 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
908 final Module typeModule = findParentModule(schemaContext, parentNode);
909 if (typeModule != null && typeModule.getName() != null) {
910 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
911 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
912 if (genTOs != null) {
913 return genTOs.get(searchedTypeName);
920 * Stores generated TO created from <code>genTOBuilder</code> for
921 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
922 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
925 * type definition for which is <code>genTOBuilder</code> created
926 * @param genTOBuilder
927 * generated TO builder which is converted to generated TO and
930 private void storeGenTO(TypeDefinition<?> newTypeDef, GeneratedTOBuilder genTOBuilder, SchemaNode parentNode) {
931 if (!(newTypeDef instanceof UnionType)) {
933 final Module parentModule = findParentModule(schemaContext, parentNode);
934 if (parentModule != null && parentModule.getName() != null) {
935 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
936 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
937 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
943 * Adds a new property with the name <code>propertyName</code> and with type
944 * <code>type</code> to <code>unonGenTransObject</code>.
946 * @param unionGenTransObject
947 * generated TO to which should be property added
949 * JAVA <code>type</code> of the property which should be added
950 * to <code>unionGentransObject</code>
951 * @param propertyName
952 * string with name of property which should be added to
953 * <code>unionGentransObject</code>
955 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
956 final String propertyName) {
957 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
958 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
959 .addProperty(parseToValidParamName(propertyName));
960 propBuilder.setReturnType(type);
962 unionGenTransObject.addEqualsIdentity(propBuilder);
963 unionGenTransObject.addHashIdentity(propBuilder);
964 unionGenTransObject.addToStringProperty(propBuilder);
969 * Converts <code>typedef</code> to the generated TO builder.
971 * @param basePackageName
972 * string with name of package to which the module belongs
974 * type definition from which is the generated TO builder created
975 * @return generated TO builder which contains data from
976 * <code>typedef</code> and <code>basePackageName</code>
978 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
980 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
981 final String typeDefTOName = typedef.getQName().getLocalName();
983 if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
984 final String genTOName = parseToClassName(typeDefTOName);
985 final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
986 newType.addComment(typedef.getDescription());
993 * Converts <code>typeDef</code> which should be of the type
994 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
996 * All the bits of the typeDef are added to returning generated TO as
999 * @param basePackageName
1000 * string with name of package to which the module belongs
1002 * type definition from which is the generated TO builder created
1003 * @param typeDefName
1004 * string with the name for generated TO builder
1005 * @return generated TO builder which represents <code>typeDef</code>
1006 * @throws IllegalArgumentException
1008 * <li>if <code>typeDef</code> equals null</li>
1009 * <li>if <code>basePackageName</code> equals null</li>
1012 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1013 final TypeDefinition<?> typeDef, String typeDefName) {
1015 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1016 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1018 if (typeDef instanceof BitsTypeDefinition) {
1019 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1021 final String typeName = parseToClassName(typeDefName);
1022 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1024 final List<Bit> bitList = bitsTypeDefinition.getBits();
1025 GeneratedPropertyBuilder genPropertyBuilder;
1026 for (final Bit bit : bitList) {
1027 String name = bit.getName();
1028 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
1029 genPropertyBuilder.setReadOnly(true);
1030 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1032 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1033 genTOBuilder.addHashIdentity(genPropertyBuilder);
1034 genTOBuilder.addToStringProperty(genPropertyBuilder);
1037 return genTOBuilder;
1043 * Converts the pattern constraints from <code>typedef</code> to the list of
1044 * the strings which represents these constraints.
1047 * extended type in which are the pattern constraints sought
1048 * @return list of strings which represents the constraint patterns
1049 * @throws IllegalArgumentException
1050 * if <code>typedef</code> equals null
1053 private List<String> resolveRegExpressionsFromTypedef(ExtendedType typedef) {
1054 final List<String> regExps = new ArrayList<String>();
1055 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1056 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1057 if (strTypeDef instanceof StringType) {
1058 final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1059 if (!patternConstraints.isEmpty()) {
1061 String modifiedRegEx;
1062 for (PatternConstraint patternConstraint : patternConstraints) {
1063 regEx = patternConstraint.getRegularExpression();
1064 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1065 regExps.add(modifiedRegEx);
1074 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1075 * expressions from the <code>regularExpressions</code>
1077 * @param genTOBuilder
1078 * generated TO builder to which are
1079 * <code>regular expressions</code> added
1080 * @param regularExpressions
1081 * list of string which represent regular expressions
1082 * @throws IllegalArgumentException
1084 * <li>if <code>genTOBuilder</code> equals null</li>
1085 * <li>if <code>regularExpressions</code> equals null</li>
1088 private void addStringRegExAsConstant(GeneratedTOBuilder genTOBuilder, List<String> regularExpressions) {
1089 if (genTOBuilder == null) {
1090 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1092 if (regularExpressions == null) {
1093 throw new IllegalArgumentException("List of regular expressions can't be null");
1095 if (!regularExpressions.isEmpty()) {
1096 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1097 regularExpressions);
1102 * Creates generated TO with data about inner extended type
1103 * <code>innerExtendedType</code>, about the package name
1104 * <code>typedefName</code> and about the generated TO name
1105 * <code>typedefName</code>.
1107 * It is supposed that <code>innerExtendedType</code> is already present in
1108 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1109 * be possible set it as extended type for the returning generated TO.
1111 * @param innerExtendedType
1112 * extended type which is part of some other extended type
1113 * @param basePackageName
1114 * string with the package name of the module
1115 * @param typedefName
1116 * string with the name for the generated TO
1117 * @return generated TO which extends generated TO for
1118 * <code>innerExtendedType</code>
1119 * @throws IllegalArgumentException
1121 * <li>if <code>extendedType</code> equals null</li>
1122 * <li>if <code>basePackageName</code> equals null</li>
1123 * <li>if <code>typedefName</code> equals null</li>
1126 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1127 final ExtendedType innerExtendedType, final String basePackageName) {
1128 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1129 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1131 final String typedefName = typedef.getQName().getLocalName();
1132 final String classTypedefName = parseToClassName(typedefName);
1133 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1134 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1135 genTOBuilder.setTypedef(true);
1136 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1137 genTOBuilder.setRestrictions(r);
1139 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1140 genTOBuilder.setIsUnion(true);
1143 Map<Date, Map<String, Type>> modulesByDate = null;
1144 Map<String, Type> typeMap = null;
1145 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1146 if (parentModule != null) {
1147 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1148 typeMap = modulesByDate.get(parentModule.getRevision());
1151 if (typeMap != null) {
1152 Type type = typeMap.get(innerTypeDef);
1153 if (type instanceof GeneratedTransferObject) {
1154 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1157 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1159 return genTOBuilder.toInstance();
1163 * Finds out for each type definition how many immersion (depth) is
1164 * necessary to get to the base type. Every type definition is inserted to
1165 * the map which key is depth and value is list of type definitions with
1166 * equal depth. In next step are lists from this map concatenated to one
1167 * list in ascending order according to their depth. All type definitions
1168 * are in the list behind all type definitions on which depends.
1170 * @param unsortedTypeDefinitions
1171 * list of type definitions which should be sorted by depth
1172 * @return list of type definitions sorted according their each other
1173 * dependencies (type definitions which are depend on other type
1174 * definitions are in list behind them).
1176 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1177 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1178 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1180 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1181 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1182 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1183 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1184 if (typeDefinitionsConcreteDepth == null) {
1185 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1186 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1188 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1190 // keys are in ascending order
1191 Set<Integer> depths = typeDefinitionsDepths.keySet();
1192 for (Integer depth : depths) {
1193 sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1196 return sortedTypeDefinition;
1200 * Returns how many immersion is necessary to get from the type definition
1203 * @param typeDefinition
1204 * type definition for which is depth sought.
1205 * @return number of immersions which are necessary to get from the type
1206 * definition to the base type
1208 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1209 if (typeDefinition == null) {
1213 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1215 if (baseType instanceof ExtendedType) {
1216 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1217 } else if (baseType instanceof UnionType) {
1218 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1219 int maxChildDepth = 0;
1221 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1222 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1223 if (childDepth > maxChildDepth) {
1224 maxChildDepth = childDepth;
1227 return maxChildDepth;
1233 * Returns string which contains the same value as <code>name</code> but
1234 * integer suffix is incremented by one. If <code>name</code> contains no
1235 * number suffix then number 1 is added.
1238 * string with name of augmented node
1239 * @return string with the number suffix incremented by one (or 1 is added)
1241 private String provideAvailableNameForGenTOBuilder(String name) {
1242 Pattern searchedPattern = Pattern.compile("[0-9]+\\z");
1243 Matcher mtch = searchedPattern.matcher(name);
1245 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1246 return name.substring(0, mtch.start()) + newSuffix;
1252 public void addUnitsToGenTO(GeneratedTOBuilder to, String units) {
1253 if (units != null && !units.isEmpty()) {
1254 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1255 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1256 prop.setReturnType(Types.STRING);
1257 to.addToStringProperty(prop);
1262 public String getTypeDefaultConstruction(LeafSchemaNode node) {
1263 return getTypeDefaultConstruction(node, node.getDefault());
1266 public String getTypeDefaultConstruction(LeafSchemaNode node, String defaultValue) {
1267 TypeDefinition<?> type = node.getType();
1268 QName typeQName = type.getQName();
1269 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1270 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of " + node);
1271 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of "
1274 StringBuilder sb = new StringBuilder();
1275 String result = null;
1276 if (base instanceof BinaryTypeDefinition) {
1277 result = binaryToDef(defaultValue);
1278 } else if (base instanceof BitsTypeDefinition) {
1281 SchemaPath nodePath = node.getPath();
1282 Module parent = getParentModule(node);
1283 if (nodePath.getPath().size() == 1) {
1284 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1285 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1286 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1288 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1289 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1290 parentName = BindingMapping.getClassName(((SchemaNode) parent).getQName());
1291 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1293 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1294 } else if (base instanceof BooleanTypeDefinition) {
1295 result = typeToDef(Boolean.class, defaultValue);
1296 } else if (base instanceof DecimalTypeDefinition) {
1297 result = typeToDef(BigDecimal.class, defaultValue);
1298 } else if (base instanceof EmptyTypeDefinition) {
1299 result = typeToDef(Boolean.class, defaultValue);
1300 } else if (base instanceof EnumTypeDefinition) {
1301 char[] defValArray = defaultValue.toCharArray();
1302 char first = Character.toUpperCase(defaultValue.charAt(0));
1303 defValArray[0] = first;
1304 String newDefVal = new String(defValArray);
1306 if (type instanceof ExtendedType) {
1307 Module m = getParentModule(type);
1308 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1309 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1310 className = packageName + "." + BindingMapping.getClassName(typeQName);
1312 Module parentModule = getParentModule(node);
1313 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1314 String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
1315 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1317 result = className + "." + newDefVal;
1318 } else if (base instanceof IdentityrefTypeDefinition) {
1319 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1320 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1321 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1322 } else if (base instanceof Int8) {
1323 result = typeToDef(Byte.class, defaultValue);
1324 } else if (base instanceof Int16) {
1325 result = typeToDef(Short.class, defaultValue);
1326 } else if (base instanceof Int32) {
1327 result = typeToDef(Integer.class, defaultValue);
1328 } else if (base instanceof Int64) {
1329 result = typeToDef(Long.class, defaultValue);
1330 } else if (base instanceof LeafrefTypeDefinition) {
1331 result = leafrefToDef(node, (LeafrefTypeDefinition) base);
1332 } else if (base instanceof StringTypeDefinition) {
1333 result = "\"" + defaultValue + "\"";
1334 } else if (base instanceof Uint8) {
1335 result = typeToDef(Short.class, defaultValue);
1336 } else if (base instanceof Uint16) {
1337 result = typeToDef(Integer.class, defaultValue);
1338 } else if (base instanceof Uint32) {
1339 result = typeToDef(Long.class, defaultValue);
1340 } else if (base instanceof Uint64) {
1341 result = typeToDef(BigInteger.class, defaultValue);
1342 } else if (base instanceof UnionTypeDefinition) {
1343 result = unionToDef(node);
1349 if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
1350 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
1351 Module m = getParentModule(type);
1352 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1353 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1354 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1355 sb.insert(0, "new " + className + "(");
1356 sb.insert(sb.length(), ")");
1359 return sb.toString();
1362 private String typeToDef(Class<?> clazz, String defaultValue) {
1363 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1366 private String binaryToDef(String defaultValue) {
1367 StringBuilder sb = new StringBuilder();
1368 BaseEncoding en = BaseEncoding.base64();
1369 byte[] encoded = en.decode(defaultValue);
1370 sb.append("new byte[] {");
1371 for (int i = 0; i < encoded.length; i++) {
1372 sb.append(encoded[i]);
1373 if (i != encoded.length - 1) {
1378 return sb.toString();
1381 private String bitsToDef(BitsTypeDefinition type, String className, String defaultValue, boolean isExt) {
1382 List<Bit> bits = new ArrayList<>(type.getBits());
1383 Collections.sort(bits, new Comparator<Bit>() {
1385 public int compare(Bit o1, Bit o2) {
1386 return o1.getName().compareTo(o2.getName());
1389 StringBuilder sb = new StringBuilder();
1390 sb.append(isExt ? "" : "new " + className + "(");
1391 for (int i = 0; i < bits.size(); i++) {
1392 if (bits.get(i).getName().equals(defaultValue)) {
1397 if (i != bits.size() - 1) {
1401 sb.append(isExt ? "" : ")");
1402 return sb.toString();
1405 private Module getParentModule(SchemaNode node) {
1406 QName qname = node.getPath().getPath().get(0);
1407 URI namespace = qname.getNamespace();
1408 Date revision = qname.getRevision();
1409 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1412 private String leafrefToDef(LeafSchemaNode parentNode, LeafrefTypeDefinition leafrefType) {
1413 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1414 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1415 "The Path Statement for Leafref Type Definition cannot be NULL!");
1417 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1418 final String strXPath = xpath.toString();
1420 if (strXPath != null) {
1421 if (strXPath.contains("[")) {
1422 return "new java.lang.Object()";
1424 final Module module = findParentModule(schemaContext, parentNode);
1425 if (module != null) {
1426 final SchemaNode dataNode;
1427 if (xpath.isAbsolute()) {
1428 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1430 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1432 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, parentNode.getDefault());
1441 private String unionToDef(LeafSchemaNode node) {
1445 if (node.getType() instanceof ExtendedType) {
1446 ExtendedType type = (ExtendedType) node.getType();
1447 QName typeQName = type.getQName();
1448 Module module = null;
1449 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1450 if (modules.size() > 1) {
1451 for (Module m : modules) {
1452 if (m.getRevision().equals(typeQName.getRevision())) {
1457 if (module == null) {
1458 List<Module> modulesList = new ArrayList<>(modules);
1459 Collections.sort(modulesList, new Comparator<Module>() {
1461 public int compare(Module o1, Module o2) {
1462 return o1.getRevision().compareTo(o2.getRevision());
1465 module = modulesList.get(0);
1468 module = modules.iterator().next();
1471 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
1472 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1474 SchemaPath nodePath = node.getPath();
1475 if (nodePath.getPath().size() == 1) {
1476 QName first = nodePath.getPath().get(0);
1477 URI namespace = first.getNamespace();
1478 Date revision = first.getRevision();
1479 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1480 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1481 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1482 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1484 QName first = node.getPath().getPath().get(0);
1485 URI namespace = first.getNamespace();
1486 Date revision = first.getRevision();
1487 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1488 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1489 String packageName = packageNameForGeneratedType(basePackageName, node.getType().getPath());
1490 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1493 return union(className, node.getDefault(), node);
1496 private String union(String className, String defaultValue, LeafSchemaNode node) {
1497 StringBuilder sb = new StringBuilder();
1498 sb.append("new " + className + "(");
1500 sb.append(defaultValue);
1502 sb.append(".toCharArray()");
1504 return sb.toString();
1508 public String getConstructorPropertyName(SchemaNode node) {
1509 if (node instanceof TypeDefinition<?>) {
1517 public String getParamNameFromType(TypeDefinition<?> type) {
1518 return BindingGeneratorUtil.parseToValidParamName(type.getQName().getLocalName());