2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.sal.binding.yang.types;
10 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.moduleNamespaceToPackageName;
11 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
12 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.parseToValidParamName;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
14 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
15 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
17 import com.google.common.base.Preconditions;
18 import com.google.common.collect.Sets;
19 import com.google.common.io.BaseEncoding;
20 import java.io.Serializable;
21 import java.math.BigDecimal;
22 import java.math.BigInteger;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.Date;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
34 import java.util.TreeMap;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37 import org.apache.commons.lang3.StringEscapeUtils;
38 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
39 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
40 import org.opendaylight.yangtools.binding.generator.util.Types;
41 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
42 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
43 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
44 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
45 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
46 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
47 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
48 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty;
49 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
50 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
51 import org.opendaylight.yangtools.sal.binding.model.api.Type;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
53 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
54 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
55 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
56 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
57 import org.opendaylight.yangtools.yang.binding.BindingMapping;
58 import org.opendaylight.yangtools.yang.common.QName;
59 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.Module;
63 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
67 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
69 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
71 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
79 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
82 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
83 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
84 import org.opendaylight.yangtools.yang.model.util.Int16;
85 import org.opendaylight.yangtools.yang.model.util.Int32;
86 import org.opendaylight.yangtools.yang.model.util.Int64;
87 import org.opendaylight.yangtools.yang.model.util.Int8;
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;
95 public final class TypeProviderImpl implements TypeProvider {
96 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
99 * Contains the schema data red from YANG files.
101 private final SchemaContext schemaContext;
104 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
106 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
109 * The map which maps schema paths to JAVA <code>Type</code>.
111 private final Map<SchemaPath, Type> referencedTypes;
112 private final Map<Module, Set<Type>> additionalTypes;
115 * Creates new instance of class <code>TypeProviderImpl</code>.
117 * @param schemaContext
118 * contains the schema data red from YANG files
119 * @throws IllegalArgumentException
120 * if <code>schemaContext</code> equal null.
122 public TypeProviderImpl(final SchemaContext schemaContext) {
123 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
125 this.schemaContext = schemaContext;
126 this.genTypeDefsContextMap = new HashMap<>();
127 this.referencedTypes = new HashMap<>();
128 this.additionalTypes = new HashMap<>();
129 resolveTypeDefsFromContext();
133 * Puts <code>refType</code> to map with key <code>refTypePath</code>
136 * schema path used as the map key
138 * type which represents the map value
139 * @throws IllegalArgumentException
141 * <li>if <code>refTypePath</code> equal null</li>
142 * <li>if <code>refType</code> equal null</li>
146 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
147 Preconditions.checkArgument(refTypePath != null,
148 "Path reference of Enumeration Type Definition cannot be NULL!");
149 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
150 referencedTypes.put(refTypePath, refType);
153 public Map<Module, Set<Type>> getAdditionalTypes() {
154 return additionalTypes;
159 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
162 * string with YANG name of type
163 * @return JAVA <code>Type</code> for YANG type <code>type</code>
164 * @see TypeProvider#javaTypeForYangType(String)
168 public Type javaTypeForYangType(final String type) {
169 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
173 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
174 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
178 * Converts schema definition type <code>typeDefinition</code> to JAVA
181 * @param typeDefinition
182 * type definition which is converted to JAVA type
183 * @throws IllegalArgumentException
185 * <li>if <code>typeDefinition</code> equal null</li>
186 * <li>if Qname of <code>typeDefinition</code> equal null</li>
187 * <li>if name of <code>typeDefinition</code> equal null</li>
191 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
192 final Restrictions r) {
193 Type returnType = null;
194 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
195 Preconditions.checkArgument(typeDefinition.getQName() != null,
196 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
197 String typedefName = typeDefinition.getQName().getLocalName();
198 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
200 if (typeDefinition instanceof ExtendedType) {
201 returnType = javaTypeForExtendedType(typeDefinition);
202 if (r != null && returnType instanceof GeneratedTransferObject) {
203 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
204 Module module = findParentModule(schemaContext, parentNode);
205 String basePackageName = moduleNamespaceToPackageName(module);
206 String packageName = packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
207 String genTOName = BindingMapping.getClassName(typedefName);
208 String name = packageName + "." + genTOName;
209 if (!(returnType.getFullyQualifiedName().equals(name))) {
210 returnType = shadedTOWithRestrictions(gto, r);
214 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
215 if (returnType == null) {
216 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
220 // TODO: add throw exception when we will be able to resolve ALL yang
222 // if (returnType == null) {
223 // throw new IllegalArgumentException("Type Provider can't resolve " +
224 // "type for specified Type Definition " + typedefName);
229 private GeneratedTransferObject shadedTOWithRestrictions(GeneratedTransferObject gto, Restrictions r) {
230 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
231 GeneratedTransferObject parent = gto.getSuperType();
232 if (parent != null) {
233 gtob.setExtendsType(parent);
235 gtob.setRestrictions(r);
236 for (GeneratedProperty gp : gto.getProperties()) {
237 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
238 gpb.setValue(gp.getValue());
239 gpb.setReadOnly(gp.isReadOnly());
240 gpb.setAccessModifier(gp.getAccessModifier());
241 gpb.setReturnType(gp.getReturnType());
242 gpb.setFinal(gp.isFinal());
243 gpb.setStatic(gp.isStatic());
245 return gtob.toInstance();
249 * Returns JAVA <code>Type</code> for instances of the type
250 * <code>LeafrefTypeDefinition</code> or
251 * <code>IdentityrefTypeDefinition</code>.
253 * @param typeDefinition
254 * type definition which is converted to JAVA <code>Type</code>
255 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
257 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
258 if (typeDefinition instanceof LeafrefTypeDefinition) {
259 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
260 return provideTypeForLeafref(leafref, parentNode);
261 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
262 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
263 return provideTypeForIdentityref(idref);
270 * Returns JAVA <code>Type</code> for instances of the type
271 * <code>ExtendedType</code>.
273 * @param typeDefinition
274 * type definition which is converted to JAVA <code>Type</code>
275 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
277 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
278 final String typedefName = typeDefinition.getQName().getLocalName();
279 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
280 Type returnType = null;
281 returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
282 if (returnType == null) {
283 if (baseTypeDef instanceof EnumTypeDefinition) {
284 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
285 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
287 final Module module = findParentModule(schemaContext, typeDefinition);
288 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
289 if (module != null) {
290 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
291 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
292 if (genTOs != null) {
293 returnType = genTOs.get(typedefName);
295 if (returnType == null) {
296 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
297 baseTypeDef, typeDefinition, r);
303 // TODO: add throw exception when we will be able to resolve ALL yang
305 // if (returnType == null) {
306 // throw new IllegalArgumentException("Type Provider can't resolve " +
307 // "type for specified Type Definition " + typedefName);
312 * Seeks for identity reference <code>idref</code> the JAVA
313 * <code>type</code>.<br />
317 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
318 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
321 * identityref type definition for which JAVA <code>Type</code>
323 * @return JAVA <code>Type</code> of the identity which is refrenced through
326 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
327 QName baseIdQName = idref.getIdentity().getQName();
328 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
329 baseIdQName.getRevision());
330 IdentitySchemaNode identity = null;
331 for (IdentitySchemaNode id : module.getIdentities()) {
332 if (id.getQName().equals(baseIdQName)) {
336 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
338 final String basePackageName = moduleNamespaceToPackageName(module);
339 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
340 final String genTypeName = BindingMapping.getClassName(identity.getQName());
342 Type baseType = Types.typeForClass(Class.class);
343 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
344 return Types.parameterizedTypeFor(baseType, paramType);
348 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
350 * @param typeDefinition
351 * type definition which should be converted to JAVA
353 * @return JAVA <code>Type</code> which represents
354 * <code>typeDefinition</code>
355 * @throws IllegalArgumentException
357 * <li>if <code>typeDefinition</code> equal null</li>
358 * <li>if Q name of <code>typeDefinition</code></li>
359 * <li>if name of <code>typeDefinition</code></li>
362 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
363 final SchemaNode parentNode) {
364 Type returnType = null;
365 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
366 if (typeDefinition.getQName() == null) {
367 throw new IllegalArgumentException(
368 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
370 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
371 "Type Definitions Local Name cannot be NULL!");
373 final String typedefName = typeDefinition.getQName().getLocalName();
374 if (typeDefinition instanceof ExtendedType) {
375 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
377 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
378 final Module module = findParentModule(schemaContext, parentNode);
380 if (module != null) {
381 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
382 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
383 if (genTOs != null) {
384 returnType = genTOs.get(typedefName);
393 * Gets base type definition for <code>extendTypeDef</code>. The method is
394 * recursivelly called until non <code>ExtendedType</code> type is found.
396 * @param extendTypeDef
397 * type definition for which is the base type definition sought
398 * @return type definition which is base type for <code>extendTypeDef</code>
399 * @throws IllegalArgumentException
400 * if <code>extendTypeDef</code> equal null
402 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
403 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
404 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
405 if (baseTypeDef == null) {
406 return extendTypeDef;
407 } else if (baseTypeDef instanceof ExtendedType) {
408 return baseTypeDefForExtendedType(baseTypeDef);
416 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
418 * The path of <code>leafrefType</code> is followed to find referenced node
419 * and its <code>Type</code> is returned.
422 * leafref type definition for which is the type sought
423 * @return JAVA <code>Type</code> of data schema node which is referenced in
424 * <code>leafrefType</code>
425 * @throws IllegalArgumentException
427 * <li>if <code>leafrefType</code> equal null</li>
428 * <li>if path statement of <code>leafrefType</code> equal null</li>
432 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
433 Type returnType = null;
434 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
436 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
437 "The Path Statement for Leafref Type Definition cannot be NULL!");
439 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
440 final String strXPath = xpath.toString();
442 if (strXPath != null) {
443 if (strXPath.indexOf('[') == -1) {
444 final Module module = findParentModule(schemaContext, parentNode);
445 if (module != null) {
446 final SchemaNode dataNode;
447 if (xpath.isAbsolute()) {
448 dataNode = findDataSchemaNode(schemaContext, module, xpath);
450 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
453 if (leafContainsEnumDefinition(dataNode)) {
454 returnType = referencedTypes.get(dataNode.getPath());
455 } else if (leafListContainsEnumDefinition(dataNode)) {
456 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
458 returnType = resolveTypeFromDataSchemaNode(dataNode);
462 returnType = Types.typeForClass(Object.class);
465 if (returnType == null) {
466 throw new IllegalArgumentException("Failed to find leafref target: " + strXPath);
472 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
473 * so then checks if it is of type <code>EnumTypeDefinition</code>.
476 * data schema node for which is checked if it is leaf and if it
478 * @return boolean value
480 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
481 * <li>false - other cases</li>
484 private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
485 if (dataNode instanceof LeafSchemaNode) {
486 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
487 if (leaf.getType() instanceof EnumTypeDefinition) {
495 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
496 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
499 * data schema node for which is checked if it is leaflist and if
501 * @return boolean value
503 * <li>true - if <code>dataNode</code> is leaflist of type
505 * <li>false - other cases</li>
508 private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
509 if (dataNode instanceof LeafListSchemaNode) {
510 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
511 if (leafList.getType() instanceof EnumTypeDefinition) {
519 * Converts <code>enumTypeDef</code> to
520 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
524 * enumeration type definition which is converted to enumeration
526 * string with name which is used as the enumeration name
527 * @return enumeration type which is built with data (name, enum values)
528 * from <code>enumTypeDef</code>
529 * @throws IllegalArgumentException
531 * <li>if <code>enumTypeDef</code> equals null</li>
532 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
533 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
534 * <li>if name of <code>enumTypeDef</code> equal null</li>
537 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
538 final SchemaNode parentNode) {
539 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
540 Preconditions.checkArgument(enumTypeDef.getValues() != null,
541 "EnumTypeDefinition MUST contain at least ONE value definition!");
542 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
543 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
544 "Local Name in EnumTypeDefinition QName cannot be NULL!");
546 final String enumerationName = BindingMapping.getClassName(enumName);
548 Module module = findParentModule(schemaContext, parentNode);
549 final String basePackageName = moduleNamespaceToPackageName(module);
551 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
552 enumBuilder.setDescription(enumTypeDef.getDescription());
553 enumBuilder.setReference(enumTypeDef.getReference());
554 enumBuilder.setModuleName(module.getName());
555 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
556 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
557 return enumBuilder.toInstance(null);
561 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
562 * taken from <code>enumTypeDef</code>.
565 * enumeration type definition is source of enumeration data for
566 * <code>typeBuilder</code>
568 * string with the name of enumeration
570 * generated type builder to which is enumeration added
571 * @return enumeration type which contains enumeration data form
572 * <code>enumTypeDef</code>
573 * @throws IllegalArgumentException
575 * <li>if <code>enumTypeDef</code> equals null</li>
576 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
577 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
578 * <li>if name of <code>enumTypeDef</code> equal null</li>
579 * <li>if name of <code>typeBuilder</code> equal null</li>
583 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
584 final GeneratedTypeBuilderBase<?> typeBuilder) {
585 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
586 Preconditions.checkArgument(enumTypeDef.getValues() != null,
587 "EnumTypeDefinition MUST contain at least ONE value definition!");
588 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
589 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
590 "Local Name in EnumTypeDefinition QName cannot be NULL!");
591 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
593 final String enumerationName = BindingMapping.getClassName(enumName);
595 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
596 enumBuilder.setDescription(enumTypeDef.getDescription());
597 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
598 return enumBuilder.toInstance(enumBuilder);
602 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
605 * contains information about YANG type
606 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
608 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
609 Type returnType = null;
610 if (dataNode != null) {
611 if (dataNode instanceof LeafSchemaNode) {
612 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
613 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
614 } else if (dataNode instanceof LeafListSchemaNode) {
615 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
616 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
623 * Passes through all modules and through all its type definitions and
624 * convert it to generated types.
626 * The modules are firstly sorted by mutual dependencies. The modules are
627 * sequentially passed. All type definitions of a module are at the
628 * beginning sorted so that type definition with less amount of references
629 * to other type definition are processed first.<br />
630 * For each module is created mapping record in the map
631 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
632 * which map current module name to the map which maps type names to
633 * returned types (generated types).
636 private void resolveTypeDefsFromContext() {
637 final Set<Module> modules = schemaContext.getModules();
638 Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
639 final Module[] modulesArray = new Module[modules.size()];
641 for (Module modul : modules) {
642 modulesArray[i++] = modul;
644 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
647 for (final Module module : modulesSortedByDependency) {
648 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
649 if (dateTypeMap == null) {
650 dateTypeMap = new HashMap<>();
652 final Map<String, Type> typeMap = new HashMap<>();
653 dateTypeMap.put(module.getRevision(), typeMap);
654 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
657 for (final Module module : modulesSortedByDependency) {
658 if (module == null) {
661 final String basePackageName = moduleNamespaceToPackageName(module);
663 final DataNodeIterator it = new DataNodeIterator(module);
664 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
665 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
667 if ((listTypeDefinitions != null) && (basePackageName != null)) {
668 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
669 typedefToGeneratedType(basePackageName, module, typedef);
677 * @param basePackageName
678 * string with name of package to which the module belongs
680 * string with the name of the module for to which the
681 * <code>typedef</code> belongs
683 * type definition of the node for which should be creted JAVA
684 * <code>Type</code> (usually generated TO)
685 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
686 * <code>null</code> value if <code>basePackageName</code> or
687 * <code>modulName</code> or <code>typedef</code> or Q name of
688 * <code>typedef</code> equals <code>null</code>
690 private Type typedefToGeneratedType(final String basePackageName, final Module module,
691 final TypeDefinition<?> typedef) {
692 final String moduleName = module.getName();
693 final Date moduleRevision = module.getRevision();
694 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
695 final String typedefName = typedef.getQName().getLocalName();
696 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
697 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
698 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
699 Type returnType = null;
700 if (innerTypeDefinition instanceof ExtendedType) {
701 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
702 returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName,
704 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
705 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
706 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
707 genTOBuilder.setTypedef(true);
708 genTOBuilder.setIsUnion(true);
709 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
710 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
711 returnType = genTOBuilder.toInstance();
713 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
714 genTOBuilder.getName() + "Builder");
715 unionBuilder.setIsUnionBuilder(true);
716 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
717 method.setReturnType(returnType);
718 method.addParameter(Types.STRING, "defaultValue");
719 method.setAccessModifier(AccessModifier.PUBLIC);
720 method.setStatic(true);
721 Set<Type> types = additionalTypes.get(module);
723 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
724 additionalTypes.put(module, types);
726 types.add(unionBuilder.toInstance());
728 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
729 // enums are automatically Serializable
730 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
731 // TODO units for typedef enum
732 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
733 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
734 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
735 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
736 basePackageName, bitsTypeDefinition, typedefName, module.getName());
737 genTOBuilder.setTypedef(true);
738 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
739 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
740 returnType = genTOBuilder.toInstance();
742 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
743 innerTypeDefinition, typedef);
744 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
746 if (returnType != null) {
747 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
748 final Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
749 if (typeMap != null) {
750 typeMap.put(typedefName, returnType);
760 * Wraps base YANG type to generated TO.
762 * @param basePackageName
763 * string with name of package to which the module belongs
765 * type definition which is converted to the TO
767 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
768 * @return generated transfer object which represent<code>javaType</code>
770 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
771 final Type javaType, final String moduleName) {
772 Preconditions.checkNotNull(javaType, "javaType cannot be null");
773 final String propertyName = "value";
775 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
776 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
777 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
778 genPropBuilder.setReturnType(javaType);
779 genTOBuilder.addEqualsIdentity(genPropBuilder);
780 genTOBuilder.addHashIdentity(genPropBuilder);
781 genTOBuilder.addToStringProperty(genPropBuilder);
782 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef instanceof ExtendedType) {
783 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
784 addStringRegExAsConstant(genTOBuilder, regExps);
786 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
787 genTOBuilder.setTypedef(true);
788 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
789 return genTOBuilder.toInstance();
793 * Converts output list of generated TO builders to one TO builder (first
794 * from list) which contains the remaining builders as its enclosing TO.
796 * @param basePackageName
797 * string with name of package to which the module belongs
799 * type definition which should be of type
800 * <code>UnionTypeDefinition</code>
802 * string with name for generated TO
803 * @return generated TO builder with the list of enclosed generated TO
806 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
807 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
808 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
809 typedef, typeDefName, parentNode);
810 GeneratedTOBuilder resultTOBuilder = null;
811 if (genTOBuilders.isEmpty()) {
812 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typedef);
815 resultTOBuilder = genTOBuilders.remove(0);
816 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
817 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
820 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
821 genPropBuilder.setReturnType(Types.primitiveType("char[]", null));
822 resultTOBuilder.addEqualsIdentity(genPropBuilder);
823 resultTOBuilder.addHashIdentity(genPropBuilder);
824 resultTOBuilder.addToStringProperty(genPropBuilder);
826 return resultTOBuilder;
830 * Converts <code>typedef</code> to generated TO with
831 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
832 * added to generated TO builder as property.
834 * @param basePackageName
835 * string with name of package to which the module belongs
837 * type definition which should be of type
838 * <code>UnionTypeDefinition</code>
840 * string with name for generated TO
841 * @return generated TO builder which represents <code>typedef</code>
842 * @throws NullPointerException
844 * <li>if <code>basePackageName</code> is null</li>
845 * <li>if <code>typedef</code> is null</li>
846 * <li>if Qname of <code>typedef</code> is null</li>
849 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
850 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
851 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
852 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
853 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
855 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
856 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
857 final Module module = findParentModule(schemaContext, parentNode);
859 final GeneratedTOBuilderImpl unionGenTOBuilder;
860 if (typeDefName != null && !typeDefName.isEmpty()) {
861 final String typeName = BindingMapping.getClassName(typeDefName);
862 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
863 unionGenTOBuilder.setDescription(typedef.getDescription());
864 unionGenTOBuilder.setReference(typedef.getReference());
865 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
866 unionGenTOBuilder.setModuleName(module.getName());
868 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
871 generatedTOBuilders.add(unionGenTOBuilder);
872 unionGenTOBuilder.setIsUnion(true);
873 final List<String> regularExpressions = new ArrayList<String>();
874 for (final TypeDefinition<?> unionType : unionTypes) {
875 final String unionTypeName = unionType.getQName().getLocalName();
876 if (unionType instanceof UnionType) {
877 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
878 basePackageName, parentNode));
879 } else if (unionType instanceof ExtendedType) {
880 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, regularExpressions,
882 } else if (unionType instanceof EnumTypeDefinition) {
883 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
884 unionTypeName, unionGenTOBuilder);
885 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
887 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
889 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
892 if (!regularExpressions.isEmpty()) {
893 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
896 storeGenTO(typedef, unionGenTOBuilder, parentNode);
898 return generatedTOBuilders;
902 * Wraps code which handle case when union subtype is also of the type
903 * <code>UnionType</code>.
905 * In this case the new generated TO is created for union subtype (recursive
907 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, TypeDefinition, String)
908 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
909 * <code>parentUnionGenTOBuilder</code> is created property which type is
910 * equal to new generated TO.
912 * @param parentUnionGenTOBuilder
913 * generated TO builder to which is the property with the child
914 * union subtype added
915 * @param basePackageName
916 * string with the name of the module package
917 * @param unionSubtype
918 * type definition which represents union subtype
919 * @return list of generated TO builders. The number of the builders can be
920 * bigger one due to recursive call of
921 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
923 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
924 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
925 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
926 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
927 basePackageName, unionSubtype, newTOBuilderName, parentNode);
929 final GeneratedPropertyBuilder propertyBuilder;
930 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
931 .parseToValidParamName(newTOBuilderName));
932 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
933 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
934 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
936 return subUnionGenTOBUilders;
940 * Wraps code which handle case when union subtype is of the type
941 * <code>ExtendedType</code>.
943 * If TO for this type already exists it is used for the creation of the
944 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
945 * type is used for the property creation.
947 * @param parentUnionGenTOBuilder
948 * generated TO builder in which new property is created
949 * @param unionSubtype
950 * type definition of the <code>ExtendedType</code> type which
951 * represents union subtype
952 * @param unionTypeName
953 * string with the name for <code>unionSubtype</code>
954 * @param regularExpressions
955 * list of strings with the regular expressions
957 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
958 final ExtendedType unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
959 final String unionTypeName = unionSubtype.getQName().getLocalName();
960 final Type genTO = findGenTO(unionTypeName, unionSubtype);
962 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
964 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
965 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
966 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
968 if (javaType != null) {
969 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
972 if (baseType instanceof StringType) {
973 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
979 * Searches for generated TO for <code>searchedTypeDef</code> type
980 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
982 * @param searchedTypeName
983 * string with name of <code>searchedTypeDef</code>
984 * @return generated TO for <code>searchedTypeDef</code> or
985 * <code>null</code> it it doesn't exist
987 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
988 final Module typeModule = findParentModule(schemaContext, parentNode);
989 if (typeModule != null && typeModule.getName() != null) {
990 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
991 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
992 if (genTOs != null) {
993 return genTOs.get(searchedTypeName);
1000 * Stores generated TO created from <code>genTOBuilder</code> for
1001 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1002 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1005 * type definition for which is <code>genTOBuilder</code> created
1006 * @param genTOBuilder
1007 * generated TO builder which is converted to generated TO and
1010 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1011 final SchemaNode parentNode) {
1012 if (!(newTypeDef instanceof UnionType)) {
1014 final Module parentModule = findParentModule(schemaContext, parentNode);
1015 if (parentModule != null && parentModule.getName() != null) {
1016 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1017 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1018 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1024 * Adds a new property with the name <code>propertyName</code> and with type
1025 * <code>type</code> to <code>unonGenTransObject</code>.
1027 * @param unionGenTransObject
1028 * generated TO to which should be property added
1030 * JAVA <code>type</code> of the property which should be added
1031 * to <code>unionGentransObject</code>
1032 * @param propertyName
1033 * string with name of property which should be added to
1034 * <code>unionGentransObject</code>
1036 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1037 final String propertyName) {
1038 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1039 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1040 .addProperty(parseToValidParamName(propertyName));
1041 propBuilder.setReturnType(type);
1043 unionGenTransObject.addEqualsIdentity(propBuilder);
1044 unionGenTransObject.addHashIdentity(propBuilder);
1045 unionGenTransObject.addToStringProperty(propBuilder);
1050 * Converts <code>typedef</code> to the generated TO builder.
1052 * @param basePackageName
1053 * string with name of package to which the module belongs
1055 * type definition from which is the generated TO builder created
1056 * @return generated TO builder which contains data from
1057 * <code>typedef</code> and <code>basePackageName</code>
1059 private GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName,
1060 final TypeDefinition<?> typedef, final String moduleName) {
1062 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
1063 final String typeDefTOName = typedef.getQName().getLocalName();
1065 if ((packageName != null) && (typeDefTOName != null)) {
1066 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1067 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1069 newType.setDescription(typedef.getDescription());
1070 newType.setReference(typedef.getReference());
1071 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1072 newType.setModuleName(moduleName);
1080 * Converts <code>typeDef</code> which should be of the type
1081 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1083 * All the bits of the typeDef are added to returning generated TO as
1086 * @param basePackageName
1087 * string with name of package to which the module belongs
1089 * type definition from which is the generated TO builder created
1090 * @param typeDefName
1091 * string with the name for generated TO builder
1092 * @return generated TO builder which represents <code>typeDef</code>
1093 * @throws IllegalArgumentException
1095 * <li>if <code>typeDef</code> equals null</li>
1096 * <li>if <code>basePackageName</code> equals null</li>
1099 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1100 final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1102 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1103 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1105 if (typeDef instanceof BitsTypeDefinition) {
1106 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1108 final String typeName = BindingMapping.getClassName(typeDefName);
1109 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1111 genTOBuilder.setDescription(typeDef.getDescription());
1112 genTOBuilder.setReference(typeDef.getReference());
1113 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1114 genTOBuilder.setModuleName(moduleName);
1116 final List<Bit> bitList = bitsTypeDefinition.getBits();
1117 GeneratedPropertyBuilder genPropertyBuilder;
1118 for (final Bit bit : bitList) {
1119 String name = bit.getName();
1120 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
1121 genPropertyBuilder.setReadOnly(true);
1122 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1124 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1125 genTOBuilder.addHashIdentity(genPropertyBuilder);
1126 genTOBuilder.addToStringProperty(genPropertyBuilder);
1129 return genTOBuilder;
1135 * Converts the pattern constraints from <code>typedef</code> to the list of
1136 * the strings which represents these constraints.
1139 * extended type in which are the pattern constraints sought
1140 * @return list of strings which represents the constraint patterns
1141 * @throws IllegalArgumentException
1142 * if <code>typedef</code> equals null
1145 private List<String> resolveRegExpressionsFromTypedef(final ExtendedType typedef) {
1146 final List<String> regExps = new ArrayList<String>();
1147 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1148 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1149 if (strTypeDef instanceof StringType) {
1150 final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1151 if (!patternConstraints.isEmpty()) {
1153 String modifiedRegEx;
1154 for (PatternConstraint patternConstraint : patternConstraints) {
1155 regEx = patternConstraint.getRegularExpression();
1156 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1157 regExps.add(modifiedRegEx);
1166 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1167 * expressions from the <code>regularExpressions</code>
1169 * @param genTOBuilder
1170 * generated TO builder to which are
1171 * <code>regular expressions</code> added
1172 * @param regularExpressions
1173 * list of string which represent regular expressions
1174 * @throws IllegalArgumentException
1176 * <li>if <code>genTOBuilder</code> equals null</li>
1177 * <li>if <code>regularExpressions</code> equals null</li>
1180 private void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1181 if (genTOBuilder == null) {
1182 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1184 if (regularExpressions == null) {
1185 throw new IllegalArgumentException("List of regular expressions can't be null");
1187 if (!regularExpressions.isEmpty()) {
1188 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1189 regularExpressions);
1194 * Creates generated TO with data about inner extended type
1195 * <code>innerExtendedType</code>, about the package name
1196 * <code>typedefName</code> and about the generated TO name
1197 * <code>typedefName</code>.
1199 * It is supposed that <code>innerExtendedType</code> is already present in
1200 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1201 * be possible set it as extended type for the returning generated TO.
1203 * @param innerExtendedType
1204 * extended type which is part of some other extended type
1205 * @param basePackageName
1206 * string with the package name of the module
1207 * @param typedefName
1208 * string with the name for the generated TO
1209 * @return generated TO which extends generated TO for
1210 * <code>innerExtendedType</code>
1211 * @throws IllegalArgumentException
1213 * <li>if <code>extendedType</code> equals null</li>
1214 * <li>if <code>basePackageName</code> equals null</li>
1215 * <li>if <code>typedefName</code> equals null</li>
1218 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1219 final ExtendedType innerExtendedType, final String basePackageName, final String moduleName) {
1220 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1221 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1223 final String typedefName = typedef.getQName().getLocalName();
1224 final String classTypedefName = BindingMapping.getClassName(typedefName);
1225 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1226 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1228 genTOBuilder.setDescription(typedef.getDescription());
1229 genTOBuilder.setReference(typedef.getReference());
1230 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1231 genTOBuilder.setModuleName(moduleName);
1232 genTOBuilder.setTypedef(true);
1233 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1234 genTOBuilder.setRestrictions(r);
1236 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1237 genTOBuilder.setIsUnion(true);
1240 Map<Date, Map<String, Type>> modulesByDate = null;
1241 Map<String, Type> typeMap = null;
1242 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1243 if (parentModule != null) {
1244 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1245 typeMap = modulesByDate.get(parentModule.getRevision());
1248 if (typeMap != null) {
1249 Type type = typeMap.get(innerTypeDef);
1250 if (type instanceof GeneratedTransferObject) {
1251 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1254 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1255 makeSerializable(genTOBuilder);
1257 return genTOBuilder.toInstance();
1261 * Add {@link Serializable} to implemented interfaces of this TO. Also
1262 * compute and add serialVersionUID property.
1265 * transfer object which needs to be serializable
1267 private void makeSerializable(final GeneratedTOBuilderImpl gto) {
1268 gto.addImplementsType(Types.typeForClass(Serializable.class));
1269 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1270 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1275 * Finds out for each type definition how many immersion (depth) is
1276 * necessary to get to the base type. Every type definition is inserted to
1277 * the map which key is depth and value is list of type definitions with
1278 * equal depth. In next step are lists from this map concatenated to one
1279 * list in ascending order according to their depth. All type definitions
1280 * are in the list behind all type definitions on which depends.
1282 * @param unsortedTypeDefinitions
1283 * list of type definitions which should be sorted by depth
1284 * @return list of type definitions sorted according their each other
1285 * dependencies (type definitions which are depend on other type
1286 * definitions are in list behind them).
1288 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1289 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1290 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1292 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1293 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1294 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1295 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1296 if (typeDefinitionsConcreteDepth == null) {
1297 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1298 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1300 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1302 // keys are in ascending order
1303 for (Map.Entry<Integer, List<TypeDefinition<?>>> entry : typeDefinitionsDepths.entrySet()) {
1304 sortedTypeDefinition.addAll(entry.getValue());
1307 return sortedTypeDefinition;
1311 * Returns how many immersion is necessary to get from the type definition
1314 * @param typeDefinition
1315 * type definition for which is depth sought.
1316 * @return number of immersions which are necessary to get from the type
1317 * definition to the base type
1319 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1320 if (typeDefinition == null) {
1324 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1326 if (baseType instanceof ExtendedType) {
1327 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1328 } else if (baseType instanceof UnionType) {
1329 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1330 int maxChildDepth = 0;
1332 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1333 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1334 if (childDepth > maxChildDepth) {
1335 maxChildDepth = childDepth;
1338 return maxChildDepth;
1344 * Returns string which contains the same value as <code>name</code> but
1345 * integer suffix is incremented by one. If <code>name</code> contains no
1346 * number suffix then number 1 is added.
1349 * string with name of augmented node
1350 * @return string with the number suffix incremented by one (or 1 is added)
1352 private String provideAvailableNameForGenTOBuilder(final String name) {
1353 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1355 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1356 return name.substring(0, mtch.start()) + newSuffix;
1362 public void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1363 if (units != null && !units.isEmpty()) {
1364 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1365 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1366 prop.setReturnType(Types.STRING);
1367 to.addToStringProperty(prop);
1372 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1373 return getTypeDefaultConstruction(node, node.getDefault());
1376 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1377 TypeDefinition<?> type = node.getType();
1378 QName typeQName = type.getQName();
1379 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1380 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of " + node);
1381 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of "
1384 StringBuilder sb = new StringBuilder();
1385 String result = null;
1386 if (base instanceof BinaryTypeDefinition) {
1387 result = binaryToDef(defaultValue);
1388 } else if (base instanceof BitsTypeDefinition) {
1391 Module parent = getParentModule(node);
1392 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1394 if (!(path.hasNext())) {
1395 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1396 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1397 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1399 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1400 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1401 parentName = BindingMapping.getClassName(((SchemaNode) parent).getQName());
1402 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1404 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1405 } else if (base instanceof BooleanTypeDefinition) {
1406 result = typeToDef(Boolean.class, defaultValue);
1407 } else if (base instanceof DecimalTypeDefinition) {
1408 result = typeToDef(BigDecimal.class, defaultValue);
1409 } else if (base instanceof EmptyTypeDefinition) {
1410 result = typeToDef(Boolean.class, defaultValue);
1411 } else if (base instanceof EnumTypeDefinition) {
1412 char[] defValArray = defaultValue.toCharArray();
1413 char first = Character.toUpperCase(defaultValue.charAt(0));
1414 defValArray[0] = first;
1415 String newDefVal = new String(defValArray);
1417 if (type instanceof ExtendedType) {
1418 Module m = getParentModule(type);
1419 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1420 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1421 className = packageName + "." + BindingMapping.getClassName(typeQName);
1423 Module parentModule = getParentModule(node);
1424 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1425 String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
1426 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1428 result = className + "." + newDefVal;
1429 } else if (base instanceof IdentityrefTypeDefinition) {
1430 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1431 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1432 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1433 } else if (base instanceof Int8) {
1434 result = typeToDef(Byte.class, defaultValue);
1435 } else if (base instanceof Int16) {
1436 result = typeToDef(Short.class, defaultValue);
1437 } else if (base instanceof Int32) {
1438 result = typeToDef(Integer.class, defaultValue);
1439 } else if (base instanceof Int64) {
1440 result = typeToDef(Long.class, defaultValue);
1441 } else if (base instanceof LeafrefTypeDefinition) {
1442 result = leafrefToDef(node, (LeafrefTypeDefinition) base);
1443 } else if (base instanceof StringTypeDefinition) {
1444 result = "\"" + defaultValue + "\"";
1445 } else if (base instanceof Uint8) {
1446 result = typeToDef(Short.class, defaultValue);
1447 } else if (base instanceof Uint16) {
1448 result = typeToDef(Integer.class, defaultValue);
1449 } else if (base instanceof Uint32) {
1450 result = typeToDef(Long.class, defaultValue);
1451 } else if (base instanceof Uint64) {
1452 result = typeToDef(BigInteger.class, defaultValue);
1453 } else if (base instanceof UnionTypeDefinition) {
1454 result = unionToDef(node);
1460 if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
1461 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
1462 Module m = getParentModule(type);
1463 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1464 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1465 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1466 sb.insert(0, "new " + className + "(");
1467 sb.insert(sb.length(), ')');
1470 return sb.toString();
1473 private String typeToDef(final Class<?> clazz, final String defaultValue) {
1474 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1477 private String binaryToDef(final String defaultValue) {
1478 StringBuilder sb = new StringBuilder();
1479 BaseEncoding en = BaseEncoding.base64();
1480 byte[] encoded = en.decode(defaultValue);
1481 sb.append("new byte[] {");
1482 for (int i = 0; i < encoded.length; i++) {
1483 sb.append(encoded[i]);
1484 if (i != encoded.length - 1) {
1489 return sb.toString();
1492 private String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1493 final boolean isExt) {
1494 List<Bit> bits = new ArrayList<>(type.getBits());
1495 Collections.sort(bits, new Comparator<Bit>() {
1497 public int compare(final Bit o1, final Bit o2) {
1498 return o1.getName().compareTo(o2.getName());
1501 StringBuilder sb = new StringBuilder();
1504 sb.append(className);
1507 for (int i = 0; i < bits.size(); i++) {
1508 if (bits.get(i).getName().equals(defaultValue)) {
1513 if (i != bits.size() - 1) {
1520 return sb.toString();
1523 private Module getParentModule(final SchemaNode node) {
1524 QName qname = node.getPath().getPathFromRoot().iterator().next();
1525 URI namespace = qname.getNamespace();
1526 Date revision = qname.getRevision();
1527 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1530 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType) {
1531 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1532 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1533 "The Path Statement for Leafref Type Definition cannot be NULL!");
1535 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1536 final String strXPath = xpath.toString();
1538 if (strXPath != null) {
1539 if (strXPath.indexOf('[') == -1) {
1540 final Module module = findParentModule(schemaContext, parentNode);
1541 if (module != null) {
1542 final SchemaNode dataNode;
1543 if (xpath.isAbsolute()) {
1544 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1546 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1548 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, parentNode.getDefault());
1552 return "new java.lang.Object()";
1559 private String unionToDef(final LeafSchemaNode node) {
1563 if (node.getType() instanceof ExtendedType) {
1564 ExtendedType type = (ExtendedType) node.getType();
1565 QName typeQName = type.getQName();
1566 Module module = null;
1567 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1568 if (modules.size() > 1) {
1569 for (Module m : modules) {
1570 if (m.getRevision().equals(typeQName.getRevision())) {
1575 if (module == null) {
1576 List<Module> modulesList = new ArrayList<>(modules);
1577 Collections.sort(modulesList, new Comparator<Module>() {
1579 public int compare(final Module o1, final Module o2) {
1580 return o1.getRevision().compareTo(o2.getRevision());
1583 module = modulesList.get(0);
1586 module = modules.iterator().next();
1589 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
1590 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1592 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1593 QName first = path.next();
1594 if (!(path.hasNext())) {
1595 URI namespace = first.getNamespace();
1596 Date revision = first.getRevision();
1597 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1598 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1599 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1600 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1602 URI namespace = first.getNamespace();
1603 Date revision = first.getRevision();
1604 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1605 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1606 String packageName = packageNameForGeneratedType(basePackageName, node.getType().getPath());
1607 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1610 return union(className, node.getDefault(), node);
1613 private String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1614 StringBuilder sb = new StringBuilder();
1616 sb.append(className);
1618 sb.append(defaultValue);
1619 sb.append("\".toCharArray())");
1620 return sb.toString();
1624 public String getConstructorPropertyName(final SchemaNode node) {
1625 if (node instanceof TypeDefinition<?>) {
1633 public String getParamNameFromType(final TypeDefinition<?> type) {
1634 return BindingGeneratorUtil.parseToValidParamName(type.getQName().getLocalName());