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.yang.model.util.SchemaContextUtil.findDataSchemaNode;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
14 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
16 import com.google.common.base.Preconditions;
17 import com.google.common.collect.Sets;
18 import com.google.common.io.BaseEncoding;
19 import java.io.Serializable;
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.GeneratedProperty;
48 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
49 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
50 import org.opendaylight.yangtools.sal.binding.model.api.Type;
51 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
53 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
54 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
55 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
56 import org.opendaylight.yangtools.yang.binding.BindingMapping;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.Module;
62 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
66 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
67 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
69 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
70 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
78 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
81 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
82 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
83 import org.opendaylight.yangtools.yang.model.util.Int16;
84 import org.opendaylight.yangtools.yang.model.util.Int32;
85 import org.opendaylight.yangtools.yang.model.util.Int64;
86 import org.opendaylight.yangtools.yang.model.util.Int8;
87 import org.opendaylight.yangtools.yang.model.util.StringType;
88 import org.opendaylight.yangtools.yang.model.util.Uint16;
89 import org.opendaylight.yangtools.yang.model.util.Uint32;
90 import org.opendaylight.yangtools.yang.model.util.Uint64;
91 import org.opendaylight.yangtools.yang.model.util.Uint8;
92 import org.opendaylight.yangtools.yang.model.util.UnionType;
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)
167 public Type javaTypeForYangType(final String type) {
168 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
172 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
173 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
177 * Converts schema definition type <code>typeDefinition</code> to JAVA
180 * @param typeDefinition
181 * type definition which is converted to JAVA type
182 * @throws IllegalArgumentException
184 * <li>if <code>typeDefinition</code> equal null</li>
185 * <li>if Qname of <code>typeDefinition</code> equal null</li>
186 * <li>if name of <code>typeDefinition</code> equal null</li>
190 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
191 final Restrictions r) {
193 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
194 Preconditions.checkArgument(typeDefinition.getQName() != null,
195 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
196 String typedefName = typeDefinition.getQName().getLocalName();
197 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
199 if (typeDefinition instanceof ExtendedType) {
200 returnType = javaTypeForExtendedType(typeDefinition);
201 if (r != null && returnType instanceof GeneratedTransferObject) {
202 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
203 Module module = findParentModule(schemaContext, parentNode);
204 String basePackageName = moduleNamespaceToPackageName(module);
205 String packageName = packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
206 String genTOName = BindingMapping.getClassName(typedefName);
207 String name = packageName + "." + genTOName;
208 if (!(returnType.getFullyQualifiedName().equals(name))) {
209 returnType = shadedTOWithRestrictions(gto, r);
213 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
214 if (returnType == null) {
215 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
222 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
223 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
224 GeneratedTransferObject parent = gto.getSuperType();
225 if (parent != null) {
226 gtob.setExtendsType(parent);
228 gtob.setRestrictions(r);
229 for (GeneratedProperty gp : gto.getProperties()) {
230 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
231 gpb.setValue(gp.getValue());
232 gpb.setReadOnly(gp.isReadOnly());
233 gpb.setAccessModifier(gp.getAccessModifier());
234 gpb.setReturnType(gp.getReturnType());
235 gpb.setFinal(gp.isFinal());
236 gpb.setStatic(gp.isStatic());
238 return gtob.toInstance();
242 * Returns JAVA <code>Type</code> for instances of the type
243 * <code>LeafrefTypeDefinition</code> or
244 * <code>IdentityrefTypeDefinition</code>.
246 * @param typeDefinition
247 * type definition which is converted to JAVA <code>Type</code>
248 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
250 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
251 if (typeDefinition instanceof LeafrefTypeDefinition) {
252 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
253 return provideTypeForLeafref(leafref, parentNode);
254 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
255 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
256 return provideTypeForIdentityref(idref);
263 * Returns JAVA <code>Type</code> for instances of the type
264 * <code>ExtendedType</code>.
266 * @param typeDefinition
267 * type definition which is converted to JAVA <code>Type</code>
268 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
270 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
271 final String typedefName = typeDefinition.getQName().getLocalName();
272 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
273 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
274 if (returnType == null) {
275 if (baseTypeDef instanceof EnumTypeDefinition) {
276 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
277 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
279 final Module module = findParentModule(schemaContext, typeDefinition);
280 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
281 if (module != null) {
282 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
283 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
284 if (genTOs != null) {
285 returnType = genTOs.get(typedefName);
287 if (returnType == null) {
288 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
289 baseTypeDef, typeDefinition, r);
298 * Seeks for identity reference <code>idref</code> the JAVA
299 * <code>type</code>.<br />
303 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
304 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
307 * identityref type definition for which JAVA <code>Type</code>
309 * @return JAVA <code>Type</code> of the identity which is refrenced through
312 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
313 QName baseIdQName = idref.getIdentity().getQName();
314 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
315 baseIdQName.getRevision());
316 IdentitySchemaNode identity = null;
317 for (IdentitySchemaNode id : module.getIdentities()) {
318 if (id.getQName().equals(baseIdQName)) {
322 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
324 final String basePackageName = moduleNamespaceToPackageName(module);
325 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
326 final String genTypeName = BindingMapping.getClassName(identity.getQName());
328 Type baseType = Types.typeForClass(Class.class);
329 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
330 return Types.parameterizedTypeFor(baseType, paramType);
334 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
336 * @param typeDefinition
337 * type definition which should be converted to JAVA
339 * @return JAVA <code>Type</code> which represents
340 * <code>typeDefinition</code>
341 * @throws IllegalArgumentException
343 * <li>if <code>typeDefinition</code> equal null</li>
344 * <li>if Q name of <code>typeDefinition</code></li>
345 * <li>if name of <code>typeDefinition</code></li>
348 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
349 final SchemaNode parentNode) {
350 Type returnType = null;
351 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
352 if (typeDefinition.getQName() == null) {
353 throw new IllegalArgumentException(
354 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
356 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
357 "Type Definitions Local Name cannot be NULL!");
359 final String typedefName = typeDefinition.getQName().getLocalName();
360 if (typeDefinition instanceof ExtendedType) {
361 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
363 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
364 final Module module = findParentModule(schemaContext, parentNode);
366 if (module != null) {
367 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
368 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
369 if (genTOs != null) {
370 returnType = genTOs.get(typedefName);
379 * Gets base type definition for <code>extendTypeDef</code>. The method is
380 * recursivelly called until non <code>ExtendedType</code> type is found.
382 * @param extendTypeDef
383 * type definition for which is the base type definition sought
384 * @return type definition which is base type for <code>extendTypeDef</code>
385 * @throws IllegalArgumentException
386 * if <code>extendTypeDef</code> equal null
388 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
389 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
390 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
391 if (baseTypeDef == null) {
392 return extendTypeDef;
393 } else if (baseTypeDef instanceof ExtendedType) {
394 return baseTypeDefForExtendedType(baseTypeDef);
402 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
404 * The path of <code>leafrefType</code> is followed to find referenced node
405 * and its <code>Type</code> is returned.
408 * leafref type definition for which is the type sought
409 * @return JAVA <code>Type</code> of data schema node which is referenced in
410 * <code>leafrefType</code>
411 * @throws IllegalArgumentException
413 * <li>if <code>leafrefType</code> equal null</li>
414 * <li>if path statement of <code>leafrefType</code> equal null</li>
418 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
419 Type returnType = null;
420 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
422 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
423 "The Path Statement for Leafref Type Definition cannot be NULL!");
425 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
426 final String strXPath = xpath.toString();
428 if (strXPath != null) {
429 if (strXPath.indexOf('[') == -1) {
430 final Module module = findParentModule(schemaContext, parentNode);
431 if (module != null) {
432 final SchemaNode dataNode;
433 if (xpath.isAbsolute()) {
434 dataNode = findDataSchemaNode(schemaContext, module, xpath);
436 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
439 if (leafContainsEnumDefinition(dataNode)) {
440 returnType = referencedTypes.get(dataNode.getPath());
441 } else if (leafListContainsEnumDefinition(dataNode)) {
442 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
444 returnType = resolveTypeFromDataSchemaNode(dataNode);
448 returnType = Types.typeForClass(Object.class);
451 if (returnType == null) {
452 throw new IllegalArgumentException("Failed to find leafref target: " + strXPath);
458 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
459 * so then checks if it is of type <code>EnumTypeDefinition</code>.
462 * data schema node for which is checked if it is leaf and if it
464 * @return boolean value
466 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
467 * <li>false - other cases</li>
470 private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
471 if (dataNode instanceof LeafSchemaNode) {
472 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
473 if (leaf.getType() instanceof EnumTypeDefinition) {
481 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
482 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
485 * data schema node for which is checked if it is leaflist and if
487 * @return boolean value
489 * <li>true - if <code>dataNode</code> is leaflist of type
491 * <li>false - other cases</li>
494 private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
495 if (dataNode instanceof LeafListSchemaNode) {
496 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
497 if (leafList.getType() instanceof EnumTypeDefinition) {
505 * Converts <code>enumTypeDef</code> to
506 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
510 * enumeration type definition which is converted to enumeration
512 * string with name which is used as the enumeration name
513 * @return enumeration type which is built with data (name, enum values)
514 * from <code>enumTypeDef</code>
515 * @throws IllegalArgumentException
517 * <li>if <code>enumTypeDef</code> equals null</li>
518 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
519 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
520 * <li>if name of <code>enumTypeDef</code> equal null</li>
523 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
524 final SchemaNode parentNode) {
525 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
526 Preconditions.checkArgument(enumTypeDef.getValues() != null,
527 "EnumTypeDefinition MUST contain at least ONE value definition!");
528 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
529 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
530 "Local Name in EnumTypeDefinition QName cannot be NULL!");
532 final String enumerationName = BindingMapping.getClassName(enumName);
534 Module module = findParentModule(schemaContext, parentNode);
535 final String basePackageName = moduleNamespaceToPackageName(module);
537 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
538 enumBuilder.setDescription(enumTypeDef.getDescription());
539 enumBuilder.setReference(enumTypeDef.getReference());
540 enumBuilder.setModuleName(module.getName());
541 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
542 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
543 return enumBuilder.toInstance(null);
547 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
548 * taken from <code>enumTypeDef</code>.
551 * enumeration type definition is source of enumeration data for
552 * <code>typeBuilder</code>
554 * string with the name of enumeration
556 * generated type builder to which is enumeration added
557 * @return enumeration type which contains enumeration data form
558 * <code>enumTypeDef</code>
559 * @throws IllegalArgumentException
561 * <li>if <code>enumTypeDef</code> equals null</li>
562 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
563 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
564 * <li>if name of <code>enumTypeDef</code> equal null</li>
565 * <li>if name of <code>typeBuilder</code> equal null</li>
569 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
570 final GeneratedTypeBuilderBase<?> typeBuilder) {
571 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
572 Preconditions.checkArgument(enumTypeDef.getValues() != null,
573 "EnumTypeDefinition MUST contain at least ONE value definition!");
574 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
575 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
576 "Local Name in EnumTypeDefinition QName cannot be NULL!");
577 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
579 final String enumerationName = BindingMapping.getClassName(enumName);
581 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
582 enumBuilder.setDescription(enumTypeDef.getDescription());
583 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
584 return enumBuilder.toInstance(enumBuilder);
588 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
591 * contains information about YANG type
592 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
594 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
595 Type returnType = null;
596 if (dataNode != null) {
597 if (dataNode instanceof LeafSchemaNode) {
598 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
599 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
600 } else if (dataNode instanceof LeafListSchemaNode) {
601 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
602 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
609 * Passes through all modules and through all its type definitions and
610 * convert it to generated types.
612 * The modules are firstly sorted by mutual dependencies. The modules are
613 * sequentially passed. All type definitions of a module are at the
614 * beginning sorted so that type definition with less amount of references
615 * to other type definition are processed first.<br />
616 * For each module is created mapping record in the map
617 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
618 * which map current module name to the map which maps type names to
619 * returned types (generated types).
622 private void resolveTypeDefsFromContext() {
623 final Set<Module> modules = schemaContext.getModules();
624 Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
625 final Module[] modulesArray = new Module[modules.size()];
627 for (Module modul : modules) {
628 modulesArray[i++] = modul;
630 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
633 for (final Module module : modulesSortedByDependency) {
634 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
635 if (dateTypeMap == null) {
636 dateTypeMap = new HashMap<>();
638 final Map<String, Type> typeMap = new HashMap<>();
639 dateTypeMap.put(module.getRevision(), typeMap);
640 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
643 for (final Module module : modulesSortedByDependency) {
644 if (module == null) {
647 final String basePackageName = moduleNamespaceToPackageName(module);
649 final DataNodeIterator it = new DataNodeIterator(module);
650 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
651 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
653 if ((listTypeDefinitions != null) && (basePackageName != null)) {
654 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
655 typedefToGeneratedType(basePackageName, module, typedef);
663 * @param basePackageName
664 * string with name of package to which the module belongs
666 * string with the name of the module for to which the
667 * <code>typedef</code> belongs
669 * type definition of the node for which should be creted JAVA
670 * <code>Type</code> (usually generated TO)
671 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
672 * <code>null</code> value if <code>basePackageName</code> or
673 * <code>modulName</code> or <code>typedef</code> or Q name of
674 * <code>typedef</code> equals <code>null</code>
676 private Type typedefToGeneratedType(final String basePackageName, final Module module,
677 final TypeDefinition<?> typedef) {
678 final String moduleName = module.getName();
679 final Date moduleRevision = module.getRevision();
680 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
681 final String typedefName = typedef.getQName().getLocalName();
682 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
683 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
684 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
685 Type returnType = null;
686 if (innerTypeDefinition instanceof ExtendedType) {
687 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
688 returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName,
690 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
691 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
692 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
693 genTOBuilder.setTypedef(true);
694 genTOBuilder.setIsUnion(true);
695 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
696 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
697 returnType = genTOBuilder.toInstance();
699 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
700 genTOBuilder.getName() + "Builder");
701 unionBuilder.setIsUnionBuilder(true);
702 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
703 method.setReturnType(returnType);
704 method.addParameter(Types.STRING, "defaultValue");
705 method.setAccessModifier(AccessModifier.PUBLIC);
706 method.setStatic(true);
707 Set<Type> types = additionalTypes.get(module);
709 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
710 additionalTypes.put(module, types);
712 types.add(unionBuilder.toInstance());
714 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
715 // enums are automatically Serializable
716 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
717 // TODO units for typedef enum
718 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
719 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
720 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
721 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
722 basePackageName, bitsTypeDefinition, typedefName, module.getName());
723 genTOBuilder.setTypedef(true);
724 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
725 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
726 returnType = genTOBuilder.toInstance();
728 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
729 innerTypeDefinition, typedef);
730 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
732 if (returnType != null) {
733 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
734 final Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
735 if (typeMap != null) {
736 typeMap.put(typedefName, returnType);
746 * Wraps base YANG type to generated TO.
748 * @param basePackageName
749 * string with name of package to which the module belongs
751 * type definition which is converted to the TO
753 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
754 * @return generated transfer object which represent<code>javaType</code>
756 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
757 final Type javaType, final String moduleName) {
758 Preconditions.checkNotNull(javaType, "javaType cannot be null");
759 final String propertyName = "value";
761 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
762 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
763 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
764 genPropBuilder.setReturnType(javaType);
765 genTOBuilder.addEqualsIdentity(genPropBuilder);
766 genTOBuilder.addHashIdentity(genPropBuilder);
767 genTOBuilder.addToStringProperty(genPropBuilder);
768 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef instanceof ExtendedType) {
769 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
770 addStringRegExAsConstant(genTOBuilder, regExps);
772 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
773 genTOBuilder.setTypedef(true);
774 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
775 return genTOBuilder.toInstance();
779 * Converts output list of generated TO builders to one TO builder (first
780 * from list) which contains the remaining builders as its enclosing TO.
782 * @param basePackageName
783 * string with name of package to which the module belongs
785 * type definition which should be of type
786 * <code>UnionTypeDefinition</code>
788 * string with name for generated TO
789 * @return generated TO builder with the list of enclosed generated TO
792 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
793 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
794 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
795 typedef, typeDefName, parentNode);
796 GeneratedTOBuilder resultTOBuilder = null;
797 if (genTOBuilders.isEmpty()) {
798 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typedef);
801 resultTOBuilder = genTOBuilders.remove(0);
802 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
803 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
806 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
807 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
808 resultTOBuilder.addEqualsIdentity(genPropBuilder);
809 resultTOBuilder.addHashIdentity(genPropBuilder);
810 resultTOBuilder.addToStringProperty(genPropBuilder);
812 return resultTOBuilder;
816 * Converts <code>typedef</code> to generated TO with
817 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
818 * added to generated TO builder as property.
820 * @param basePackageName
821 * string with name of package to which the module belongs
823 * type definition which should be of type
824 * <code>UnionTypeDefinition</code>
826 * string with name for generated TO
827 * @return generated TO builder which represents <code>typedef</code>
828 * @throws NullPointerException
830 * <li>if <code>basePackageName</code> is null</li>
831 * <li>if <code>typedef</code> is null</li>
832 * <li>if Qname of <code>typedef</code> is null</li>
835 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
836 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
837 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
838 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
839 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
841 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
842 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
843 final Module module = findParentModule(schemaContext, parentNode);
845 final GeneratedTOBuilderImpl unionGenTOBuilder;
846 if (typeDefName != null && !typeDefName.isEmpty()) {
847 final String typeName = BindingMapping.getClassName(typeDefName);
848 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
849 unionGenTOBuilder.setDescription(typedef.getDescription());
850 unionGenTOBuilder.setReference(typedef.getReference());
851 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
852 unionGenTOBuilder.setModuleName(module.getName());
854 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
857 generatedTOBuilders.add(unionGenTOBuilder);
858 unionGenTOBuilder.setIsUnion(true);
859 final List<String> regularExpressions = new ArrayList<String>();
860 for (final TypeDefinition<?> unionType : unionTypes) {
861 final String unionTypeName = unionType.getQName().getLocalName();
862 if (unionType instanceof UnionType) {
863 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
864 basePackageName, parentNode));
865 } else if (unionType instanceof ExtendedType) {
866 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, regularExpressions,
868 } else if (unionType instanceof EnumTypeDefinition) {
869 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
870 unionTypeName, unionGenTOBuilder);
871 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
873 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
875 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
878 if (!regularExpressions.isEmpty()) {
879 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
882 storeGenTO(typedef, unionGenTOBuilder, parentNode);
884 return generatedTOBuilders;
888 * Wraps code which handle case when union subtype is also of the type
889 * <code>UnionType</code>.
891 * In this case the new generated TO is created for union subtype (recursive
893 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
894 * String, SchemaNode)}
895 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
896 * <code>parentUnionGenTOBuilder</code> is created property which type is
897 * equal to new generated TO.
899 * @param parentUnionGenTOBuilder
900 * generated TO builder to which is the property with the child
901 * union subtype added
902 * @param basePackageName
903 * string with the name of the module package
904 * @param unionSubtype
905 * type definition which represents union subtype
906 * @return list of generated TO builders. The number of the builders can be
907 * bigger one due to recursive call of
908 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
910 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
911 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
912 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
913 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
914 basePackageName, unionSubtype, newTOBuilderName, parentNode);
916 final GeneratedPropertyBuilder propertyBuilder;
917 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
918 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
919 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
920 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
922 return subUnionGenTOBUilders;
926 * Wraps code which handle case when union subtype is of the type
927 * <code>ExtendedType</code>.
929 * If TO for this type already exists it is used for the creation of the
930 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
931 * type is used for the property creation.
933 * @param parentUnionGenTOBuilder
934 * generated TO builder in which new property is created
935 * @param unionSubtype
936 * type definition of the <code>ExtendedType</code> type which
937 * represents union subtype
938 * @param regularExpressions
939 * list of strings with the regular expressions
941 * parent Schema Node for Extended Subtype
944 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
945 final ExtendedType unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
946 final String unionTypeName = unionSubtype.getQName().getLocalName();
947 final Type genTO = findGenTO(unionTypeName, unionSubtype);
949 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
951 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
952 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
953 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
955 if (javaType != null) {
956 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
959 if (baseType instanceof StringType) {
960 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
966 * Searches for generated TO for <code>searchedTypeDef</code> type
967 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
969 * @param searchedTypeName
970 * string with name of <code>searchedTypeDef</code>
971 * @return generated TO for <code>searchedTypeDef</code> or
972 * <code>null</code> it it doesn't exist
974 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
975 final Module typeModule = findParentModule(schemaContext, parentNode);
976 if (typeModule != null && typeModule.getName() != null) {
977 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
978 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
979 if (genTOs != null) {
980 return genTOs.get(searchedTypeName);
987 * Stores generated TO created from <code>genTOBuilder</code> for
988 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
989 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
992 * type definition for which is <code>genTOBuilder</code> created
993 * @param genTOBuilder
994 * generated TO builder which is converted to generated TO and
997 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
998 final SchemaNode parentNode) {
999 if (!(newTypeDef instanceof UnionType)) {
1001 final Module parentModule = findParentModule(schemaContext, parentNode);
1002 if (parentModule != null && parentModule.getName() != null) {
1003 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1004 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1005 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1011 * Adds a new property with the name <code>propertyName</code> and with type
1012 * <code>type</code> to <code>unonGenTransObject</code>.
1014 * @param unionGenTransObject
1015 * generated TO to which should be property added
1017 * JAVA <code>type</code> of the property which should be added
1018 * to <code>unionGentransObject</code>
1019 * @param propertyName
1020 * string with name of property which should be added to
1021 * <code>unionGentransObject</code>
1023 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1024 final String propertyName) {
1025 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1026 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1027 .addProperty(BindingMapping.getPropertyName(propertyName));
1028 propBuilder.setReturnType(type);
1030 unionGenTransObject.addEqualsIdentity(propBuilder);
1031 unionGenTransObject.addHashIdentity(propBuilder);
1032 unionGenTransObject.addToStringProperty(propBuilder);
1037 * Converts <code>typedef</code> to the generated TO builder.
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 * @return generated TO builder which contains data from
1044 * <code>typedef</code> and <code>basePackageName</code>
1046 private GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName,
1047 final TypeDefinition<?> typedef, final String moduleName) {
1049 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
1050 final String typeDefTOName = typedef.getQName().getLocalName();
1052 if ((packageName != null) && (typeDefTOName != null)) {
1053 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1054 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1056 newType.setDescription(typedef.getDescription());
1057 newType.setReference(typedef.getReference());
1058 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1059 newType.setModuleName(moduleName);
1067 * Converts <code>typeDef</code> which should be of the type
1068 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1070 * All the bits of the typeDef are added to returning generated TO as
1073 * @param basePackageName
1074 * string with name of package to which the module belongs
1076 * type definition from which is the generated TO builder created
1077 * @param typeDefName
1078 * string with the name for generated TO builder
1079 * @return generated TO builder which represents <code>typeDef</code>
1080 * @throws IllegalArgumentException
1082 * <li>if <code>typeDef</code> equals null</li>
1083 * <li>if <code>basePackageName</code> equals null</li>
1086 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1087 final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1089 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1090 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1092 if (typeDef instanceof BitsTypeDefinition) {
1093 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1095 final String typeName = BindingMapping.getClassName(typeDefName);
1096 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1098 genTOBuilder.setDescription(typeDef.getDescription());
1099 genTOBuilder.setReference(typeDef.getReference());
1100 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1101 genTOBuilder.setModuleName(moduleName);
1102 genTOBuilder.setBaseType(typeDef);
1104 final List<Bit> bitList = bitsTypeDefinition.getBits();
1105 GeneratedPropertyBuilder genPropertyBuilder;
1106 for (final Bit bit : bitList) {
1107 String name = bit.getName();
1108 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1109 genPropertyBuilder.setReadOnly(true);
1110 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1112 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1113 genTOBuilder.addHashIdentity(genPropertyBuilder);
1114 genTOBuilder.addToStringProperty(genPropertyBuilder);
1117 return genTOBuilder;
1123 * Converts the pattern constraints from <code>typedef</code> to the list of
1124 * the strings which represents these constraints.
1127 * extended type in which are the pattern constraints sought
1128 * @return list of strings which represents the constraint patterns
1129 * @throws IllegalArgumentException
1130 * if <code>typedef</code> equals null
1133 private List<String> resolveRegExpressionsFromTypedef(final ExtendedType typedef) {
1134 final List<String> regExps = new ArrayList<String>();
1135 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1136 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1137 if (strTypeDef instanceof StringType) {
1138 final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1139 if (!patternConstraints.isEmpty()) {
1141 String modifiedRegEx;
1142 for (PatternConstraint patternConstraint : patternConstraints) {
1143 regEx = patternConstraint.getRegularExpression();
1144 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1145 regExps.add(modifiedRegEx);
1154 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1155 * expressions from the <code>regularExpressions</code>
1157 * @param genTOBuilder
1158 * generated TO builder to which are
1159 * <code>regular expressions</code> added
1160 * @param regularExpressions
1161 * list of string which represent regular expressions
1162 * @throws IllegalArgumentException
1164 * <li>if <code>genTOBuilder</code> equals null</li>
1165 * <li>if <code>regularExpressions</code> equals null</li>
1168 private void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1169 if (genTOBuilder == null) {
1170 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1172 if (regularExpressions == null) {
1173 throw new IllegalArgumentException("List of regular expressions can't be null");
1175 if (!regularExpressions.isEmpty()) {
1176 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1177 regularExpressions);
1182 * Creates generated TO with data about inner extended type
1183 * <code>innerExtendedType</code>, about the package name
1184 * <code>typedefName</code> and about the generated TO name
1185 * <code>typedefName</code>.
1187 * It is supposed that <code>innerExtendedType</code> is already present in
1188 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1189 * be possible set it as extended type for the returning generated TO.
1193 * @param innerExtendedType
1194 * extended type which is part of some other extended type
1195 * @param basePackageName
1196 * string with the package name of the module
1199 * @return generated TO which extends generated TO for
1200 * <code>innerExtendedType</code>
1201 * @throws IllegalArgumentException
1203 * <li>if <code>extendedType</code> equals null</li>
1204 * <li>if <code>basePackageName</code> equals null</li>
1205 * <li>if <code>typedefName</code> equals null</li>
1208 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1209 final ExtendedType innerExtendedType, final String basePackageName, final String moduleName) {
1210 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1211 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1213 final String typedefName = typedef.getQName().getLocalName();
1214 final String classTypedefName = BindingMapping.getClassName(typedefName);
1215 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1216 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1218 genTOBuilder.setDescription(typedef.getDescription());
1219 genTOBuilder.setReference(typedef.getReference());
1220 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1221 genTOBuilder.setModuleName(moduleName);
1222 genTOBuilder.setTypedef(true);
1223 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1224 genTOBuilder.setRestrictions(r);
1226 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1227 genTOBuilder.setIsUnion(true);
1230 Map<Date, Map<String, Type>> modulesByDate = null;
1231 Map<String, Type> typeMap = null;
1232 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1233 if (parentModule != null) {
1234 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1235 typeMap = modulesByDate.get(parentModule.getRevision());
1238 if (typeMap != null) {
1239 Type type = typeMap.get(innerTypeDef);
1240 if (type instanceof GeneratedTransferObject) {
1241 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1244 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1245 makeSerializable(genTOBuilder);
1247 return genTOBuilder.toInstance();
1251 * Add {@link Serializable} to implemented interfaces of this TO. Also
1252 * compute and add serialVersionUID property.
1255 * transfer object which needs to be serializable
1257 private void makeSerializable(final GeneratedTOBuilderImpl gto) {
1258 gto.addImplementsType(Types.typeForClass(Serializable.class));
1259 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1260 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1265 * Finds out for each type definition how many immersion (depth) is
1266 * necessary to get to the base type. Every type definition is inserted to
1267 * the map which key is depth and value is list of type definitions with
1268 * equal depth. In next step are lists from this map concatenated to one
1269 * list in ascending order according to their depth. All type definitions
1270 * are in the list behind all type definitions on which depends.
1272 * @param unsortedTypeDefinitions
1273 * list of type definitions which should be sorted by depth
1274 * @return list of type definitions sorted according their each other
1275 * dependencies (type definitions which are depend on other type
1276 * definitions are in list behind them).
1278 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1279 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1280 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1282 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1283 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1284 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1285 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1286 if (typeDefinitionsConcreteDepth == null) {
1287 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1288 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1290 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1293 // SortedMap guarantees order corresponding to keys in ascending order
1294 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1295 sortedTypeDefinition.addAll(v);
1298 return sortedTypeDefinition;
1302 * Returns how many immersion is necessary to get from the type definition
1305 * @param typeDefinition
1306 * type definition for which is depth sought.
1307 * @return number of immersions which are necessary to get from the type
1308 * definition to the base type
1310 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1311 if (typeDefinition == null) {
1315 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1317 if (baseType instanceof ExtendedType) {
1318 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1319 } else if (baseType instanceof UnionType) {
1320 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1321 int maxChildDepth = 0;
1323 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1324 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1325 if (childDepth > maxChildDepth) {
1326 maxChildDepth = childDepth;
1329 return maxChildDepth;
1335 * Returns string which contains the same value as <code>name</code> but
1336 * integer suffix is incremented by one. If <code>name</code> contains no
1337 * number suffix then number 1 is added.
1340 * string with name of augmented node
1341 * @return string with the number suffix incremented by one (or 1 is added)
1343 private String provideAvailableNameForGenTOBuilder(final String name) {
1344 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1346 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1347 return name.substring(0, mtch.start()) + newSuffix;
1353 public void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1354 if (units != null && !units.isEmpty()) {
1355 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1356 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1357 prop.setReturnType(Types.STRING);
1358 to.addToStringProperty(prop);
1363 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1364 return getTypeDefaultConstruction(node, node.getDefault());
1367 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1368 TypeDefinition<?> type = node.getType();
1369 QName typeQName = type.getQName();
1370 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1371 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of " + node);
1372 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of "
1375 StringBuilder sb = new StringBuilder();
1376 String result = null;
1377 if (base instanceof BinaryTypeDefinition) {
1378 result = binaryToDef(defaultValue);
1379 } else if (base instanceof BitsTypeDefinition) {
1382 Module parent = getParentModule(node);
1383 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1385 if (!(path.hasNext())) {
1386 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1387 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1388 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1390 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1391 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1392 parentName = BindingMapping.getClassName(parent.getName());
1393 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1395 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1396 } else if (base instanceof BooleanTypeDefinition) {
1397 result = typeToDef(Boolean.class, defaultValue);
1398 } else if (base instanceof DecimalTypeDefinition) {
1399 result = typeToDef(BigDecimal.class, defaultValue);
1400 } else if (base instanceof EmptyTypeDefinition) {
1401 result = typeToDef(Boolean.class, defaultValue);
1402 } else if (base instanceof EnumTypeDefinition) {
1403 char[] defValArray = defaultValue.toCharArray();
1404 char first = Character.toUpperCase(defaultValue.charAt(0));
1405 defValArray[0] = first;
1406 String newDefVal = new String(defValArray);
1408 if (type instanceof ExtendedType) {
1409 Module m = getParentModule(type);
1410 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1411 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1412 className = packageName + "." + BindingMapping.getClassName(typeQName);
1414 Module parentModule = getParentModule(node);
1415 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1416 String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
1417 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1419 result = className + "." + newDefVal;
1420 } else if (base instanceof IdentityrefTypeDefinition) {
1421 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1422 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1423 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1424 } else if (base instanceof Int8) {
1425 result = typeToDef(Byte.class, defaultValue);
1426 } else if (base instanceof Int16) {
1427 result = typeToDef(Short.class, defaultValue);
1428 } else if (base instanceof Int32) {
1429 result = typeToDef(Integer.class, defaultValue);
1430 } else if (base instanceof Int64) {
1431 result = typeToDef(Long.class, defaultValue);
1432 } else if (base instanceof LeafrefTypeDefinition) {
1433 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1434 } else if (base instanceof StringTypeDefinition) {
1435 result = "\"" + defaultValue + "\"";
1436 } else if (base instanceof Uint8) {
1437 result = typeToDef(Short.class, defaultValue);
1438 } else if (base instanceof Uint16) {
1439 result = typeToDef(Integer.class, defaultValue);
1440 } else if (base instanceof Uint32) {
1441 result = typeToDef(Long.class, defaultValue);
1442 } else if (base instanceof Uint64) {
1443 result = typeToDef(BigInteger.class, defaultValue);
1444 } else if (base instanceof UnionTypeDefinition) {
1445 result = unionToDef(node);
1451 if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
1452 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
1453 Module m = getParentModule(type);
1454 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1455 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1456 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1457 sb.insert(0, "new " + className + "(");
1458 sb.insert(sb.length(), ')');
1461 return sb.toString();
1464 private String typeToDef(final Class<?> clazz, final String defaultValue) {
1465 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1468 private String binaryToDef(final String defaultValue) {
1469 StringBuilder sb = new StringBuilder();
1470 BaseEncoding en = BaseEncoding.base64();
1471 byte[] encoded = en.decode(defaultValue);
1472 sb.append("new byte[] {");
1473 for (int i = 0; i < encoded.length; i++) {
1474 sb.append(encoded[i]);
1475 if (i != encoded.length - 1) {
1480 return sb.toString();
1483 private String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1484 final boolean isExt) {
1485 List<Bit> bits = new ArrayList<>(type.getBits());
1486 Collections.sort(bits, new Comparator<Bit>() {
1488 public int compare(final Bit o1, final Bit o2) {
1489 return o1.getName().compareTo(o2.getName());
1492 StringBuilder sb = new StringBuilder();
1495 sb.append(className);
1498 for (int i = 0; i < bits.size(); i++) {
1499 if (bits.get(i).getName().equals(defaultValue)) {
1504 if (i != bits.size() - 1) {
1511 return sb.toString();
1514 private Module getParentModule(final SchemaNode node) {
1515 QName qname = node.getPath().getPathFromRoot().iterator().next();
1516 URI namespace = qname.getNamespace();
1517 Date revision = qname.getRevision();
1518 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1521 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1522 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1523 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1524 "The Path Statement for Leafref Type Definition cannot be NULL!");
1526 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1527 final String strXPath = xpath.toString();
1529 if (strXPath != null) {
1530 if (strXPath.indexOf('[') == -1) {
1531 final Module module = findParentModule(schemaContext, parentNode);
1532 if (module != null) {
1533 final SchemaNode dataNode;
1534 if (xpath.isAbsolute()) {
1535 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1537 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1539 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1543 return "new java.lang.Object()";
1550 private String unionToDef(final LeafSchemaNode node) {
1554 if (node.getType() instanceof ExtendedType) {
1555 ExtendedType type = (ExtendedType) node.getType();
1556 QName typeQName = type.getQName();
1557 Module module = null;
1558 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1559 if (modules.size() > 1) {
1560 for (Module m : modules) {
1561 if (m.getRevision().equals(typeQName.getRevision())) {
1566 if (module == null) {
1567 List<Module> modulesList = new ArrayList<>(modules);
1568 Collections.sort(modulesList, new Comparator<Module>() {
1570 public int compare(final Module o1, final Module o2) {
1571 return o1.getRevision().compareTo(o2.getRevision());
1574 module = modulesList.get(0);
1577 module = modules.iterator().next();
1580 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
1581 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1583 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1584 QName first = path.next();
1585 if (!(path.hasNext())) {
1586 URI namespace = first.getNamespace();
1587 Date revision = first.getRevision();
1588 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1589 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1590 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1591 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1593 URI namespace = first.getNamespace();
1594 Date revision = first.getRevision();
1595 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1596 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1597 String packageName = packageNameForGeneratedType(basePackageName, node.getType().getPath());
1598 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1601 return union(className, node.getDefault(), node);
1604 private String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1605 StringBuilder sb = new StringBuilder();
1607 sb.append(className);
1609 sb.append(defaultValue);
1610 sb.append("\".toCharArray())");
1611 return sb.toString();
1615 public String getConstructorPropertyName(final SchemaNode node) {
1616 if (node instanceof TypeDefinition<?>) {
1624 public String getParamNameFromType(final TypeDefinition<?> type) {
1625 return BindingMapping.getPropertyName(type.getQName().getLocalName());