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.packageNameForGeneratedType;
11 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
12 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Sets;
16 import com.google.common.io.BaseEncoding;
17 import java.io.Serializable;
18 import java.math.BigDecimal;
19 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.Comparator;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
31 import java.util.TreeMap;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34 import org.apache.commons.lang3.StringEscapeUtils;
35 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
36 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
37 import org.opendaylight.yangtools.binding.generator.util.Types;
38 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
39 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
40 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
41 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
42 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
43 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
44 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
45 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty;
46 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
47 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
48 import org.opendaylight.yangtools.sal.binding.model.api.Type;
49 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
50 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
51 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
53 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
54 import org.opendaylight.yangtools.yang.binding.BindingMapping;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
57 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
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.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.RevisionAwareXPathImpl;
87 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
88 import org.opendaylight.yangtools.yang.model.util.StringType;
89 import org.opendaylight.yangtools.yang.model.util.Uint16;
90 import org.opendaylight.yangtools.yang.model.util.Uint32;
91 import org.opendaylight.yangtools.yang.model.util.Uint64;
92 import org.opendaylight.yangtools.yang.model.util.Uint8;
93 import org.opendaylight.yangtools.yang.model.util.UnionType;
94 import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
96 public final class TypeProviderImpl implements TypeProvider {
97 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
100 * Contains the schema data red from YANG files.
102 private final SchemaContext schemaContext;
105 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
107 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
110 * The map which maps schema paths to JAVA <code>Type</code>.
112 private final Map<SchemaPath, Type> referencedTypes;
113 private final Map<Module, Set<Type>> additionalTypes;
116 * Creates new instance of class <code>TypeProviderImpl</code>.
118 * @param schemaContext
119 * contains the schema data red from YANG files
120 * @throws IllegalArgumentException
121 * if <code>schemaContext</code> equal null.
123 public TypeProviderImpl(final SchemaContext schemaContext) {
124 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
126 this.schemaContext = schemaContext;
127 this.genTypeDefsContextMap = new HashMap<>();
128 this.referencedTypes = new HashMap<>();
129 this.additionalTypes = new HashMap<>();
130 resolveTypeDefsFromContext();
134 * Puts <code>refType</code> to map with key <code>refTypePath</code>
137 * schema path used as the map key
139 * type which represents the map value
140 * @throws IllegalArgumentException
142 * <li>if <code>refTypePath</code> equal null</li>
143 * <li>if <code>refType</code> equal null</li>
147 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
148 Preconditions.checkArgument(refTypePath != null,
149 "Path reference of Enumeration Type Definition cannot be NULL!");
150 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
151 referencedTypes.put(refTypePath, refType);
154 public Map<Module, Set<Type>> getAdditionalTypes() {
155 return additionalTypes;
160 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
163 * string with YANG name of type
164 * @return JAVA <code>Type</code> for YANG type <code>type</code>
165 * @see TypeProvider#javaTypeForYangType(String)
169 public Type javaTypeForYangType(final String type) {
170 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
174 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
175 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
179 * Converts schema definition type <code>typeDefinition</code> to JAVA
182 * @param typeDefinition
183 * type definition which is converted to JAVA type
184 * @throws IllegalArgumentException
186 * <li>if <code>typeDefinition</code> equal null</li>
187 * <li>if Qname of <code>typeDefinition</code> equal null</li>
188 * <li>if name of <code>typeDefinition</code> equal null</li>
192 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
193 final Restrictions r) {
195 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
196 Preconditions.checkArgument(typeDefinition.getQName() != null,
197 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
198 String typedefName = typeDefinition.getQName().getLocalName();
199 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
201 if (typeDefinition instanceof ExtendedType) {
202 returnType = javaTypeForExtendedType(typeDefinition);
203 if (r != null && returnType instanceof GeneratedTransferObject) {
204 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
205 Module module = findParentModule(schemaContext, parentNode);
206 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
207 String packageName = packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
208 String genTOName = BindingMapping.getClassName(typedefName);
209 String name = packageName + "." + genTOName;
210 if (!(returnType.getFullyQualifiedName().equals(name))) {
211 returnType = shadedTOWithRestrictions(gto, r);
215 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
216 if (returnType == null) {
217 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
224 private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
225 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
226 GeneratedTransferObject parent = gto.getSuperType();
227 if (parent != null) {
228 gtob.setExtendsType(parent);
230 gtob.setRestrictions(r);
231 for (GeneratedProperty gp : gto.getProperties()) {
232 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
233 gpb.setValue(gp.getValue());
234 gpb.setReadOnly(gp.isReadOnly());
235 gpb.setAccessModifier(gp.getAccessModifier());
236 gpb.setReturnType(gp.getReturnType());
237 gpb.setFinal(gp.isFinal());
238 gpb.setStatic(gp.isStatic());
240 return gtob.toInstance();
243 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
244 final SchemaNode leafRefValueNode;
245 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
246 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
247 .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute());
249 ///// skip leafrefs in augments - they're checked once augments are resolved
250 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
251 boolean isAugmenting = false;
252 DataNodeContainer current = null;
253 DataSchemaNode dataChildByName;
255 while (iterator.hasNext() && !isAugmenting) {
256 final QName next = iterator.next();
257 if (current == null) {
258 dataChildByName = schemaContext.getDataChildByName(next);
260 dataChildByName = current.getDataChildByName(next);
262 if (dataChildByName != null) {
263 isAugmenting = dataChildByName.isAugmenting();
267 if (dataChildByName instanceof DataNodeContainer) {
268 current = (DataNodeContainer) dataChildByName;
276 Module parentModule = getParentModule(parentNode);
277 if (!leafRefStrippedXPath.isAbsolute()) {
278 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
279 parentNode, leafRefStrippedXPath);
281 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
283 return (leafRefValueNode != null) ? leafRefValueNode.equals(parentNode) : false;
287 * Returns JAVA <code>Type</code> for instances of the type
288 * <code>LeafrefTypeDefinition</code> or
289 * <code>IdentityrefTypeDefinition</code>.
291 * @param typeDefinition
292 * type definition which is converted to JAVA <code>Type</code>
293 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
295 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
296 if (typeDefinition instanceof LeafrefTypeDefinition) {
297 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
298 if (isLeafRefSelfReference(leafref, parentNode)) {
299 throw new YangValidationException("Leafref " + leafref.toString() + " is referencing itself, incoming" +
300 " StackOverFlowError detected.");
302 return provideTypeForLeafref(leafref, parentNode);
303 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
304 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
305 return provideTypeForIdentityref(idref);
312 * Returns JAVA <code>Type</code> for instances of the type
313 * <code>ExtendedType</code>.
315 * @param typeDefinition
316 * type definition which is converted to JAVA <code>Type</code>
317 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
319 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
320 final String typedefName = typeDefinition.getQName().getLocalName();
321 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
322 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
323 if (returnType == null) {
324 if (baseTypeDef instanceof EnumTypeDefinition) {
325 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
326 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
328 final Module module = findParentModule(schemaContext, typeDefinition);
329 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
330 if (module != null) {
331 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
332 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
333 if (genTOs != null) {
334 returnType = genTOs.get(typedefName);
336 if (returnType == null) {
337 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
338 baseTypeDef, typeDefinition, r);
347 * Seeks for identity reference <code>idref</code> the JAVA
348 * <code>type</code>.<br />
352 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
353 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
356 * identityref type definition for which JAVA <code>Type</code>
358 * @return JAVA <code>Type</code> of the identity which is refrenced through
361 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
362 QName baseIdQName = idref.getIdentity().getQName();
363 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
364 baseIdQName.getRevision());
365 IdentitySchemaNode identity = null;
366 for (IdentitySchemaNode id : module.getIdentities()) {
367 if (id.getQName().equals(baseIdQName)) {
371 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
373 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
374 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
375 final String genTypeName = BindingMapping.getClassName(identity.getQName());
377 Type baseType = Types.typeForClass(Class.class);
378 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
379 return Types.parameterizedTypeFor(baseType, paramType);
383 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
385 * @param typeDefinition
386 * type definition which should be converted to JAVA
388 * @return JAVA <code>Type</code> which represents
389 * <code>typeDefinition</code>
390 * @throws IllegalArgumentException
392 * <li>if <code>typeDefinition</code> equal null</li>
393 * <li>if Q name of <code>typeDefinition</code></li>
394 * <li>if name of <code>typeDefinition</code></li>
397 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
398 final SchemaNode parentNode) {
399 Type returnType = null;
400 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
401 if (typeDefinition.getQName() == null) {
402 throw new IllegalArgumentException(
403 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
405 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
406 "Type Definitions Local Name cannot be NULL!");
408 final String typedefName = typeDefinition.getQName().getLocalName();
409 if (typeDefinition instanceof ExtendedType) {
410 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
412 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
413 final Module module = findParentModule(schemaContext, parentNode);
415 if (module != null) {
416 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
417 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
418 if (genTOs != null) {
419 returnType = genTOs.get(typedefName);
428 * Gets base type definition for <code>extendTypeDef</code>. The method is
429 * recursivelly called until non <code>ExtendedType</code> type is found.
431 * @param extendTypeDef
432 * type definition for which is the base type definition sought
433 * @return type definition which is base type for <code>extendTypeDef</code>
434 * @throws IllegalArgumentException
435 * if <code>extendTypeDef</code> equal null
437 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
438 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
439 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
440 if (baseTypeDef == null) {
441 return extendTypeDef;
442 } else if (baseTypeDef instanceof ExtendedType) {
443 return baseTypeDefForExtendedType(baseTypeDef);
451 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
453 * The path of <code>leafrefType</code> is followed to find referenced node
454 * and its <code>Type</code> is returned.
457 * leafref type definition for which is the type sought
458 * @return JAVA <code>Type</code> of data schema node which is referenced in
459 * <code>leafrefType</code>
460 * @throws IllegalArgumentException
462 * <li>if <code>leafrefType</code> equal null</li>
463 * <li>if path statement of <code>leafrefType</code> equal null</li>
467 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
468 Type returnType = null;
469 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
471 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
472 "The Path Statement for Leafref Type Definition cannot be NULL!");
474 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
475 final String strXPath = xpath.toString();
477 if (strXPath != null) {
478 if (strXPath.indexOf('[') == -1) {
479 final Module module = findParentModule(schemaContext, parentNode);
480 if (module != null) {
481 final SchemaNode dataNode;
482 if (xpath.isAbsolute()) {
483 dataNode = findDataSchemaNode(schemaContext, module, xpath);
485 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
488 if (leafContainsEnumDefinition(dataNode)) {
489 returnType = referencedTypes.get(dataNode.getPath());
490 } else if (leafListContainsEnumDefinition(dataNode)) {
491 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
493 returnType = resolveTypeFromDataSchemaNode(dataNode);
497 returnType = Types.typeForClass(Object.class);
500 if (returnType == null) {
501 throw new IllegalArgumentException("Failed to find leafref target: " + strXPath);
507 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
508 * so then checks if it is of type <code>EnumTypeDefinition</code>.
511 * data schema node for which is checked if it is leaf and if it
513 * @return boolean value
515 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
516 * <li>false - other cases</li>
519 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
520 if (dataNode instanceof LeafSchemaNode) {
521 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
522 if (leaf.getType() instanceof EnumTypeDefinition) {
530 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
531 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
534 * data schema node for which is checked if it is leaflist and if
536 * @return boolean value
538 * <li>true - if <code>dataNode</code> is leaflist of type
540 * <li>false - other cases</li>
543 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
544 if (dataNode instanceof LeafListSchemaNode) {
545 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
546 if (leafList.getType() instanceof EnumTypeDefinition) {
554 * Converts <code>enumTypeDef</code> to
555 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
559 * enumeration type definition which is converted to enumeration
561 * string with name which is used as the enumeration name
562 * @return enumeration type which is built with data (name, enum values)
563 * from <code>enumTypeDef</code>
564 * @throws IllegalArgumentException
566 * <li>if <code>enumTypeDef</code> equals null</li>
567 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
568 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
569 * <li>if name of <code>enumTypeDef</code> equal null</li>
572 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
573 final SchemaNode parentNode) {
574 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
575 Preconditions.checkArgument(enumTypeDef.getValues() != null,
576 "EnumTypeDefinition MUST contain at least ONE value definition!");
577 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
578 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
579 "Local Name in EnumTypeDefinition QName cannot be NULL!");
581 final String enumerationName = BindingMapping.getClassName(enumName);
583 Module module = findParentModule(schemaContext, parentNode);
584 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
586 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
587 enumBuilder.setDescription(enumTypeDef.getDescription());
588 enumBuilder.setReference(enumTypeDef.getReference());
589 enumBuilder.setModuleName(module.getName());
590 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
591 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
592 return enumBuilder.toInstance(null);
596 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
597 * taken from <code>enumTypeDef</code>.
600 * enumeration type definition is source of enumeration data for
601 * <code>typeBuilder</code>
603 * string with the name of enumeration
605 * generated type builder to which is enumeration added
606 * @return enumeration type which contains enumeration data form
607 * <code>enumTypeDef</code>
608 * @throws IllegalArgumentException
610 * <li>if <code>enumTypeDef</code> equals null</li>
611 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
612 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
613 * <li>if name of <code>enumTypeDef</code> equal null</li>
614 * <li>if name of <code>typeBuilder</code> equal null</li>
618 private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
619 final GeneratedTypeBuilderBase<?> typeBuilder) {
620 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
621 Preconditions.checkArgument(enumTypeDef.getValues() != null,
622 "EnumTypeDefinition MUST contain at least ONE value definition!");
623 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
624 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
625 "Local Name in EnumTypeDefinition QName cannot be NULL!");
626 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
628 final String enumerationName = BindingMapping.getClassName(enumName);
630 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
631 enumBuilder.setDescription(enumTypeDef.getDescription());
632 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
633 return enumBuilder.toInstance(enumBuilder);
637 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
640 * contains information about YANG type
641 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
643 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
644 Type returnType = null;
645 if (dataNode != null) {
646 if (dataNode instanceof LeafSchemaNode) {
647 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
648 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
649 } else if (dataNode instanceof LeafListSchemaNode) {
650 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
651 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
658 * Passes through all modules and through all its type definitions and
659 * convert it to generated types.
661 * The modules are firstly sorted by mutual dependencies. The modules are
662 * sequentially passed. All type definitions of a module are at the
663 * beginning sorted so that type definition with less amount of references
664 * to other type definition are processed first.<br />
665 * For each module is created mapping record in the map
666 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
667 * which map current module name to the map which maps type names to
668 * returned types (generated types).
671 private void resolveTypeDefsFromContext() {
672 final Set<Module> modules = schemaContext.getModules();
673 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
674 final Module[] modulesArray = new Module[modules.size()];
676 for (Module modul : modules) {
677 modulesArray[i++] = modul;
679 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
682 for (final Module module : modulesSortedByDependency) {
683 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
684 if (dateTypeMap == null) {
685 dateTypeMap = new HashMap<>();
687 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
688 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
691 for (final Module module : modulesSortedByDependency) {
692 if (module == null) {
695 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
697 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
698 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
700 if ((listTypeDefinitions != null) && (basePackageName != null)) {
701 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
702 typedefToGeneratedType(basePackageName, module, typedef);
710 * @param basePackageName
711 * string with name of package to which the module belongs
713 * string with the name of the module for to which the
714 * <code>typedef</code> belongs
716 * type definition of the node for which should be creted JAVA
717 * <code>Type</code> (usually generated TO)
718 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
719 * <code>null</code> value if <code>basePackageName</code> or
720 * <code>modulName</code> or <code>typedef</code> or Q name of
721 * <code>typedef</code> equals <code>null</code>
723 private Type typedefToGeneratedType(final String basePackageName, final Module module,
724 final TypeDefinition<?> typedef) {
725 final String moduleName = module.getName();
726 final Date moduleRevision = module.getRevision();
727 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
728 final String typedefName = typedef.getQName().getLocalName();
729 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
730 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
731 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
732 Type returnType = null;
733 if (innerTypeDefinition instanceof ExtendedType) {
734 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
735 returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName,
737 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
738 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
739 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
740 genTOBuilder.setTypedef(true);
741 genTOBuilder.setIsUnion(true);
742 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
743 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
744 returnType = genTOBuilder.toInstance();
746 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
747 genTOBuilder.getName() + "Builder");
748 unionBuilder.setIsUnionBuilder(true);
749 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
750 method.setReturnType(returnType);
751 method.addParameter(Types.STRING, "defaultValue");
752 method.setAccessModifier(AccessModifier.PUBLIC);
753 method.setStatic(true);
754 Set<Type> types = additionalTypes.get(module);
756 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
757 additionalTypes.put(module, types);
759 types.add(unionBuilder.toInstance());
761 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
762 // enums are automatically Serializable
763 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
764 // TODO units for typedef enum
765 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
766 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
767 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
768 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
769 basePackageName, bitsTypeDefinition, typedefName, module.getName());
770 genTOBuilder.setTypedef(true);
771 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
772 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
773 returnType = genTOBuilder.toInstance();
775 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
776 innerTypeDefinition, typedef);
777 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
779 if (returnType != null) {
780 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
781 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
782 if (typeMap != null) {
783 if (typeMap.isEmpty()) {
784 typeMap = new HashMap<>(4);
785 modulesByDate.put(moduleRevision, typeMap);
787 typeMap.put(typedefName, returnType);
797 * Wraps base YANG type to generated TO.
799 * @param basePackageName
800 * string with name of package to which the module belongs
802 * type definition which is converted to the TO
804 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
805 * @return generated transfer object which represent<code>javaType</code>
807 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
808 final Type javaType, final String moduleName) {
809 Preconditions.checkNotNull(javaType, "javaType cannot be null");
810 final String propertyName = "value";
812 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
813 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
814 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
815 genPropBuilder.setReturnType(javaType);
816 genTOBuilder.addEqualsIdentity(genPropBuilder);
817 genTOBuilder.addHashIdentity(genPropBuilder);
818 genTOBuilder.addToStringProperty(genPropBuilder);
819 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef instanceof ExtendedType) {
820 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
821 addStringRegExAsConstant(genTOBuilder, regExps);
823 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
824 genTOBuilder.setTypedef(true);
825 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
826 return genTOBuilder.toInstance();
830 * Converts output list of generated TO builders to one TO builder (first
831 * from list) which contains the remaining builders as its enclosing TO.
833 * @param basePackageName
834 * string with name of package to which the module belongs
836 * type definition which should be of type
837 * <code>UnionTypeDefinition</code>
839 * string with name for generated TO
840 * @return generated TO builder with the list of enclosed generated TO
843 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
844 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
845 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
846 typedef, typeDefName, parentNode);
847 GeneratedTOBuilder resultTOBuilder = null;
848 if (genTOBuilders.isEmpty()) {
849 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typedef);
852 resultTOBuilder = genTOBuilders.remove(0);
853 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
854 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
857 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
858 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
859 resultTOBuilder.addEqualsIdentity(genPropBuilder);
860 resultTOBuilder.addHashIdentity(genPropBuilder);
861 resultTOBuilder.addToStringProperty(genPropBuilder);
863 return resultTOBuilder;
867 * Converts <code>typedef</code> to generated TO with
868 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
869 * added to generated TO builder as property.
871 * @param basePackageName
872 * string with name of package to which the module belongs
874 * type definition which should be of type
875 * <code>UnionTypeDefinition</code>
877 * string with name for generated TO
878 * @return generated TO builder which represents <code>typedef</code>
879 * @throws NullPointerException
881 * <li>if <code>basePackageName</code> is null</li>
882 * <li>if <code>typedef</code> is null</li>
883 * <li>if Qname of <code>typedef</code> is null</li>
886 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
887 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
888 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
889 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
890 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
892 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
893 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
894 final Module module = findParentModule(schemaContext, parentNode);
896 final GeneratedTOBuilderImpl unionGenTOBuilder;
897 if (typeDefName != null && !typeDefName.isEmpty()) {
898 final String typeName = BindingMapping.getClassName(typeDefName);
899 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
900 unionGenTOBuilder.setDescription(typedef.getDescription());
901 unionGenTOBuilder.setReference(typedef.getReference());
902 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
903 unionGenTOBuilder.setModuleName(module.getName());
905 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
908 generatedTOBuilders.add(unionGenTOBuilder);
909 unionGenTOBuilder.setIsUnion(true);
910 final List<String> regularExpressions = new ArrayList<String>();
911 for (final TypeDefinition<?> unionType : unionTypes) {
912 final String unionTypeName = unionType.getQName().getLocalName();
913 if (unionType instanceof UnionType) {
914 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
915 basePackageName, parentNode));
916 } else if (unionType instanceof ExtendedType) {
917 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, regularExpressions,
919 } else if (unionType instanceof EnumTypeDefinition) {
920 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
921 unionTypeName, unionGenTOBuilder);
922 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
924 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
926 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
929 if (!regularExpressions.isEmpty()) {
930 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
933 storeGenTO(typedef, unionGenTOBuilder, parentNode);
935 return generatedTOBuilders;
939 * Wraps code which handle case when union subtype is also of the type
940 * <code>UnionType</code>.
942 * In this case the new generated TO is created for union subtype (recursive
944 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
945 * String, SchemaNode)}
946 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
947 * <code>parentUnionGenTOBuilder</code> is created property which type is
948 * equal to new generated TO.
950 * @param parentUnionGenTOBuilder
951 * generated TO builder to which is the property with the child
952 * union subtype added
953 * @param basePackageName
954 * string with the name of the module package
955 * @param unionSubtype
956 * type definition which represents union subtype
957 * @return list of generated TO builders. The number of the builders can be
958 * bigger one due to recursive call of
959 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
961 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
962 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
963 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
964 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
965 basePackageName, unionSubtype, newTOBuilderName, parentNode);
967 final GeneratedPropertyBuilder propertyBuilder;
968 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
969 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
970 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
971 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
973 return subUnionGenTOBUilders;
977 * Wraps code which handle case when union subtype is of the type
978 * <code>ExtendedType</code>.
980 * If TO for this type already exists it is used for the creation of the
981 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
982 * type is used for the property creation.
984 * @param parentUnionGenTOBuilder
985 * generated TO builder in which new property is created
986 * @param unionSubtype
987 * type definition of the <code>ExtendedType</code> type which
988 * represents union subtype
989 * @param regularExpressions
990 * list of strings with the regular expressions
992 * parent Schema Node for Extended Subtype
995 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
996 final ExtendedType unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
997 final String unionTypeName = unionSubtype.getQName().getLocalName();
998 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1000 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1002 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1003 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1004 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1006 if (javaType != null) {
1007 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1010 if (baseType instanceof StringType) {
1011 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
1017 * Searches for generated TO for <code>searchedTypeDef</code> type
1018 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1020 * @param searchedTypeName
1021 * string with name of <code>searchedTypeDef</code>
1022 * @return generated TO for <code>searchedTypeDef</code> or
1023 * <code>null</code> it it doesn't exist
1025 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1026 final Module typeModule = findParentModule(schemaContext, parentNode);
1027 if (typeModule != null && typeModule.getName() != null) {
1028 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1029 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1030 if (genTOs != null) {
1031 return genTOs.get(searchedTypeName);
1038 * Stores generated TO created from <code>genTOBuilder</code> for
1039 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1040 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1043 * type definition for which is <code>genTOBuilder</code> created
1044 * @param genTOBuilder
1045 * generated TO builder which is converted to generated TO and
1048 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1049 final SchemaNode parentNode) {
1050 if (!(newTypeDef instanceof UnionType)) {
1052 final Module parentModule = findParentModule(schemaContext, parentNode);
1053 if (parentModule != null && parentModule.getName() != null) {
1054 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1055 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1056 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1062 * Adds a new property with the name <code>propertyName</code> and with type
1063 * <code>type</code> to <code>unonGenTransObject</code>.
1065 * @param unionGenTransObject
1066 * generated TO to which should be property added
1068 * JAVA <code>type</code> of the property which should be added
1069 * to <code>unionGentransObject</code>
1070 * @param propertyName
1071 * string with name of property which should be added to
1072 * <code>unionGentransObject</code>
1074 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1075 final String propertyName) {
1076 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1077 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1078 .addProperty(BindingMapping.getPropertyName(propertyName));
1079 propBuilder.setReturnType(type);
1081 unionGenTransObject.addEqualsIdentity(propBuilder);
1082 unionGenTransObject.addHashIdentity(propBuilder);
1083 unionGenTransObject.addToStringProperty(propBuilder);
1088 * Converts <code>typedef</code> to the generated TO builder.
1090 * @param basePackageName
1091 * string with name of package to which the module belongs
1093 * type definition from which is the generated TO builder created
1094 * @return generated TO builder which contains data from
1095 * <code>typedef</code> and <code>basePackageName</code>
1097 private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName,
1098 final TypeDefinition<?> typedef, final String moduleName) {
1100 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
1101 final String typeDefTOName = typedef.getQName().getLocalName();
1103 if ((packageName != null) && (typeDefTOName != null)) {
1104 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1105 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1107 newType.setDescription(typedef.getDescription());
1108 newType.setReference(typedef.getReference());
1109 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1110 newType.setModuleName(moduleName);
1118 * Converts <code>typeDef</code> which should be of the type
1119 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1121 * All the bits of the typeDef are added to returning generated TO as
1124 * @param basePackageName
1125 * string with name of package to which the module belongs
1127 * type definition from which is the generated TO builder created
1128 * @param typeDefName
1129 * string with the name for generated TO builder
1130 * @return generated TO builder which represents <code>typeDef</code>
1131 * @throws IllegalArgumentException
1133 * <li>if <code>typeDef</code> equals null</li>
1134 * <li>if <code>basePackageName</code> equals null</li>
1137 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1138 final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1140 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1141 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1143 if (typeDef instanceof BitsTypeDefinition) {
1144 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1146 final String typeName = BindingMapping.getClassName(typeDefName);
1147 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1149 genTOBuilder.setDescription(typeDef.getDescription());
1150 genTOBuilder.setReference(typeDef.getReference());
1151 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1152 genTOBuilder.setModuleName(moduleName);
1153 genTOBuilder.setBaseType(typeDef);
1155 final List<Bit> bitList = bitsTypeDefinition.getBits();
1156 GeneratedPropertyBuilder genPropertyBuilder;
1157 for (final Bit bit : bitList) {
1158 String name = bit.getName();
1159 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1160 genPropertyBuilder.setReadOnly(true);
1161 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1163 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1164 genTOBuilder.addHashIdentity(genPropertyBuilder);
1165 genTOBuilder.addToStringProperty(genPropertyBuilder);
1168 return genTOBuilder;
1174 * Converts the pattern constraints from <code>typedef</code> to the list of
1175 * the strings which represents these constraints.
1178 * extended type in which are the pattern constraints sought
1179 * @return list of strings which represents the constraint patterns
1180 * @throws IllegalArgumentException
1181 * if <code>typedef</code> equals null
1184 private List<String> resolveRegExpressionsFromTypedef(final ExtendedType typedef) {
1185 final List<String> regExps = new ArrayList<String>();
1186 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1187 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1188 if (strTypeDef instanceof StringType) {
1189 final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1190 if (!patternConstraints.isEmpty()) {
1192 String modifiedRegEx;
1193 for (PatternConstraint patternConstraint : patternConstraints) {
1194 regEx = patternConstraint.getRegularExpression();
1195 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1196 regExps.add(modifiedRegEx);
1205 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1206 * expressions from the <code>regularExpressions</code>
1208 * @param genTOBuilder
1209 * generated TO builder to which are
1210 * <code>regular expressions</code> added
1211 * @param regularExpressions
1212 * list of string which represent regular expressions
1213 * @throws IllegalArgumentException
1215 * <li>if <code>genTOBuilder</code> equals null</li>
1216 * <li>if <code>regularExpressions</code> equals null</li>
1219 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1220 if (genTOBuilder == null) {
1221 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1223 if (regularExpressions == null) {
1224 throw new IllegalArgumentException("List of regular expressions can't be null");
1226 if (!regularExpressions.isEmpty()) {
1227 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1228 regularExpressions);
1233 * Creates generated TO with data about inner extended type
1234 * <code>innerExtendedType</code>, about the package name
1235 * <code>typedefName</code> and about the generated TO name
1236 * <code>typedefName</code>.
1238 * It is supposed that <code>innerExtendedType</code> is already present in
1239 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1240 * be possible set it as extended type for the returning generated TO.
1244 * @param innerExtendedType
1245 * extended type which is part of some other extended type
1246 * @param basePackageName
1247 * string with the package name of the module
1250 * @return generated TO which extends generated TO for
1251 * <code>innerExtendedType</code>
1252 * @throws IllegalArgumentException
1254 * <li>if <code>extendedType</code> equals null</li>
1255 * <li>if <code>basePackageName</code> equals null</li>
1256 * <li>if <code>typedefName</code> equals null</li>
1259 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1260 final ExtendedType innerExtendedType, final String basePackageName, final String moduleName) {
1261 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1262 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1264 final String typedefName = typedef.getQName().getLocalName();
1265 final String classTypedefName = BindingMapping.getClassName(typedefName);
1266 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1267 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1269 genTOBuilder.setDescription(typedef.getDescription());
1270 genTOBuilder.setReference(typedef.getReference());
1271 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1272 genTOBuilder.setModuleName(moduleName);
1273 genTOBuilder.setTypedef(true);
1274 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1275 genTOBuilder.setRestrictions(r);
1277 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1278 genTOBuilder.setIsUnion(true);
1281 Map<Date, Map<String, Type>> modulesByDate = null;
1282 Map<String, Type> typeMap = null;
1283 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1284 if (parentModule != null) {
1285 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1286 typeMap = modulesByDate.get(parentModule.getRevision());
1289 if (typeMap != null) {
1290 Type type = typeMap.get(innerTypeDef);
1291 if (type instanceof GeneratedTransferObject) {
1292 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1295 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1296 makeSerializable(genTOBuilder);
1298 return genTOBuilder.toInstance();
1302 * Add {@link Serializable} to implemented interfaces of this TO. Also
1303 * compute and add serialVersionUID property.
1306 * transfer object which needs to be serializable
1308 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1309 gto.addImplementsType(Types.typeForClass(Serializable.class));
1310 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1311 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1316 * Finds out for each type definition how many immersion (depth) is
1317 * necessary to get to the base type. Every type definition is inserted to
1318 * the map which key is depth and value is list of type definitions with
1319 * equal depth. In next step are lists from this map concatenated to one
1320 * list in ascending order according to their depth. All type definitions
1321 * are in the list behind all type definitions on which depends.
1323 * @param unsortedTypeDefinitions
1324 * list of type definitions which should be sorted by depth
1325 * @return list of type definitions sorted according their each other
1326 * dependencies (type definitions which are depend on other type
1327 * definitions are in list behind them).
1329 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1330 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1331 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1333 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1334 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1335 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1336 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1337 if (typeDefinitionsConcreteDepth == null) {
1338 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1339 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1341 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1344 // SortedMap guarantees order corresponding to keys in ascending order
1345 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1346 sortedTypeDefinition.addAll(v);
1349 return sortedTypeDefinition;
1353 * Returns how many immersion is necessary to get from the type definition
1356 * @param typeDefinition
1357 * type definition for which is depth sought.
1358 * @return number of immersions which are necessary to get from the type
1359 * definition to the base type
1361 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1362 if (typeDefinition == null) {
1366 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1368 if (baseType instanceof ExtendedType) {
1369 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1370 } else if (baseType instanceof UnionType) {
1371 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1372 int maxChildDepth = 0;
1374 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1375 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1376 if (childDepth > maxChildDepth) {
1377 maxChildDepth = childDepth;
1380 return maxChildDepth;
1386 * Returns string which contains the same value as <code>name</code> but
1387 * integer suffix is incremented by one. If <code>name</code> contains no
1388 * number suffix then number 1 is added.
1391 * string with name of augmented node
1392 * @return string with the number suffix incremented by one (or 1 is added)
1394 private static String provideAvailableNameForGenTOBuilder(final String name) {
1395 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1397 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1398 return name.substring(0, mtch.start()) + newSuffix;
1404 public void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1405 if (units != null && !units.isEmpty()) {
1406 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1407 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1408 prop.setReturnType(Types.STRING);
1409 to.addToStringProperty(prop);
1414 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1415 return getTypeDefaultConstruction(node, node.getDefault());
1418 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1419 TypeDefinition<?> type = node.getType();
1420 QName typeQName = type.getQName();
1421 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1422 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1423 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1426 StringBuilder sb = new StringBuilder();
1427 String result = null;
1428 if (base instanceof BinaryTypeDefinition) {
1429 result = binaryToDef(defaultValue);
1430 } else if (base instanceof BitsTypeDefinition) {
1433 Module parent = getParentModule(node);
1434 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1436 if (!(path.hasNext())) {
1437 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1438 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1439 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1441 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1442 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1443 parentName = BindingMapping.getClassName(parent.getName());
1444 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1446 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1447 } else if (base instanceof BooleanTypeDefinition) {
1448 result = typeToDef(Boolean.class, defaultValue);
1449 } else if (base instanceof DecimalTypeDefinition) {
1450 result = typeToDef(BigDecimal.class, defaultValue);
1451 } else if (base instanceof EmptyTypeDefinition) {
1452 result = typeToDef(Boolean.class, defaultValue);
1453 } else if (base instanceof EnumTypeDefinition) {
1454 char[] defValArray = defaultValue.toCharArray();
1455 char first = Character.toUpperCase(defaultValue.charAt(0));
1456 defValArray[0] = first;
1457 String newDefVal = new String(defValArray);
1459 if (type instanceof ExtendedType) {
1460 Module m = getParentModule(type);
1461 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1462 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1463 className = packageName + "." + BindingMapping.getClassName(typeQName);
1465 Module parentModule = getParentModule(node);
1466 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1467 String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
1468 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1470 result = className + "." + newDefVal;
1471 } else if (base instanceof IdentityrefTypeDefinition) {
1472 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1473 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1474 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1475 } else if (base instanceof Int8) {
1476 result = typeToDef(Byte.class, defaultValue);
1477 } else if (base instanceof Int16) {
1478 result = typeToDef(Short.class, defaultValue);
1479 } else if (base instanceof Int32) {
1480 result = typeToDef(Integer.class, defaultValue);
1481 } else if (base instanceof Int64) {
1482 result = typeToDef(Long.class, defaultValue);
1483 } else if (base instanceof LeafrefTypeDefinition) {
1484 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1485 } else if (base instanceof StringTypeDefinition) {
1486 result = "\"" + defaultValue + "\"";
1487 } else if (base instanceof Uint8) {
1488 result = typeToDef(Short.class, defaultValue);
1489 } else if (base instanceof Uint16) {
1490 result = typeToDef(Integer.class, defaultValue);
1491 } else if (base instanceof Uint32) {
1492 result = typeToDef(Long.class, defaultValue);
1493 } else if (base instanceof Uint64) {
1494 result = typeToDef(BigInteger.class, defaultValue);
1495 } else if (base instanceof UnionTypeDefinition) {
1496 result = unionToDef(node);
1502 if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
1503 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
1504 Module m = getParentModule(type);
1505 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1506 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1507 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1508 sb.insert(0, "new " + className + "(");
1509 sb.insert(sb.length(), ')');
1512 return sb.toString();
1515 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1516 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1519 private static String binaryToDef(final String defaultValue) {
1520 StringBuilder sb = new StringBuilder();
1521 BaseEncoding en = BaseEncoding.base64();
1522 byte[] encoded = en.decode(defaultValue);
1523 sb.append("new byte[] {");
1524 for (int i = 0; i < encoded.length; i++) {
1525 sb.append(encoded[i]);
1526 if (i != encoded.length - 1) {
1531 return sb.toString();
1534 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1535 final boolean isExt) {
1536 List<Bit> bits = new ArrayList<>(type.getBits());
1537 Collections.sort(bits, new Comparator<Bit>() {
1539 public int compare(final Bit o1, final Bit o2) {
1540 return o1.getName().compareTo(o2.getName());
1543 StringBuilder sb = new StringBuilder();
1546 sb.append(className);
1549 for (int i = 0; i < bits.size(); i++) {
1550 if (bits.get(i).getName().equals(defaultValue)) {
1555 if (i != bits.size() - 1) {
1562 return sb.toString();
1565 private Module getParentModule(final SchemaNode node) {
1566 QName qname = node.getPath().getPathFromRoot().iterator().next();
1567 URI namespace = qname.getNamespace();
1568 Date revision = qname.getRevision();
1569 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1572 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1573 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1574 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1575 "The Path Statement for Leafref Type Definition cannot be NULL!");
1577 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1578 final String strXPath = xpath.toString();
1580 if (strXPath != null) {
1581 if (strXPath.indexOf('[') == -1) {
1582 final Module module = findParentModule(schemaContext, parentNode);
1583 if (module != null) {
1584 final SchemaNode dataNode;
1585 if (xpath.isAbsolute()) {
1586 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1588 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1590 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1594 return "new java.lang.Object()";
1601 private String unionToDef(final LeafSchemaNode node) {
1605 if (node.getType() instanceof ExtendedType) {
1606 ExtendedType type = (ExtendedType) node.getType();
1607 QName typeQName = type.getQName();
1608 Module module = null;
1609 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1610 if (modules.size() > 1) {
1611 for (Module m : modules) {
1612 if (m.getRevision().equals(typeQName.getRevision())) {
1617 if (module == null) {
1618 List<Module> modulesList = new ArrayList<>(modules);
1619 Collections.sort(modulesList, new Comparator<Module>() {
1621 public int compare(final Module o1, final Module o2) {
1622 return o1.getRevision().compareTo(o2.getRevision());
1625 module = modulesList.get(0);
1628 module = modules.iterator().next();
1631 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1632 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1634 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1635 QName first = path.next();
1636 if (!(path.hasNext())) {
1637 URI namespace = first.getNamespace();
1638 Date revision = first.getRevision();
1639 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1640 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1641 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1642 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1644 URI namespace = first.getNamespace();
1645 Date revision = first.getRevision();
1646 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1647 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1648 String packageName = packageNameForGeneratedType(basePackageName, node.getType().getPath());
1649 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1652 return union(className, node.getDefault(), node);
1655 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1656 StringBuilder sb = new StringBuilder();
1658 sb.append(className);
1660 sb.append(defaultValue);
1661 sb.append("\".toCharArray())");
1662 return sb.toString();
1666 public String getConstructorPropertyName(final SchemaNode node) {
1667 if (node instanceof TypeDefinition<?>) {
1675 public String getParamNameFromType(final TypeDefinition<?> type) {
1676 return BindingMapping.getPropertyName(type.getQName().getLocalName());