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.parseToValidParamName;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
14 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
15 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
17 import java.math.BigDecimal;
18 import java.math.BigInteger;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.Date;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.List;
30 import java.util.TreeMap;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
34 import org.apache.commons.lang3.StringEscapeUtils;
35 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
36 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
37 import org.opendaylight.yangtools.binding.generator.util.Types;
38 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
39 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
40 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
41 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
42 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
43 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
44 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
45 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
46 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
47 import org.opendaylight.yangtools.sal.binding.model.api.Type;
48 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
49 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
50 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
51 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
53 import org.opendaylight.yangtools.yang.binding.BindingMapping;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.Module;
59 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
63 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
67 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
69 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
75 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
78 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
79 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
80 import org.opendaylight.yangtools.yang.model.util.Int16;
81 import org.opendaylight.yangtools.yang.model.util.Int32;
82 import org.opendaylight.yangtools.yang.model.util.Int64;
83 import org.opendaylight.yangtools.yang.model.util.Int8;
84 import org.opendaylight.yangtools.yang.model.util.StringType;
85 import org.opendaylight.yangtools.yang.model.util.Uint16;
86 import org.opendaylight.yangtools.yang.model.util.Uint32;
87 import org.opendaylight.yangtools.yang.model.util.Uint64;
88 import org.opendaylight.yangtools.yang.model.util.Uint8;
89 import org.opendaylight.yangtools.yang.model.util.UnionType;
91 import com.google.common.base.Preconditions;
92 import com.google.common.collect.Sets;
93 import com.google.common.io.BaseEncoding;
96 public final class TypeProviderImpl implements TypeProvider {
97 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
100 * Contains the schema data red from YANG files.
102 private final SchemaContext schemaContext;
105 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
107 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
110 * The map which maps schema paths to JAVA <code>Type</code>.
112 private final Map<SchemaPath, Type> referencedTypes;
113 private final Map<Module, Set<Type>> additionalTypes;
116 * Creates new instance of class <code>TypeProviderImpl</code>.
118 * @param schemaContext
119 * contains the schema data red from YANG files
120 * @throws IllegalArgumentException
121 * if <code>schemaContext</code> equal null.
123 public TypeProviderImpl(final SchemaContext schemaContext) {
124 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
126 this.schemaContext = schemaContext;
127 this.genTypeDefsContextMap = new HashMap<>();
128 this.referencedTypes = new HashMap<>();
129 this.additionalTypes = new HashMap<>();
130 resolveTypeDefsFromContext();
134 * Puts <code>refType</code> to map with key <code>refTypePath</code>
137 * schema path used as the map key
139 * type which represents the map value
140 * @throws IllegalArgumentException
142 * <li>if <code>refTypePath</code> equal null</li>
143 * <li>if <code>refType</code> equal null</li>
147 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
148 Preconditions.checkArgument(refTypePath != null,
149 "Path reference of Enumeration Type Definition cannot be NULL!");
150 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
151 referencedTypes.put(refTypePath, refType);
154 public Map<Module, Set<Type>> getAdditionalTypes() {
155 return additionalTypes;
160 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
163 * string with YANG name of type
164 * @return JAVA <code>Type</code> for YANG type <code>type</code>
165 * @see TypeProvider#javaTypeForYangType(String)
168 public Type javaTypeForYangType(final String type) {
169 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
173 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
174 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
178 * Converts schema definition type <code>typeDefinition</code> to JAVA
181 * @param typeDefinition
182 * type definition which is converted to JAVA type
183 * @throws IllegalArgumentException
185 * <li>if <code>typeDefinition</code> equal null</li>
186 * <li>if Qname of <code>typeDefinition</code> equal null</li>
187 * <li>if name of <code>typeDefinition</code> equal null</li>
191 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
192 final Restrictions r) {
193 Type returnType = null;
194 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
195 if (typeDefinition.getQName() == null) {
196 throw new IllegalArgumentException(
197 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
199 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
200 "Type Definitions Local Name cannot be NULL!");
202 if (typeDefinition instanceof ExtendedType) {
203 returnType = javaTypeForExtendedType(typeDefinition);
205 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
206 if (returnType == null) {
207 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
211 // TODO: add throw exception when we will be able to resolve ALL yang
213 // if (returnType == null) {
214 // throw new IllegalArgumentException("Type Provider can't resolve " +
215 // "type for specified Type Definition " + typedefName);
221 * Returns JAVA <code>Type</code> for instances of the type
222 * <code>LeafrefTypeDefinition</code> or
223 * <code>IdentityrefTypeDefinition</code>.
225 * @param typeDefinition
226 * type definition which is converted to JAVA <code>Type</code>
227 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
229 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
230 if (typeDefinition instanceof LeafrefTypeDefinition) {
231 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
232 return provideTypeForLeafref(leafref, parentNode);
233 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
234 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
235 return provideTypeForIdentityref(idref);
242 * Returns JAVA <code>Type</code> for instances of the type
243 * <code>ExtendedType</code>.
245 * @param typeDefinition
246 * type definition which is converted to JAVA <code>Type</code>
247 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
249 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
250 final String typedefName = typeDefinition.getQName().getLocalName();
251 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
252 Type returnType = null;
253 returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
254 if (returnType == null) {
255 if (baseTypeDef instanceof EnumTypeDefinition) {
256 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
257 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
259 final Module module = findParentModule(schemaContext, typeDefinition);
260 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
261 if (module != null) {
262 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
263 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
264 if (genTOs != null) {
265 returnType = genTOs.get(typedefName);
267 if (returnType == null) {
268 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
269 baseTypeDef, typeDefinition, r);
275 // TODO: add throw exception when we will be able to resolve ALL yang
277 // if (returnType == null) {
278 // throw new IllegalArgumentException("Type Provider can't resolve " +
279 // "type for specified Type Definition " + typedefName);
284 * Seeks for identity reference <code>idref</code> the JAVA
285 * <code>type</code>.<br />
289 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
290 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
293 * identityref type definition for which JAVA <code>Type</code>
295 * @return JAVA <code>Type</code> of the identity which is refrenced through
298 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
299 QName baseIdQName = idref.getIdentity().getQName();
300 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
301 baseIdQName.getRevision());
302 IdentitySchemaNode identity = null;
303 for (IdentitySchemaNode id : module.getIdentities()) {
304 if (id.getQName().equals(baseIdQName)) {
308 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
310 final String basePackageName = moduleNamespaceToPackageName(module);
311 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
312 final String genTypeName = BindingMapping.getClassName(identity.getQName());
314 Type baseType = Types.typeForClass(Class.class);
315 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
316 return Types.parameterizedTypeFor(baseType, paramType);
320 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
322 * @param typeDefinition
323 * type definition which should be converted to JAVA
325 * @return JAVA <code>Type</code> which represents
326 * <code>typeDefinition</code>
327 * @throws IllegalArgumentException
329 * <li>if <code>typeDefinition</code> equal null</li>
330 * <li>if Q name of <code>typeDefinition</code></li>
331 * <li>if name of <code>typeDefinition</code></li>
334 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
335 final SchemaNode parentNode) {
336 Type returnType = null;
337 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
338 if (typeDefinition.getQName() == null) {
339 throw new IllegalArgumentException(
340 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
342 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
343 "Type Definitions Local Name cannot be NULL!");
345 final String typedefName = typeDefinition.getQName().getLocalName();
346 if (typeDefinition instanceof ExtendedType) {
347 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
349 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
350 final Module module = findParentModule(schemaContext, parentNode);
352 if (module != null) {
353 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
354 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
355 if (genTOs != null) {
356 returnType = genTOs.get(typedefName);
365 * Gets base type definition for <code>extendTypeDef</code>. The method is
366 * recursivelly called until non <code>ExtendedType</code> type is found.
368 * @param extendTypeDef
369 * type definition for which is the base type definition sought
370 * @return type definition which is base type for <code>extendTypeDef</code>
371 * @throws IllegalArgumentException
372 * if <code>extendTypeDef</code> equal null
374 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
375 Preconditions.checkArgument(extendTypeDef != null, "Type Definiition reference cannot be NULL!");
376 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
377 if (baseTypeDef == null) {
378 return extendTypeDef;
379 } else if (baseTypeDef instanceof ExtendedType) {
380 return baseTypeDefForExtendedType(baseTypeDef);
388 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
390 * The path of <code>leafrefType</code> is followed to find referenced node
391 * and its <code>Type</code> is returned.
394 * leafref type definition for which is the type sought
395 * @return JAVA <code>Type</code> of data schema node which is referenced in
396 * <code>leafrefType</code>
397 * @throws IllegalArgumentException
399 * <li>if <code>leafrefType</code> equal null</li>
400 * <li>if path statement of <code>leafrefType</code> equal null</li>
404 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
405 Type returnType = null;
406 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
408 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
409 "The Path Statement for Leafref Type Definition cannot be NULL!");
411 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
412 final String strXPath = xpath.toString();
414 if (strXPath != null) {
415 if (strXPath.contains("[")) {
416 returnType = Types.typeForClass(Object.class);
418 final Module module = findParentModule(schemaContext, parentNode);
419 if (module != null) {
420 final SchemaNode dataNode;
421 if (xpath.isAbsolute()) {
422 dataNode = findDataSchemaNode(schemaContext, module, xpath);
424 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
427 if (leafContainsEnumDefinition(dataNode)) {
428 returnType = referencedTypes.get(dataNode.getPath());
429 } else if (leafListContainsEnumDefinition(dataNode)) {
430 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
432 returnType = resolveTypeFromDataSchemaNode(dataNode);
437 if (returnType == null) {
438 throw new IllegalArgumentException("Failed to find leafref target: " + strXPath);
444 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
445 * so then checks if it is of type <code>EnumTypeDefinition</code>.
448 * data schema node for which is checked if it is leaf and if it
450 * @return boolean value
452 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
453 * <li>false - other cases</li>
456 private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
457 if (dataNode instanceof LeafSchemaNode) {
458 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
459 if (leaf.getType() instanceof EnumTypeDefinition) {
467 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
468 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
471 * data schema node for which is checked if it is leaflist and if
473 * @return boolean value
475 * <li>true - if <code>dataNode</code> is leaflist of type
477 * <li>false - other cases</li>
480 private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
481 if (dataNode instanceof LeafListSchemaNode) {
482 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
483 if (leafList.getType() instanceof EnumTypeDefinition) {
491 * Converts <code>enumTypeDef</code> to
492 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
496 * enumeration type definition which is converted to enumeration
498 * string with name which is used as the enumeration name
499 * @return enumeration type which is built with data (name, enum values)
500 * from <code>enumTypeDef</code>
501 * @throws IllegalArgumentException
503 * <li>if <code>enumTypeDef</code> equals null</li>
504 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
505 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
506 * <li>if name of <code>enumTypeDef</code> equal null</li>
509 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
510 final SchemaNode parentNode) {
511 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
512 Preconditions.checkArgument(enumTypeDef.getValues() != null,
513 "EnumTypeDefinition MUST contain at least ONE value definition!");
514 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
515 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
516 "Local Name in EnumTypeDefinition QName cannot be NULL!");
518 final String enumerationName = BindingMapping.getClassName(enumName);
520 Module module = findParentModule(schemaContext, parentNode);
521 final String basePackageName = moduleNamespaceToPackageName(module);
523 final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
524 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
525 return enumBuilder.toInstance(null);
529 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
530 * taken from <code>enumTypeDef</code>.
533 * enumeration type definition is source of enumeration data for
534 * <code>typeBuilder</code>
536 * string with the name of enumeration
538 * generated type builder to which is enumeration added
539 * @return enumeration type which contains enumeration data form
540 * <code>enumTypeDef</code>
541 * @throws IllegalArgumentException
543 * <li>if <code>enumTypeDef</code> equals null</li>
544 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
545 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
546 * <li>if name of <code>enumTypeDef</code> equal null</li>
547 * <li>if name of <code>typeBuilder</code> equal null</li>
551 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
552 final GeneratedTypeBuilderBase<?> typeBuilder) {
553 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
554 Preconditions.checkArgument(enumTypeDef.getValues() != null,
555 "EnumTypeDefinition MUST contain at least ONE value definition!");
556 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
557 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
558 "Local Name in EnumTypeDefinition QName cannot be NULL!");
559 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
561 final String enumerationName = BindingMapping.getClassName(enumName);
563 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
564 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
565 return enumBuilder.toInstance(enumBuilder);
569 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
572 * contains information about YANG type
573 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
575 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
576 Type returnType = null;
577 if (dataNode != null) {
578 if (dataNode instanceof LeafSchemaNode) {
579 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
580 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
581 } else if (dataNode instanceof LeafListSchemaNode) {
582 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
583 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
590 * Passes through all modules and through all its type definitions and
591 * convert it to generated types.
593 * The modules are firstly sorted by mutual dependencies. The modules are
594 * sequentially passed. All type definitions of a module are at the
595 * beginning sorted so that type definition with less amount of references
596 * to other type definition are processed first.<br />
597 * For each module is created mapping record in the map
598 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
599 * which map current module name to the map which maps type names to
600 * returned types (generated types).
603 private void resolveTypeDefsFromContext() {
604 final Set<Module> modules = schemaContext.getModules();
605 Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
606 final Module[] modulesArray = new Module[modules.size()];
608 for (Module modul : modules) {
609 modulesArray[i++] = modul;
611 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort.sort(modulesArray);
613 for (final Module module : modulesSortedByDependency) {
614 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
615 if (dateTypeMap == null) {
616 dateTypeMap = new HashMap<>();
618 final Map<String, Type> typeMap = new HashMap<>();
619 dateTypeMap.put(module.getRevision(), typeMap);
620 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
623 for (final Module module : modulesSortedByDependency) {
624 if (module == null) {
627 final String basePackageName = moduleNamespaceToPackageName(module);
629 final DataNodeIterator it = new DataNodeIterator(module);
630 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
631 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
633 if ((listTypeDefinitions != null) && (basePackageName != null)) {
634 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
635 typedefToGeneratedType(basePackageName, module, typedef);
643 * @param basePackageName
644 * string with name of package to which the module belongs
646 * string with the name of the module for to which the
647 * <code>typedef</code> belongs
649 * type definition of the node for which should be creted JAVA
650 * <code>Type</code> (usually generated TO)
651 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
652 * <code>null</code> value if <code>basePackageName</code> or
653 * <code>modulName</code> or <code>typedef</code> or Q name of
654 * <code>typedef</code> equals <code>null</code>
656 private Type typedefToGeneratedType(final String basePackageName, final Module module,
657 final TypeDefinition<?> typedef) {
658 final String moduleName = module.getName();
659 final Date moduleRevision = module.getRevision();
660 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
662 final String typedefName = typedef.getQName().getLocalName();
663 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
664 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
665 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
666 Type returnType = null;
667 if (innerTypeDefinition instanceof ExtendedType) {
668 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
669 returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName);
670 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
671 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
672 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
673 genTOBuilder.setTypedef(true);
674 genTOBuilder.setIsUnion(true);
675 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
676 BindingGeneratorUtil.makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
677 returnType = genTOBuilder.toInstance();
679 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
680 genTOBuilder.getName() + "Builder");
681 unionBuilder.setIsUnionBuilder(true);
682 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
683 method.setReturnType(returnType);
684 method.addParameter(Types.STRING, "defaultValue");
685 method.setAccessModifier(AccessModifier.PUBLIC);
686 method.setStatic(true);
687 Set<Type> types = additionalTypes.get(module);
689 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
690 additionalTypes.put(module, types);
692 types.add(unionBuilder.toInstance());
694 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
695 // enums are automatically Serializable
696 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
697 // TODO units for typedef enum
698 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
699 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
700 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
701 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
702 basePackageName, bitsTypeDefinition, typedefName);
703 genTOBuilder.setTypedef(true);
704 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
705 BindingGeneratorUtil.makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
706 returnType = genTOBuilder.toInstance();
708 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
709 innerTypeDefinition, typedef);
710 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
712 if (returnType != null) {
713 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
714 final Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
715 if (typeMap != null) {
716 typeMap.put(typedefName, returnType);
726 * Wraps base YANG type to generated TO.
728 * @param basePackageName
729 * string with name of package to which the module belongs
731 * type definition which is converted to the TO
733 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
734 * @return generated transfer object which represent<code>javaType</code>
736 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
737 final Type javaType) {
738 Preconditions.checkNotNull(javaType, "javaType cannot be null");
739 final String propertyName = "value";
741 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
742 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
743 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
744 genPropBuilder.setReturnType(javaType);
745 genTOBuilder.addEqualsIdentity(genPropBuilder);
746 genTOBuilder.addHashIdentity(genPropBuilder);
747 genTOBuilder.addToStringProperty(genPropBuilder);
748 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef instanceof ExtendedType) {
749 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
750 addStringRegExAsConstant(genTOBuilder, regExps);
752 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
753 genTOBuilder.setTypedef(true);
754 BindingGeneratorUtil.makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
755 return genTOBuilder.toInstance();
759 * Converts output list of generated TO builders to one TO builder (first
760 * from list) which contains the remaining builders as its enclosing TO.
762 * @param basePackageName
763 * string with name of package to which the module belongs
765 * type definition which should be of type
766 * <code>UnionTypeDefinition</code>
768 * string with name for generated TO
769 * @return generated TO builder with the list of enclosed generated TO
772 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
773 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
774 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
775 typedef, typeDefName, parentNode);
776 GeneratedTOBuilder resultTOBuilder = null;
777 if (!genTOBuilders.isEmpty()) {
778 resultTOBuilder = genTOBuilders.remove(0);
779 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
780 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
784 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
785 genPropBuilder.setReturnType(Types.primitiveType("char[]", null));
786 resultTOBuilder.addEqualsIdentity(genPropBuilder);
787 resultTOBuilder.addHashIdentity(genPropBuilder);
788 resultTOBuilder.addToStringProperty(genPropBuilder);
790 return resultTOBuilder;
794 * Converts <code>typedef</code> to generated TO with
795 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
796 * added to generated TO builder as property.
798 * @param basePackageName
799 * string with name of package to which the module belongs
801 * type definition which should be of type
802 * <code>UnionTypeDefinition</code>
804 * string with name for generated TO
805 * @return generated TO builder which represents <code>typedef</code>
806 * @throws NullPointerException
808 * <li>if <code>basePackageName</code> is null</li>
809 * <li>if <code>typedef</code> is null</li>
810 * <li>if Qname of <code>typedef</code> is null</li>
813 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
814 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
815 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
816 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
817 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
819 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
820 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
822 final GeneratedTOBuilder unionGenTOBuilder;
823 if (typeDefName != null && !typeDefName.isEmpty()) {
824 final String typeName = BindingMapping.getClassName(typeDefName);
825 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
827 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
830 generatedTOBuilders.add(unionGenTOBuilder);
831 unionGenTOBuilder.setIsUnion(true);
832 final List<String> regularExpressions = new ArrayList<String>();
833 for (final TypeDefinition<?> unionType : unionTypes) {
834 final String unionTypeName = unionType.getQName().getLocalName();
835 if (unionType instanceof UnionType) {
836 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
837 basePackageName, parentNode));
838 } else if (unionType instanceof ExtendedType) {
839 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, regularExpressions,
841 } else if (unionType instanceof EnumTypeDefinition) {
842 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
843 unionTypeName, unionGenTOBuilder);
844 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
846 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
848 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
851 if (!regularExpressions.isEmpty()) {
852 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
855 storeGenTO(typedef, unionGenTOBuilder, parentNode);
857 return generatedTOBuilders;
861 * Wraps code which handle case when union subtype is also of the type
862 * <code>UnionType</code>.
864 * In this case the new generated TO is created for union subtype (recursive
866 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, TypeDefinition, String)
867 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
868 * <code>parentUnionGenTOBuilder</code> is created property which type is
869 * equal to new generated TO.
871 * @param parentUnionGenTOBuilder
872 * generated TO builder to which is the property with the child
873 * union subtype added
874 * @param basePackageName
875 * string with the name of the module package
876 * @param unionSubtype
877 * type definition which represents union subtype
878 * @return list of generated TO builders. The number of the builders can be
879 * bigger one due to recursive call of
880 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
882 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
883 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
884 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
885 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
886 basePackageName, unionSubtype, newTOBuilderName, parentNode);
888 final GeneratedPropertyBuilder propertyBuilder;
889 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
890 .parseToValidParamName(newTOBuilderName));
891 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
892 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
893 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
895 return subUnionGenTOBUilders;
899 * Wraps code which handle case when union subtype is of the type
900 * <code>ExtendedType</code>.
902 * If TO for this type already exists it is used for the creation of the
903 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
904 * type is used for the property creation.
906 * @param parentUnionGenTOBuilder
907 * generated TO builder in which new property is created
908 * @param unionSubtype
909 * type definition of the <code>ExtendedType</code> type which
910 * represents union subtype
911 * @param unionTypeName
912 * string with the name for <code>unionSubtype</code>
913 * @param regularExpressions
914 * list of strings with the regular expressions
916 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
917 final ExtendedType unionSubtype, final List<String> regularExpressions,
918 final SchemaNode parentNode) {
919 final String unionTypeName = unionSubtype.getQName().getLocalName();
920 final Type genTO = findGenTO(unionTypeName, unionSubtype);
922 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
924 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
925 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
926 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
928 if (javaType != null) {
929 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
932 if (baseType instanceof StringType) {
933 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
939 * Searches for generated TO for <code>searchedTypeDef</code> type
940 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
942 * @param searchedTypeName
943 * string with name of <code>searchedTypeDef</code>
944 * @return generated TO for <code>searchedTypeDef</code> or
945 * <code>null</code> it it doesn't exist
947 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
948 final Module typeModule = findParentModule(schemaContext, parentNode);
949 if (typeModule != null && typeModule.getName() != null) {
950 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
951 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
952 if (genTOs != null) {
953 return genTOs.get(searchedTypeName);
960 * Stores generated TO created from <code>genTOBuilder</code> for
961 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
962 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
965 * type definition for which is <code>genTOBuilder</code> created
966 * @param genTOBuilder
967 * generated TO builder which is converted to generated TO and
970 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
971 if (!(newTypeDef instanceof UnionType)) {
973 final Module parentModule = findParentModule(schemaContext, parentNode);
974 if (parentModule != null && parentModule.getName() != null) {
975 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
976 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
977 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
983 * Adds a new property with the name <code>propertyName</code> and with type
984 * <code>type</code> to <code>unonGenTransObject</code>.
986 * @param unionGenTransObject
987 * generated TO to which should be property added
989 * JAVA <code>type</code> of the property which should be added
990 * to <code>unionGentransObject</code>
991 * @param propertyName
992 * string with name of property which should be added to
993 * <code>unionGentransObject</code>
995 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
996 final String propertyName) {
997 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
998 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
999 .addProperty(parseToValidParamName(propertyName));
1000 propBuilder.setReturnType(type);
1002 unionGenTransObject.addEqualsIdentity(propBuilder);
1003 unionGenTransObject.addHashIdentity(propBuilder);
1004 unionGenTransObject.addToStringProperty(propBuilder);
1009 * Converts <code>typedef</code> to the generated TO builder.
1011 * @param basePackageName
1012 * string with name of package to which the module belongs
1014 * type definition from which is the generated TO builder created
1015 * @return generated TO builder which contains data from
1016 * <code>typedef</code> and <code>basePackageName</code>
1018 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
1020 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
1021 final String typeDefTOName = typedef.getQName().getLocalName();
1023 if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
1024 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1025 final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1026 newType.addComment(typedef.getDescription());
1033 * Converts <code>typeDef</code> which should be of the type
1034 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1036 * All the bits of the typeDef are added to returning generated TO as
1039 * @param basePackageName
1040 * string with name of package to which the module belongs
1042 * type definition from which is the generated TO builder created
1043 * @param typeDefName
1044 * string with the name for generated TO builder
1045 * @return generated TO builder which represents <code>typeDef</code>
1046 * @throws IllegalArgumentException
1048 * <li>if <code>typeDef</code> equals null</li>
1049 * <li>if <code>basePackageName</code> equals null</li>
1052 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1053 final TypeDefinition<?> typeDef, final String typeDefName) {
1055 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1056 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1058 if (typeDef instanceof BitsTypeDefinition) {
1059 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1061 final String typeName = BindingMapping.getClassName(typeDefName);
1062 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1064 final List<Bit> bitList = bitsTypeDefinition.getBits();
1065 GeneratedPropertyBuilder genPropertyBuilder;
1066 for (final Bit bit : bitList) {
1067 String name = bit.getName();
1068 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
1069 genPropertyBuilder.setReadOnly(true);
1070 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1072 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1073 genTOBuilder.addHashIdentity(genPropertyBuilder);
1074 genTOBuilder.addToStringProperty(genPropertyBuilder);
1077 return genTOBuilder;
1083 * Converts the pattern constraints from <code>typedef</code> to the list of
1084 * the strings which represents these constraints.
1087 * extended type in which are the pattern constraints sought
1088 * @return list of strings which represents the constraint patterns
1089 * @throws IllegalArgumentException
1090 * if <code>typedef</code> equals null
1093 private List<String> resolveRegExpressionsFromTypedef(final ExtendedType typedef) {
1094 final List<String> regExps = new ArrayList<String>();
1095 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1096 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1097 if (strTypeDef instanceof StringType) {
1098 final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1099 if (!patternConstraints.isEmpty()) {
1101 String modifiedRegEx;
1102 for (PatternConstraint patternConstraint : patternConstraints) {
1103 regEx = patternConstraint.getRegularExpression();
1104 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1105 regExps.add(modifiedRegEx);
1114 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1115 * expressions from the <code>regularExpressions</code>
1117 * @param genTOBuilder
1118 * generated TO builder to which are
1119 * <code>regular expressions</code> added
1120 * @param regularExpressions
1121 * list of string which represent regular expressions
1122 * @throws IllegalArgumentException
1124 * <li>if <code>genTOBuilder</code> equals null</li>
1125 * <li>if <code>regularExpressions</code> equals null</li>
1128 private void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1129 if (genTOBuilder == null) {
1130 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1132 if (regularExpressions == null) {
1133 throw new IllegalArgumentException("List of regular expressions can't be null");
1135 if (!regularExpressions.isEmpty()) {
1136 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1137 regularExpressions);
1142 * Creates generated TO with data about inner extended type
1143 * <code>innerExtendedType</code>, about the package name
1144 * <code>typedefName</code> and about the generated TO name
1145 * <code>typedefName</code>.
1147 * It is supposed that <code>innerExtendedType</code> is already present in
1148 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1149 * be possible set it as extended type for the returning generated TO.
1151 * @param innerExtendedType
1152 * extended type which is part of some other extended type
1153 * @param basePackageName
1154 * string with the package name of the module
1155 * @param typedefName
1156 * string with the name for the generated TO
1157 * @return generated TO which extends generated TO for
1158 * <code>innerExtendedType</code>
1159 * @throws IllegalArgumentException
1161 * <li>if <code>extendedType</code> equals null</li>
1162 * <li>if <code>basePackageName</code> equals null</li>
1163 * <li>if <code>typedefName</code> equals null</li>
1166 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1167 final ExtendedType innerExtendedType, final String basePackageName) {
1168 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1169 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1171 final String typedefName = typedef.getQName().getLocalName();
1172 final String classTypedefName = BindingMapping.getClassName(typedefName);
1173 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1174 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1175 genTOBuilder.setTypedef(true);
1176 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1177 genTOBuilder.setRestrictions(r);
1179 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1180 genTOBuilder.setIsUnion(true);
1183 Map<Date, Map<String, Type>> modulesByDate = null;
1184 Map<String, Type> typeMap = null;
1185 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1186 if (parentModule != null) {
1187 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1188 typeMap = modulesByDate.get(parentModule.getRevision());
1191 if (typeMap != null) {
1192 Type type = typeMap.get(innerTypeDef);
1193 if (type instanceof GeneratedTransferObject) {
1194 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1197 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1198 BindingGeneratorUtil.makeSerializable(genTOBuilder);
1200 return genTOBuilder.toInstance();
1204 * Finds out for each type definition how many immersion (depth) is
1205 * necessary to get to the base type. Every type definition is inserted to
1206 * the map which key is depth and value is list of type definitions with
1207 * equal depth. In next step are lists from this map concatenated to one
1208 * list in ascending order according to their depth. All type definitions
1209 * are in the list behind all type definitions on which depends.
1211 * @param unsortedTypeDefinitions
1212 * list of type definitions which should be sorted by depth
1213 * @return list of type definitions sorted according their each other
1214 * dependencies (type definitions which are depend on other type
1215 * definitions are in list behind them).
1217 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1218 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1219 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1221 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1222 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1223 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1224 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1225 if (typeDefinitionsConcreteDepth == null) {
1226 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1227 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1229 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1231 // keys are in ascending order
1232 Set<Integer> depths = typeDefinitionsDepths.keySet();
1233 for (Integer depth : depths) {
1234 sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1237 return sortedTypeDefinition;
1241 * Returns how many immersion is necessary to get from the type definition
1244 * @param typeDefinition
1245 * type definition for which is depth sought.
1246 * @return number of immersions which are necessary to get from the type
1247 * definition to the base type
1249 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1250 if (typeDefinition == null) {
1254 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1256 if (baseType instanceof ExtendedType) {
1257 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1258 } else if (baseType instanceof UnionType) {
1259 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1260 int maxChildDepth = 0;
1262 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1263 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1264 if (childDepth > maxChildDepth) {
1265 maxChildDepth = childDepth;
1268 return maxChildDepth;
1274 * Returns string which contains the same value as <code>name</code> but
1275 * integer suffix is incremented by one. If <code>name</code> contains no
1276 * number suffix then number 1 is added.
1279 * string with name of augmented node
1280 * @return string with the number suffix incremented by one (or 1 is added)
1282 private String provideAvailableNameForGenTOBuilder(final String name) {
1283 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1285 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1286 return name.substring(0, mtch.start()) + newSuffix;
1292 public void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1293 if (units != null && !units.isEmpty()) {
1294 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1295 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1296 prop.setReturnType(Types.STRING);
1297 to.addToStringProperty(prop);
1302 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1303 return getTypeDefaultConstruction(node, node.getDefault());
1306 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1307 TypeDefinition<?> type = node.getType();
1308 QName typeQName = type.getQName();
1309 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1310 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of " + node);
1311 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of "
1314 StringBuilder sb = new StringBuilder();
1315 String result = null;
1316 if (base instanceof BinaryTypeDefinition) {
1317 result = binaryToDef(defaultValue);
1318 } else if (base instanceof BitsTypeDefinition) {
1321 Module parent = getParentModule(node);
1322 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1324 if (!(path.hasNext())) {
1325 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1326 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1327 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1329 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1330 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1331 parentName = BindingMapping.getClassName(((SchemaNode) parent).getQName());
1332 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1334 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1335 } else if (base instanceof BooleanTypeDefinition) {
1336 result = typeToDef(Boolean.class, defaultValue);
1337 } else if (base instanceof DecimalTypeDefinition) {
1338 result = typeToDef(BigDecimal.class, defaultValue);
1339 } else if (base instanceof EmptyTypeDefinition) {
1340 result = typeToDef(Boolean.class, defaultValue);
1341 } else if (base instanceof EnumTypeDefinition) {
1342 char[] defValArray = defaultValue.toCharArray();
1343 char first = Character.toUpperCase(defaultValue.charAt(0));
1344 defValArray[0] = first;
1345 String newDefVal = new String(defValArray);
1347 if (type instanceof ExtendedType) {
1348 Module m = getParentModule(type);
1349 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1350 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1351 className = packageName + "." + BindingMapping.getClassName(typeQName);
1353 Module parentModule = getParentModule(node);
1354 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1355 String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
1356 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1358 result = className + "." + newDefVal;
1359 } else if (base instanceof IdentityrefTypeDefinition) {
1360 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1361 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1362 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1363 } else if (base instanceof Int8) {
1364 result = typeToDef(Byte.class, defaultValue);
1365 } else if (base instanceof Int16) {
1366 result = typeToDef(Short.class, defaultValue);
1367 } else if (base instanceof Int32) {
1368 result = typeToDef(Integer.class, defaultValue);
1369 } else if (base instanceof Int64) {
1370 result = typeToDef(Long.class, defaultValue);
1371 } else if (base instanceof LeafrefTypeDefinition) {
1372 result = leafrefToDef(node, (LeafrefTypeDefinition) base);
1373 } else if (base instanceof StringTypeDefinition) {
1374 result = "\"" + defaultValue + "\"";
1375 } else if (base instanceof Uint8) {
1376 result = typeToDef(Short.class, defaultValue);
1377 } else if (base instanceof Uint16) {
1378 result = typeToDef(Integer.class, defaultValue);
1379 } else if (base instanceof Uint32) {
1380 result = typeToDef(Long.class, defaultValue);
1381 } else if (base instanceof Uint64) {
1382 result = typeToDef(BigInteger.class, defaultValue);
1383 } else if (base instanceof UnionTypeDefinition) {
1384 result = unionToDef(node);
1390 if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
1391 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
1392 Module m = getParentModule(type);
1393 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1394 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1395 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1396 sb.insert(0, "new " + className + "(");
1397 sb.insert(sb.length(), ")");
1400 return sb.toString();
1403 private String typeToDef(final Class<?> clazz, final String defaultValue) {
1404 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1407 private String binaryToDef(final String defaultValue) {
1408 StringBuilder sb = new StringBuilder();
1409 BaseEncoding en = BaseEncoding.base64();
1410 byte[] encoded = en.decode(defaultValue);
1411 sb.append("new byte[] {");
1412 for (int i = 0; i < encoded.length; i++) {
1413 sb.append(encoded[i]);
1414 if (i != encoded.length - 1) {
1419 return sb.toString();
1422 private String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1423 List<Bit> bits = new ArrayList<>(type.getBits());
1424 Collections.sort(bits, new Comparator<Bit>() {
1426 public int compare(final Bit o1, final Bit o2) {
1427 return o1.getName().compareTo(o2.getName());
1430 StringBuilder sb = new StringBuilder();
1431 sb.append(isExt ? "" : "new " + className + "(");
1432 for (int i = 0; i < bits.size(); i++) {
1433 if (bits.get(i).getName().equals(defaultValue)) {
1438 if (i != bits.size() - 1) {
1442 sb.append(isExt ? "" : ")");
1443 return sb.toString();
1446 private Module getParentModule(final SchemaNode node) {
1447 QName qname = node.getPath().getPathFromRoot().iterator().next();
1448 URI namespace = qname.getNamespace();
1449 Date revision = qname.getRevision();
1450 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1453 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType) {
1454 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1455 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1456 "The Path Statement for Leafref Type Definition cannot be NULL!");
1458 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1459 final String strXPath = xpath.toString();
1461 if (strXPath != null) {
1462 if (strXPath.contains("[")) {
1463 return "new java.lang.Object()";
1465 final Module module = findParentModule(schemaContext, parentNode);
1466 if (module != null) {
1467 final SchemaNode dataNode;
1468 if (xpath.isAbsolute()) {
1469 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1471 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1473 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, parentNode.getDefault());
1482 private String unionToDef(final LeafSchemaNode node) {
1486 if (node.getType() instanceof ExtendedType) {
1487 ExtendedType type = (ExtendedType) node.getType();
1488 QName typeQName = type.getQName();
1489 Module module = null;
1490 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1491 if (modules.size() > 1) {
1492 for (Module m : modules) {
1493 if (m.getRevision().equals(typeQName.getRevision())) {
1498 if (module == null) {
1499 List<Module> modulesList = new ArrayList<>(modules);
1500 Collections.sort(modulesList, new Comparator<Module>() {
1502 public int compare(final Module o1, final Module o2) {
1503 return o1.getRevision().compareTo(o2.getRevision());
1506 module = modulesList.get(0);
1509 module = modules.iterator().next();
1512 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
1513 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1515 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1516 QName first = path.next();
1517 if (!(path.hasNext())) {
1518 URI namespace = first.getNamespace();
1519 Date revision = first.getRevision();
1520 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1521 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1522 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1523 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1525 URI namespace = first.getNamespace();
1526 Date revision = first.getRevision();
1527 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1528 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1529 String packageName = packageNameForGeneratedType(basePackageName, node.getType().getPath());
1530 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1533 return union(className, node.getDefault(), node);
1536 private String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1537 StringBuilder sb = new StringBuilder();
1538 sb.append("new " + className + "(");
1540 sb.append(defaultValue);
1542 sb.append(".toCharArray()");
1544 return sb.toString();
1548 public String getConstructorPropertyName(final SchemaNode node) {
1549 if (node instanceof TypeDefinition<?>) {
1557 public String getParamNameFromType(final TypeDefinition<?> type) {
1558 return BindingGeneratorUtil.parseToValidParamName(type.getQName().getLocalName());