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 com.google.common.base.Preconditions;
18 import com.google.common.collect.Sets;
19 import com.google.common.io.BaseEncoding;
20 import java.math.BigDecimal;
21 import java.math.BigInteger;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.Date;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
33 import java.util.TreeMap;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import org.apache.commons.lang3.StringEscapeUtils;
37 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
38 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
39 import org.opendaylight.yangtools.binding.generator.util.Types;
40 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
41 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
42 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
43 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
44 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
45 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
46 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
47 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
48 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
49 import org.opendaylight.yangtools.sal.binding.model.api.Type;
50 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
51 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
53 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
54 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
55 import org.opendaylight.yangtools.yang.binding.BindingMapping;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
65 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
69 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
77 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
80 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
81 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
82 import org.opendaylight.yangtools.yang.model.util.Int16;
83 import org.opendaylight.yangtools.yang.model.util.Int32;
84 import org.opendaylight.yangtools.yang.model.util.Int64;
85 import org.opendaylight.yangtools.yang.model.util.Int8;
86 import org.opendaylight.yangtools.yang.model.util.StringType;
87 import org.opendaylight.yangtools.yang.model.util.Uint16;
88 import org.opendaylight.yangtools.yang.model.util.Uint32;
89 import org.opendaylight.yangtools.yang.model.util.Uint64;
90 import org.opendaylight.yangtools.yang.model.util.Uint8;
91 import org.opendaylight.yangtools.yang.model.util.UnionType;
92 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
94 public final class TypeProviderImpl implements TypeProvider {
95 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
98 * Contains the schema data red from YANG files.
100 private final SchemaContext schemaContext;
103 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
105 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
108 * The map which maps schema paths to JAVA <code>Type</code>.
110 private final Map<SchemaPath, Type> referencedTypes;
111 private final Map<Module, Set<Type>> additionalTypes;
114 * Creates new instance of class <code>TypeProviderImpl</code>.
116 * @param schemaContext
117 * contains the schema data red from YANG files
118 * @throws IllegalArgumentException
119 * if <code>schemaContext</code> equal null.
121 public TypeProviderImpl(final SchemaContext schemaContext) {
122 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
124 this.schemaContext = schemaContext;
125 this.genTypeDefsContextMap = new HashMap<>();
126 this.referencedTypes = new HashMap<>();
127 this.additionalTypes = new HashMap<>();
128 resolveTypeDefsFromContext();
132 * Puts <code>refType</code> to map with key <code>refTypePath</code>
135 * schema path used as the map key
137 * type which represents the map value
138 * @throws IllegalArgumentException
140 * <li>if <code>refTypePath</code> equal null</li>
141 * <li>if <code>refType</code> equal null</li>
145 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
146 Preconditions.checkArgument(refTypePath != null,
147 "Path reference of Enumeration Type Definition cannot be NULL!");
148 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
149 referencedTypes.put(refTypePath, refType);
152 public Map<Module, Set<Type>> getAdditionalTypes() {
153 return additionalTypes;
158 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
161 * string with YANG name of type
162 * @return JAVA <code>Type</code> for YANG type <code>type</code>
163 * @see TypeProvider#javaTypeForYangType(String)
166 public Type javaTypeForYangType(final String type) {
167 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
171 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
172 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
176 * Converts schema definition type <code>typeDefinition</code> to JAVA
179 * @param typeDefinition
180 * type definition which is converted to JAVA type
181 * @throws IllegalArgumentException
183 * <li>if <code>typeDefinition</code> equal null</li>
184 * <li>if Qname of <code>typeDefinition</code> equal null</li>
185 * <li>if name of <code>typeDefinition</code> equal null</li>
189 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
190 final Restrictions r) {
191 Type returnType = null;
192 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
193 if (typeDefinition.getQName() == null) {
194 throw new IllegalArgumentException(
195 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
197 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
198 "Type Definitions Local Name cannot be NULL!");
200 if (typeDefinition instanceof ExtendedType) {
201 returnType = javaTypeForExtendedType(typeDefinition);
203 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
204 if (returnType == null) {
205 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
209 // TODO: add throw exception when we will be able to resolve ALL yang
211 // if (returnType == null) {
212 // throw new IllegalArgumentException("Type Provider can't resolve " +
213 // "type for specified Type Definition " + typedefName);
219 * Returns JAVA <code>Type</code> for instances of the type
220 * <code>LeafrefTypeDefinition</code> or
221 * <code>IdentityrefTypeDefinition</code>.
223 * @param typeDefinition
224 * type definition which is converted to JAVA <code>Type</code>
225 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
227 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
228 if (typeDefinition instanceof LeafrefTypeDefinition) {
229 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
230 return provideTypeForLeafref(leafref, parentNode);
231 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
232 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
233 return provideTypeForIdentityref(idref);
240 * Returns JAVA <code>Type</code> for instances of the type
241 * <code>ExtendedType</code>.
243 * @param typeDefinition
244 * type definition which is converted to JAVA <code>Type</code>
245 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
247 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
248 final String typedefName = typeDefinition.getQName().getLocalName();
249 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
250 Type returnType = null;
251 returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
252 if (returnType == null) {
253 if (baseTypeDef instanceof EnumTypeDefinition) {
254 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
255 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
257 final Module module = findParentModule(schemaContext, typeDefinition);
258 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
259 if (module != null) {
260 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
261 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
262 if (genTOs != null) {
263 returnType = genTOs.get(typedefName);
265 if (returnType == null) {
266 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
267 baseTypeDef, typeDefinition, r);
273 // TODO: add throw exception when we will be able to resolve ALL yang
275 // if (returnType == null) {
276 // throw new IllegalArgumentException("Type Provider can't resolve " +
277 // "type for specified Type Definition " + typedefName);
282 * Seeks for identity reference <code>idref</code> the JAVA
283 * <code>type</code>.<br />
287 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
288 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
291 * identityref type definition for which JAVA <code>Type</code>
293 * @return JAVA <code>Type</code> of the identity which is refrenced through
296 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
297 QName baseIdQName = idref.getIdentity().getQName();
298 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
299 baseIdQName.getRevision());
300 IdentitySchemaNode identity = null;
301 for (IdentitySchemaNode id : module.getIdentities()) {
302 if (id.getQName().equals(baseIdQName)) {
306 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
308 final String basePackageName = moduleNamespaceToPackageName(module);
309 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
310 final String genTypeName = BindingMapping.getClassName(identity.getQName());
312 Type baseType = Types.typeForClass(Class.class);
313 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
314 return Types.parameterizedTypeFor(baseType, paramType);
318 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
320 * @param typeDefinition
321 * type definition which should be converted to JAVA
323 * @return JAVA <code>Type</code> which represents
324 * <code>typeDefinition</code>
325 * @throws IllegalArgumentException
327 * <li>if <code>typeDefinition</code> equal null</li>
328 * <li>if Q name of <code>typeDefinition</code></li>
329 * <li>if name of <code>typeDefinition</code></li>
332 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
333 final SchemaNode parentNode) {
334 Type returnType = null;
335 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
336 if (typeDefinition.getQName() == null) {
337 throw new IllegalArgumentException(
338 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
340 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
341 "Type Definitions Local Name cannot be NULL!");
343 final String typedefName = typeDefinition.getQName().getLocalName();
344 if (typeDefinition instanceof ExtendedType) {
345 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
347 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
348 final Module module = findParentModule(schemaContext, parentNode);
350 if (module != null) {
351 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
352 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
353 if (genTOs != null) {
354 returnType = genTOs.get(typedefName);
363 * Gets base type definition for <code>extendTypeDef</code>. The method is
364 * recursivelly called until non <code>ExtendedType</code> type is found.
366 * @param extendTypeDef
367 * type definition for which is the base type definition sought
368 * @return type definition which is base type for <code>extendTypeDef</code>
369 * @throws IllegalArgumentException
370 * if <code>extendTypeDef</code> equal null
372 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
373 Preconditions.checkArgument(extendTypeDef != null, "Type Definiition reference cannot be NULL!");
374 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
375 if (baseTypeDef == null) {
376 return extendTypeDef;
377 } else if (baseTypeDef instanceof ExtendedType) {
378 return baseTypeDefForExtendedType(baseTypeDef);
386 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
388 * The path of <code>leafrefType</code> is followed to find referenced node
389 * and its <code>Type</code> is returned.
392 * leafref type definition for which is the type sought
393 * @return JAVA <code>Type</code> of data schema node which is referenced in
394 * <code>leafrefType</code>
395 * @throws IllegalArgumentException
397 * <li>if <code>leafrefType</code> equal null</li>
398 * <li>if path statement of <code>leafrefType</code> equal null</li>
402 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
403 Type returnType = null;
404 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
406 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
407 "The Path Statement for Leafref Type Definition cannot be NULL!");
409 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
410 final String strXPath = xpath.toString();
412 if (strXPath != null) {
413 if (strXPath.contains("[")) {
414 returnType = Types.typeForClass(Object.class);
416 final Module module = findParentModule(schemaContext, parentNode);
417 if (module != null) {
418 final SchemaNode dataNode;
419 if (xpath.isAbsolute()) {
420 dataNode = findDataSchemaNode(schemaContext, module, xpath);
422 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
425 if (leafContainsEnumDefinition(dataNode)) {
426 returnType = referencedTypes.get(dataNode.getPath());
427 } else if (leafListContainsEnumDefinition(dataNode)) {
428 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
430 returnType = resolveTypeFromDataSchemaNode(dataNode);
435 if (returnType == null) {
436 throw new IllegalArgumentException("Failed to find leafref target: " + strXPath);
442 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
443 * so then checks if it is of type <code>EnumTypeDefinition</code>.
446 * data schema node for which is checked if it is leaf and if it
448 * @return boolean value
450 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
451 * <li>false - other cases</li>
454 private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
455 if (dataNode instanceof LeafSchemaNode) {
456 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
457 if (leaf.getType() instanceof EnumTypeDefinition) {
465 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
466 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
469 * data schema node for which is checked if it is leaflist and if
471 * @return boolean value
473 * <li>true - if <code>dataNode</code> is leaflist of type
475 * <li>false - other cases</li>
478 private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
479 if (dataNode instanceof LeafListSchemaNode) {
480 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
481 if (leafList.getType() instanceof EnumTypeDefinition) {
489 * Converts <code>enumTypeDef</code> to
490 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
494 * enumeration type definition which is converted to enumeration
496 * string with name which is used as the enumeration name
497 * @return enumeration type which is built with data (name, enum values)
498 * from <code>enumTypeDef</code>
499 * @throws IllegalArgumentException
501 * <li>if <code>enumTypeDef</code> equals null</li>
502 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
503 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
504 * <li>if name of <code>enumTypeDef</code> equal null</li>
507 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
508 final SchemaNode parentNode) {
509 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
510 Preconditions.checkArgument(enumTypeDef.getValues() != null,
511 "EnumTypeDefinition MUST contain at least ONE value definition!");
512 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
513 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
514 "Local Name in EnumTypeDefinition QName cannot be NULL!");
516 final String enumerationName = BindingMapping.getClassName(enumName);
518 Module module = findParentModule(schemaContext, parentNode);
519 final String basePackageName = moduleNamespaceToPackageName(module);
521 final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
522 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
523 return enumBuilder.toInstance(null);
527 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
528 * taken from <code>enumTypeDef</code>.
531 * enumeration type definition is source of enumeration data for
532 * <code>typeBuilder</code>
534 * string with the name of enumeration
536 * generated type builder to which is enumeration added
537 * @return enumeration type which contains enumeration data form
538 * <code>enumTypeDef</code>
539 * @throws IllegalArgumentException
541 * <li>if <code>enumTypeDef</code> equals null</li>
542 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
543 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
544 * <li>if name of <code>enumTypeDef</code> equal null</li>
545 * <li>if name of <code>typeBuilder</code> equal null</li>
549 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
550 final GeneratedTypeBuilderBase<?> typeBuilder) {
551 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
552 Preconditions.checkArgument(enumTypeDef.getValues() != null,
553 "EnumTypeDefinition MUST contain at least ONE value definition!");
554 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
555 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
556 "Local Name in EnumTypeDefinition QName cannot be NULL!");
557 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
559 final String enumerationName = BindingMapping.getClassName(enumName);
561 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
562 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
563 return enumBuilder.toInstance(enumBuilder);
567 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
570 * contains information about YANG type
571 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
573 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
574 Type returnType = null;
575 if (dataNode != null) {
576 if (dataNode instanceof LeafSchemaNode) {
577 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
578 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
579 } else if (dataNode instanceof LeafListSchemaNode) {
580 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
581 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
588 * Passes through all modules and through all its type definitions and
589 * convert it to generated types.
591 * The modules are firstly sorted by mutual dependencies. The modules are
592 * sequentially passed. All type definitions of a module are at the
593 * beginning sorted so that type definition with less amount of references
594 * to other type definition are processed first.<br />
595 * For each module is created mapping record in the map
596 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
597 * which map current module name to the map which maps type names to
598 * returned types (generated types).
601 private void resolveTypeDefsFromContext() {
602 final Set<Module> modules = schemaContext.getModules();
603 Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
604 final Module[] modulesArray = new Module[modules.size()];
606 for (Module modul : modules) {
607 modulesArray[i++] = modul;
609 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modulesArray);
611 for (final Module module : modulesSortedByDependency) {
612 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
613 if (dateTypeMap == null) {
614 dateTypeMap = new HashMap<>();
616 final Map<String, Type> typeMap = new HashMap<>();
617 dateTypeMap.put(module.getRevision(), typeMap);
618 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
621 for (final Module module : modulesSortedByDependency) {
622 if (module == null) {
625 final String basePackageName = moduleNamespaceToPackageName(module);
627 final DataNodeIterator it = new DataNodeIterator(module);
628 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
629 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
631 if ((listTypeDefinitions != null) && (basePackageName != null)) {
632 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
633 typedefToGeneratedType(basePackageName, module, typedef);
641 * @param basePackageName
642 * string with name of package to which the module belongs
644 * string with the name of the module for to which the
645 * <code>typedef</code> belongs
647 * type definition of the node for which should be creted JAVA
648 * <code>Type</code> (usually generated TO)
649 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
650 * <code>null</code> value if <code>basePackageName</code> or
651 * <code>modulName</code> or <code>typedef</code> or Q name of
652 * <code>typedef</code> equals <code>null</code>
654 private Type typedefToGeneratedType(final String basePackageName, final Module module,
655 final TypeDefinition<?> typedef) {
656 final String moduleName = module.getName();
657 final Date moduleRevision = module.getRevision();
658 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
660 final String typedefName = typedef.getQName().getLocalName();
661 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
662 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
663 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
664 Type returnType = null;
665 if (innerTypeDefinition instanceof ExtendedType) {
666 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
667 returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName);
668 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
669 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
670 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
671 genTOBuilder.setTypedef(true);
672 genTOBuilder.setIsUnion(true);
673 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
674 BindingGeneratorUtil.makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
675 returnType = genTOBuilder.toInstance();
677 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
678 genTOBuilder.getName() + "Builder");
679 unionBuilder.setIsUnionBuilder(true);
680 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
681 method.setReturnType(returnType);
682 method.addParameter(Types.STRING, "defaultValue");
683 method.setAccessModifier(AccessModifier.PUBLIC);
684 method.setStatic(true);
685 Set<Type> types = additionalTypes.get(module);
687 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
688 additionalTypes.put(module, types);
690 types.add(unionBuilder.toInstance());
692 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
693 // enums are automatically Serializable
694 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
695 // TODO units for typedef enum
696 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
697 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
698 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
699 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
700 basePackageName, bitsTypeDefinition, typedefName);
701 genTOBuilder.setTypedef(true);
702 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
703 BindingGeneratorUtil.makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
704 returnType = genTOBuilder.toInstance();
706 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
707 innerTypeDefinition, typedef);
708 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
710 if (returnType != null) {
711 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
712 final Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
713 if (typeMap != null) {
714 typeMap.put(typedefName, returnType);
724 * Wraps base YANG type to generated TO.
726 * @param basePackageName
727 * string with name of package to which the module belongs
729 * type definition which is converted to the TO
731 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
732 * @return generated transfer object which represent<code>javaType</code>
734 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
735 final Type javaType) {
736 Preconditions.checkNotNull(javaType, "javaType cannot be null");
737 final String propertyName = "value";
739 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
740 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
741 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
742 genPropBuilder.setReturnType(javaType);
743 genTOBuilder.addEqualsIdentity(genPropBuilder);
744 genTOBuilder.addHashIdentity(genPropBuilder);
745 genTOBuilder.addToStringProperty(genPropBuilder);
746 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef instanceof ExtendedType) {
747 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
748 addStringRegExAsConstant(genTOBuilder, regExps);
750 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
751 genTOBuilder.setTypedef(true);
752 BindingGeneratorUtil.makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
753 return genTOBuilder.toInstance();
757 * Converts output list of generated TO builders to one TO builder (first
758 * from list) which contains the remaining builders as its enclosing TO.
760 * @param basePackageName
761 * string with name of package to which the module belongs
763 * type definition which should be of type
764 * <code>UnionTypeDefinition</code>
766 * string with name for generated TO
767 * @return generated TO builder with the list of enclosed generated TO
770 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
771 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
772 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
773 typedef, typeDefName, parentNode);
774 GeneratedTOBuilder resultTOBuilder = null;
775 if (!genTOBuilders.isEmpty()) {
776 resultTOBuilder = genTOBuilders.remove(0);
777 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
778 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
782 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
783 genPropBuilder.setReturnType(Types.primitiveType("char[]", null));
784 resultTOBuilder.addEqualsIdentity(genPropBuilder);
785 resultTOBuilder.addHashIdentity(genPropBuilder);
786 resultTOBuilder.addToStringProperty(genPropBuilder);
788 return resultTOBuilder;
792 * Converts <code>typedef</code> to generated TO with
793 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
794 * added to generated TO builder as property.
796 * @param basePackageName
797 * string with name of package to which the module belongs
799 * type definition which should be of type
800 * <code>UnionTypeDefinition</code>
802 * string with name for generated TO
803 * @return generated TO builder which represents <code>typedef</code>
804 * @throws NullPointerException
806 * <li>if <code>basePackageName</code> is null</li>
807 * <li>if <code>typedef</code> is null</li>
808 * <li>if Qname of <code>typedef</code> is null</li>
811 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
812 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
813 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
814 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
815 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
817 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
818 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
820 final GeneratedTOBuilder unionGenTOBuilder;
821 if (typeDefName != null && !typeDefName.isEmpty()) {
822 final String typeName = BindingMapping.getClassName(typeDefName);
823 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
825 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
828 generatedTOBuilders.add(unionGenTOBuilder);
829 unionGenTOBuilder.setIsUnion(true);
830 final List<String> regularExpressions = new ArrayList<String>();
831 for (final TypeDefinition<?> unionType : unionTypes) {
832 final String unionTypeName = unionType.getQName().getLocalName();
833 if (unionType instanceof UnionType) {
834 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
835 basePackageName, parentNode));
836 } else if (unionType instanceof ExtendedType) {
837 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, regularExpressions,
839 } else if (unionType instanceof EnumTypeDefinition) {
840 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
841 unionTypeName, unionGenTOBuilder);
842 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
844 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
846 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
849 if (!regularExpressions.isEmpty()) {
850 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
853 storeGenTO(typedef, unionGenTOBuilder, parentNode);
855 return generatedTOBuilders;
859 * Wraps code which handle case when union subtype is also of the type
860 * <code>UnionType</code>.
862 * In this case the new generated TO is created for union subtype (recursive
864 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, TypeDefinition, String)
865 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
866 * <code>parentUnionGenTOBuilder</code> is created property which type is
867 * equal to new generated TO.
869 * @param parentUnionGenTOBuilder
870 * generated TO builder to which is the property with the child
871 * union subtype added
872 * @param basePackageName
873 * string with the name of the module package
874 * @param unionSubtype
875 * type definition which represents union subtype
876 * @return list of generated TO builders. The number of the builders can be
877 * bigger one due to recursive call of
878 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
880 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
881 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
882 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
883 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
884 basePackageName, unionSubtype, newTOBuilderName, parentNode);
886 final GeneratedPropertyBuilder propertyBuilder;
887 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
888 .parseToValidParamName(newTOBuilderName));
889 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
890 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
891 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
893 return subUnionGenTOBUilders;
897 * Wraps code which handle case when union subtype is of the type
898 * <code>ExtendedType</code>.
900 * If TO for this type already exists it is used for the creation of the
901 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
902 * type is used for the property creation.
904 * @param parentUnionGenTOBuilder
905 * generated TO builder in which new property is created
906 * @param unionSubtype
907 * type definition of the <code>ExtendedType</code> type which
908 * represents union subtype
909 * @param unionTypeName
910 * string with the name for <code>unionSubtype</code>
911 * @param regularExpressions
912 * list of strings with the regular expressions
914 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
915 final ExtendedType unionSubtype, final List<String> regularExpressions,
916 final SchemaNode parentNode) {
917 final String unionTypeName = unionSubtype.getQName().getLocalName();
918 final Type genTO = findGenTO(unionTypeName, unionSubtype);
920 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
922 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
923 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
924 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
926 if (javaType != null) {
927 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
930 if (baseType instanceof StringType) {
931 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
937 * Searches for generated TO for <code>searchedTypeDef</code> type
938 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
940 * @param searchedTypeName
941 * string with name of <code>searchedTypeDef</code>
942 * @return generated TO for <code>searchedTypeDef</code> or
943 * <code>null</code> it it doesn't exist
945 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
946 final Module typeModule = findParentModule(schemaContext, parentNode);
947 if (typeModule != null && typeModule.getName() != null) {
948 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
949 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
950 if (genTOs != null) {
951 return genTOs.get(searchedTypeName);
958 * Stores generated TO created from <code>genTOBuilder</code> for
959 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
960 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
963 * type definition for which is <code>genTOBuilder</code> created
964 * @param genTOBuilder
965 * generated TO builder which is converted to generated TO and
968 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
969 if (!(newTypeDef instanceof UnionType)) {
971 final Module parentModule = findParentModule(schemaContext, parentNode);
972 if (parentModule != null && parentModule.getName() != null) {
973 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
974 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
975 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
981 * Adds a new property with the name <code>propertyName</code> and with type
982 * <code>type</code> to <code>unonGenTransObject</code>.
984 * @param unionGenTransObject
985 * generated TO to which should be property added
987 * JAVA <code>type</code> of the property which should be added
988 * to <code>unionGentransObject</code>
989 * @param propertyName
990 * string with name of property which should be added to
991 * <code>unionGentransObject</code>
993 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
994 final String propertyName) {
995 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
996 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
997 .addProperty(parseToValidParamName(propertyName));
998 propBuilder.setReturnType(type);
1000 unionGenTransObject.addEqualsIdentity(propBuilder);
1001 unionGenTransObject.addHashIdentity(propBuilder);
1002 unionGenTransObject.addToStringProperty(propBuilder);
1007 * Converts <code>typedef</code> to the generated TO builder.
1009 * @param basePackageName
1010 * string with name of package to which the module belongs
1012 * type definition from which is the generated TO builder created
1013 * @return generated TO builder which contains data from
1014 * <code>typedef</code> and <code>basePackageName</code>
1016 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
1018 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
1019 final String typeDefTOName = typedef.getQName().getLocalName();
1021 if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
1022 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1023 final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1024 newType.addComment(typedef.getDescription());
1031 * Converts <code>typeDef</code> which should be of the type
1032 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1034 * All the bits of the typeDef are added to returning generated TO as
1037 * @param basePackageName
1038 * string with name of package to which the module belongs
1040 * type definition from which is the generated TO builder created
1041 * @param typeDefName
1042 * string with the name for generated TO builder
1043 * @return generated TO builder which represents <code>typeDef</code>
1044 * @throws IllegalArgumentException
1046 * <li>if <code>typeDef</code> equals null</li>
1047 * <li>if <code>basePackageName</code> equals null</li>
1050 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1051 final TypeDefinition<?> typeDef, final String typeDefName) {
1053 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1054 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1056 if (typeDef instanceof BitsTypeDefinition) {
1057 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1059 final String typeName = BindingMapping.getClassName(typeDefName);
1060 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1062 final List<Bit> bitList = bitsTypeDefinition.getBits();
1063 GeneratedPropertyBuilder genPropertyBuilder;
1064 for (final Bit bit : bitList) {
1065 String name = bit.getName();
1066 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
1067 genPropertyBuilder.setReadOnly(true);
1068 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1070 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1071 genTOBuilder.addHashIdentity(genPropertyBuilder);
1072 genTOBuilder.addToStringProperty(genPropertyBuilder);
1075 return genTOBuilder;
1081 * Converts the pattern constraints from <code>typedef</code> to the list of
1082 * the strings which represents these constraints.
1085 * extended type in which are the pattern constraints sought
1086 * @return list of strings which represents the constraint patterns
1087 * @throws IllegalArgumentException
1088 * if <code>typedef</code> equals null
1091 private List<String> resolveRegExpressionsFromTypedef(final ExtendedType typedef) {
1092 final List<String> regExps = new ArrayList<String>();
1093 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1094 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1095 if (strTypeDef instanceof StringType) {
1096 final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1097 if (!patternConstraints.isEmpty()) {
1099 String modifiedRegEx;
1100 for (PatternConstraint patternConstraint : patternConstraints) {
1101 regEx = patternConstraint.getRegularExpression();
1102 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1103 regExps.add(modifiedRegEx);
1112 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1113 * expressions from the <code>regularExpressions</code>
1115 * @param genTOBuilder
1116 * generated TO builder to which are
1117 * <code>regular expressions</code> added
1118 * @param regularExpressions
1119 * list of string which represent regular expressions
1120 * @throws IllegalArgumentException
1122 * <li>if <code>genTOBuilder</code> equals null</li>
1123 * <li>if <code>regularExpressions</code> equals null</li>
1126 private void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1127 if (genTOBuilder == null) {
1128 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1130 if (regularExpressions == null) {
1131 throw new IllegalArgumentException("List of regular expressions can't be null");
1133 if (!regularExpressions.isEmpty()) {
1134 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1135 regularExpressions);
1140 * Creates generated TO with data about inner extended type
1141 * <code>innerExtendedType</code>, about the package name
1142 * <code>typedefName</code> and about the generated TO name
1143 * <code>typedefName</code>.
1145 * It is supposed that <code>innerExtendedType</code> is already present in
1146 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1147 * be possible set it as extended type for the returning generated TO.
1149 * @param innerExtendedType
1150 * extended type which is part of some other extended type
1151 * @param basePackageName
1152 * string with the package name of the module
1153 * @param typedefName
1154 * string with the name for the generated TO
1155 * @return generated TO which extends generated TO for
1156 * <code>innerExtendedType</code>
1157 * @throws IllegalArgumentException
1159 * <li>if <code>extendedType</code> equals null</li>
1160 * <li>if <code>basePackageName</code> equals null</li>
1161 * <li>if <code>typedefName</code> equals null</li>
1164 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1165 final ExtendedType innerExtendedType, final String basePackageName) {
1166 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1167 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1169 final String typedefName = typedef.getQName().getLocalName();
1170 final String classTypedefName = BindingMapping.getClassName(typedefName);
1171 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1172 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1173 genTOBuilder.setTypedef(true);
1174 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1175 genTOBuilder.setRestrictions(r);
1177 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1178 genTOBuilder.setIsUnion(true);
1181 Map<Date, Map<String, Type>> modulesByDate = null;
1182 Map<String, Type> typeMap = null;
1183 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1184 if (parentModule != null) {
1185 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1186 typeMap = modulesByDate.get(parentModule.getRevision());
1189 if (typeMap != null) {
1190 Type type = typeMap.get(innerTypeDef);
1191 if (type instanceof GeneratedTransferObject) {
1192 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1195 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1196 BindingGeneratorUtil.makeSerializable(genTOBuilder);
1198 return genTOBuilder.toInstance();
1202 * Finds out for each type definition how many immersion (depth) is
1203 * necessary to get to the base type. Every type definition is inserted to
1204 * the map which key is depth and value is list of type definitions with
1205 * equal depth. In next step are lists from this map concatenated to one
1206 * list in ascending order according to their depth. All type definitions
1207 * are in the list behind all type definitions on which depends.
1209 * @param unsortedTypeDefinitions
1210 * list of type definitions which should be sorted by depth
1211 * @return list of type definitions sorted according their each other
1212 * dependencies (type definitions which are depend on other type
1213 * definitions are in list behind them).
1215 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1216 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1217 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1219 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1220 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1221 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1222 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1223 if (typeDefinitionsConcreteDepth == null) {
1224 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1225 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1227 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1229 // keys are in ascending order
1230 Set<Integer> depths = typeDefinitionsDepths.keySet();
1231 for (Integer depth : depths) {
1232 sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1235 return sortedTypeDefinition;
1239 * Returns how many immersion is necessary to get from the type definition
1242 * @param typeDefinition
1243 * type definition for which is depth sought.
1244 * @return number of immersions which are necessary to get from the type
1245 * definition to the base type
1247 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1248 if (typeDefinition == null) {
1252 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1254 if (baseType instanceof ExtendedType) {
1255 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1256 } else if (baseType instanceof UnionType) {
1257 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1258 int maxChildDepth = 0;
1260 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1261 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1262 if (childDepth > maxChildDepth) {
1263 maxChildDepth = childDepth;
1266 return maxChildDepth;
1272 * Returns string which contains the same value as <code>name</code> but
1273 * integer suffix is incremented by one. If <code>name</code> contains no
1274 * number suffix then number 1 is added.
1277 * string with name of augmented node
1278 * @return string with the number suffix incremented by one (or 1 is added)
1280 private String provideAvailableNameForGenTOBuilder(final String name) {
1281 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1283 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1284 return name.substring(0, mtch.start()) + newSuffix;
1290 public void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1291 if (units != null && !units.isEmpty()) {
1292 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1293 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1294 prop.setReturnType(Types.STRING);
1295 to.addToStringProperty(prop);
1300 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1301 return getTypeDefaultConstruction(node, node.getDefault());
1304 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1305 TypeDefinition<?> type = node.getType();
1306 QName typeQName = type.getQName();
1307 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1308 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of " + node);
1309 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of "
1312 StringBuilder sb = new StringBuilder();
1313 String result = null;
1314 if (base instanceof BinaryTypeDefinition) {
1315 result = binaryToDef(defaultValue);
1316 } else if (base instanceof BitsTypeDefinition) {
1319 Module parent = getParentModule(node);
1320 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1322 if (!(path.hasNext())) {
1323 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1324 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1325 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1327 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1328 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1329 parentName = BindingMapping.getClassName(((SchemaNode) parent).getQName());
1330 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1332 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1333 } else if (base instanceof BooleanTypeDefinition) {
1334 result = typeToDef(Boolean.class, defaultValue);
1335 } else if (base instanceof DecimalTypeDefinition) {
1336 result = typeToDef(BigDecimal.class, defaultValue);
1337 } else if (base instanceof EmptyTypeDefinition) {
1338 result = typeToDef(Boolean.class, defaultValue);
1339 } else if (base instanceof EnumTypeDefinition) {
1340 char[] defValArray = defaultValue.toCharArray();
1341 char first = Character.toUpperCase(defaultValue.charAt(0));
1342 defValArray[0] = first;
1343 String newDefVal = new String(defValArray);
1345 if (type instanceof ExtendedType) {
1346 Module m = getParentModule(type);
1347 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1348 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1349 className = packageName + "." + BindingMapping.getClassName(typeQName);
1351 Module parentModule = getParentModule(node);
1352 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1353 String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
1354 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1356 result = className + "." + newDefVal;
1357 } else if (base instanceof IdentityrefTypeDefinition) {
1358 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1359 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1360 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1361 } else if (base instanceof Int8) {
1362 result = typeToDef(Byte.class, defaultValue);
1363 } else if (base instanceof Int16) {
1364 result = typeToDef(Short.class, defaultValue);
1365 } else if (base instanceof Int32) {
1366 result = typeToDef(Integer.class, defaultValue);
1367 } else if (base instanceof Int64) {
1368 result = typeToDef(Long.class, defaultValue);
1369 } else if (base instanceof LeafrefTypeDefinition) {
1370 result = leafrefToDef(node, (LeafrefTypeDefinition) base);
1371 } else if (base instanceof StringTypeDefinition) {
1372 result = "\"" + defaultValue + "\"";
1373 } else if (base instanceof Uint8) {
1374 result = typeToDef(Short.class, defaultValue);
1375 } else if (base instanceof Uint16) {
1376 result = typeToDef(Integer.class, defaultValue);
1377 } else if (base instanceof Uint32) {
1378 result = typeToDef(Long.class, defaultValue);
1379 } else if (base instanceof Uint64) {
1380 result = typeToDef(BigInteger.class, defaultValue);
1381 } else if (base instanceof UnionTypeDefinition) {
1382 result = unionToDef(node);
1388 if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
1389 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
1390 Module m = getParentModule(type);
1391 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1392 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1393 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1394 sb.insert(0, "new " + className + "(");
1395 sb.insert(sb.length(), ")");
1398 return sb.toString();
1401 private String typeToDef(final Class<?> clazz, final String defaultValue) {
1402 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1405 private String binaryToDef(final String defaultValue) {
1406 StringBuilder sb = new StringBuilder();
1407 BaseEncoding en = BaseEncoding.base64();
1408 byte[] encoded = en.decode(defaultValue);
1409 sb.append("new byte[] {");
1410 for (int i = 0; i < encoded.length; i++) {
1411 sb.append(encoded[i]);
1412 if (i != encoded.length - 1) {
1417 return sb.toString();
1420 private String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1421 List<Bit> bits = new ArrayList<>(type.getBits());
1422 Collections.sort(bits, new Comparator<Bit>() {
1424 public int compare(final Bit o1, final Bit o2) {
1425 return o1.getName().compareTo(o2.getName());
1428 StringBuilder sb = new StringBuilder();
1429 sb.append(isExt ? "" : "new " + className + "(");
1430 for (int i = 0; i < bits.size(); i++) {
1431 if (bits.get(i).getName().equals(defaultValue)) {
1436 if (i != bits.size() - 1) {
1440 sb.append(isExt ? "" : ")");
1441 return sb.toString();
1444 private Module getParentModule(final SchemaNode node) {
1445 QName qname = node.getPath().getPathFromRoot().iterator().next();
1446 URI namespace = qname.getNamespace();
1447 Date revision = qname.getRevision();
1448 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1451 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType) {
1452 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1453 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1454 "The Path Statement for Leafref Type Definition cannot be NULL!");
1456 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1457 final String strXPath = xpath.toString();
1459 if (strXPath != null) {
1460 if (strXPath.contains("[")) {
1461 return "new java.lang.Object()";
1463 final Module module = findParentModule(schemaContext, parentNode);
1464 if (module != null) {
1465 final SchemaNode dataNode;
1466 if (xpath.isAbsolute()) {
1467 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1469 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1471 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, parentNode.getDefault());
1480 private String unionToDef(final LeafSchemaNode node) {
1484 if (node.getType() instanceof ExtendedType) {
1485 ExtendedType type = (ExtendedType) node.getType();
1486 QName typeQName = type.getQName();
1487 Module module = null;
1488 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1489 if (modules.size() > 1) {
1490 for (Module m : modules) {
1491 if (m.getRevision().equals(typeQName.getRevision())) {
1496 if (module == null) {
1497 List<Module> modulesList = new ArrayList<>(modules);
1498 Collections.sort(modulesList, new Comparator<Module>() {
1500 public int compare(final Module o1, final Module o2) {
1501 return o1.getRevision().compareTo(o2.getRevision());
1504 module = modulesList.get(0);
1507 module = modules.iterator().next();
1510 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
1511 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1513 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1514 QName first = path.next();
1515 if (!(path.hasNext())) {
1516 URI namespace = first.getNamespace();
1517 Date revision = first.getRevision();
1518 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1519 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1520 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1521 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1523 URI namespace = first.getNamespace();
1524 Date revision = first.getRevision();
1525 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1526 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1527 String packageName = packageNameForGeneratedType(basePackageName, node.getType().getPath());
1528 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1531 return union(className, node.getDefault(), node);
1534 private String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1535 StringBuilder sb = new StringBuilder();
1536 sb.append("new " + className + "(");
1538 sb.append(defaultValue);
1540 sb.append(".toCharArray()");
1542 return sb.toString();
1546 public String getConstructorPropertyName(final SchemaNode node) {
1547 if (node instanceof TypeDefinition<?>) {
1555 public String getParamNameFromType(final TypeDefinition<?> type) {
1556 return BindingGeneratorUtil.parseToValidParamName(type.getQName().getLocalName());