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.encodeAngleBrackets;
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.base.Strings;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.Sets;
18 import com.google.common.io.BaseEncoding;
19 import java.io.Serializable;
20 import java.math.BigDecimal;
21 import java.math.BigInteger;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.Date;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
33 import java.util.TreeMap;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import org.apache.commons.lang3.StringEscapeUtils;
37 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
38 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
39 import org.opendaylight.yangtools.binding.generator.util.Types;
40 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
41 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
42 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
43 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
44 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
45 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
46 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
47 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty;
48 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
49 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
50 import org.opendaylight.yangtools.sal.binding.model.api.Type;
51 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
53 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
54 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
55 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
56 import org.opendaylight.yangtools.yang.binding.BindingMapping;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
59 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.Module;
64 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
68 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
69 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
72 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
80 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.util.Decimal64;
83 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
84 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
85 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
86 import org.opendaylight.yangtools.yang.model.util.UnionType;
87 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
88 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
89 import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
93 public final class TypeProviderImpl implements TypeProvider {
94 private static final Logger LOG = LoggerFactory.getLogger(TypeProviderImpl.class);
95 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
98 * Contains the schema data red from YANG files.
100 private final SchemaContext schemaContext;
103 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
105 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
108 * The map which maps schema paths to JAVA <code>Type</code>.
110 private final Map<SchemaPath, Type> referencedTypes;
111 private final Map<Module, Set<Type>> additionalTypes;
114 * Creates new instance of class <code>TypeProviderImpl</code>.
116 * @param schemaContext
117 * contains the schema data red from YANG files
118 * @throws IllegalArgumentException
119 * if <code>schemaContext</code> equal null.
121 public TypeProviderImpl(final SchemaContext schemaContext) {
122 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
124 this.schemaContext = schemaContext;
125 this.genTypeDefsContextMap = new HashMap<>();
126 this.referencedTypes = new HashMap<>();
127 this.additionalTypes = new HashMap<>();
128 resolveTypeDefsFromContext();
132 * Puts <code>refType</code> to map with key <code>refTypePath</code>
135 * schema path used as the map key
137 * type which represents the map value
138 * @throws IllegalArgumentException
140 * <li>if <code>refTypePath</code> equal null</li>
141 * <li>if <code>refType</code> equal null</li>
145 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
146 Preconditions.checkArgument(refTypePath != null,
147 "Path reference of Enumeration Type Definition cannot be NULL!");
148 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
149 referencedTypes.put(refTypePath, refType);
152 public Map<Module, Set<Type>> getAdditionalTypes() {
153 return additionalTypes;
158 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
161 * string with YANG name of type
162 * @return JAVA <code>Type</code> for YANG type <code>type</code>
163 * @see TypeProvider#javaTypeForYangType(String)
167 public Type javaTypeForYangType(final String type) {
168 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
172 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
173 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
177 * Converts schema definition type <code>typeDefinition</code> to JAVA
180 * @param typeDefinition
181 * type definition which is converted to JAVA type
182 * @throws IllegalArgumentException
184 * <li>if <code>typeDefinition</code> equal null</li>
185 * <li>if Qname of <code>typeDefinition</code> equal null</li>
186 * <li>if name of <code>typeDefinition</code> equal null</li>
190 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode, final Restrictions r) {
191 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
192 Preconditions.checkArgument(typeDefinition.getQName() != null,
193 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
194 String typedefName = typeDefinition.getQName().getLocalName();
195 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
197 // Deal with base types
198 if (typeDefinition.getBaseType() == null) {
199 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
200 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
201 // a base type which holds these constraints -- and the class is not a Decimal64.
202 if (typeDefinition instanceof DecimalTypeDefinition && !(typeDefinition instanceof Decimal64)) {
203 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition, parentNode, r);
209 // Deal with leafrefs/identityrefs
210 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
215 // FIXME: it looks as though we could be using the same codepath as above...
216 ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName().getLocalName());
218 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
224 Type returnType = javaTypeForExtendedType(typeDefinition);
225 if (r != null && returnType instanceof GeneratedTransferObject) {
226 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
227 Module module = findParentModule(schemaContext, parentNode);
228 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
229 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
230 String genTOName = BindingMapping.getClassName(typedefName);
231 String name = packageName + "." + genTOName;
232 if (!(returnType.getFullyQualifiedName().equals(name))) {
233 returnType = shadedTOWithRestrictions(gto, r);
239 private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
240 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
241 GeneratedTransferObject parent = gto.getSuperType();
242 if (parent != null) {
243 gtob.setExtendsType(parent);
245 gtob.setRestrictions(r);
246 for (GeneratedProperty gp : gto.getProperties()) {
247 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
248 gpb.setValue(gp.getValue());
249 gpb.setReadOnly(gp.isReadOnly());
250 gpb.setAccessModifier(gp.getAccessModifier());
251 gpb.setReturnType(gp.getReturnType());
252 gpb.setFinal(gp.isFinal());
253 gpb.setStatic(gp.isStatic());
255 return gtob.toInstance();
258 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
259 final SchemaNode leafRefValueNode;
260 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
261 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
262 .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute());
264 ///// skip leafrefs in augments - they're checked once augments are resolved
265 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
266 boolean isAugmenting = false;
267 DataNodeContainer current = null;
268 DataSchemaNode dataChildByName;
270 while (iterator.hasNext() && !isAugmenting) {
271 final QName next = iterator.next();
272 if (current == null) {
273 dataChildByName = schemaContext.getDataChildByName(next);
275 dataChildByName = current.getDataChildByName(next);
277 if (dataChildByName != null) {
278 isAugmenting = dataChildByName.isAugmenting();
282 if (dataChildByName instanceof DataNodeContainer) {
283 current = (DataNodeContainer) dataChildByName;
291 Module parentModule = getParentModule(parentNode);
292 if (!leafRefStrippedXPath.isAbsolute()) {
293 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
294 parentNode, leafRefStrippedXPath);
296 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
298 return (leafRefValueNode != null) ? leafRefValueNode.equals(parentNode) : false;
302 * Returns JAVA <code>Type</code> for instances of the type
303 * <code>LeafrefTypeDefinition</code> or
304 * <code>IdentityrefTypeDefinition</code>.
306 * @param typeDefinition
307 * type definition which is converted to JAVA <code>Type</code>
308 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
310 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
311 if (typeDefinition instanceof LeafrefTypeDefinition) {
312 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
313 if (isLeafRefSelfReference(leafref, parentNode)) {
314 throw new YangValidationException("Leafref " + leafref.toString() + " is referencing itself, incoming" +
315 " StackOverFlowError detected.");
317 return provideTypeForLeafref(leafref, parentNode);
318 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
319 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
320 return provideTypeForIdentityref(idref);
327 * Returns JAVA <code>Type</code> for instances of the type
328 * <code>ExtendedType</code>.
330 * @param typeDefinition
331 * type definition which is converted to JAVA <code>Type</code>
332 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
334 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
335 final String typedefName = typeDefinition.getQName().getLocalName();
336 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
337 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
338 if (returnType == null) {
339 if (baseTypeDef instanceof EnumTypeDefinition) {
340 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
341 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
343 final Module module = findParentModule(schemaContext, typeDefinition);
344 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
345 if (module != null) {
346 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
347 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
348 if (genTOs != null) {
349 returnType = genTOs.get(typedefName);
351 if (returnType == null) {
352 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
353 baseTypeDef, typeDefinition, r);
362 * Seeks for identity reference <code>idref</code> the JAVA
363 * <code>type</code>.<br />
367 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
368 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
371 * identityref type definition for which JAVA <code>Type</code>
373 * @return JAVA <code>Type</code> of the identity which is refrenced through
376 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
377 QName baseIdQName = idref.getIdentity().getQName();
378 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
379 baseIdQName.getRevision());
380 IdentitySchemaNode identity = null;
381 for (IdentitySchemaNode id : module.getIdentities()) {
382 if (id.getQName().equals(baseIdQName)) {
386 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
388 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
389 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath());
390 final String genTypeName = BindingMapping.getClassName(identity.getQName());
392 Type baseType = Types.typeForClass(Class.class);
393 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
394 return Types.parameterizedTypeFor(baseType, paramType);
398 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
400 * @param typeDefinition
401 * type definition which should be converted to JAVA
403 * @return JAVA <code>Type</code> which represents
404 * <code>typeDefinition</code>
405 * @throws IllegalArgumentException
407 * <li>if <code>typeDefinition</code> equal null</li>
408 * <li>if Q name of <code>typeDefinition</code></li>
409 * <li>if name of <code>typeDefinition</code></li>
412 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
413 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
414 if (typeDefinition.getQName() == null) {
415 throw new IllegalArgumentException(
416 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
418 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
419 "Type Definitions Local Name cannot be NULL!");
421 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
422 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
423 final Module module = findParentModule(schemaContext, parentNode);
425 if (module != null) {
426 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
427 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
428 if (genTOs != null) {
429 return genTOs.get(typeDefinition.getQName().getLocalName());
437 * Gets base type definition for <code>extendTypeDef</code>. The method is
438 * recursively called until non <code>ExtendedType</code> type is found.
440 * @param extendTypeDef
441 * type definition for which is the base type definition sought
442 * @return type definition which is base type for <code>extendTypeDef</code>
443 * @throws IllegalArgumentException
444 * if <code>extendTypeDef</code> equal null
446 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
447 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
449 TypeDefinition<?> ret = extendTypeDef;
450 while (ret.getBaseType() != null) {
451 ret = ret.getBaseType();
458 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
460 * The path of <code>leafrefType</code> is followed to find referenced node
461 * and its <code>Type</code> is returned.
464 * leafref type definition for which is the type sought
465 * @return JAVA <code>Type</code> of data schema node which is referenced in
466 * <code>leafrefType</code>
467 * @throws IllegalArgumentException
469 * <li>if <code>leafrefType</code> equal null</li>
470 * <li>if path statement of <code>leafrefType</code> equal null</li>
474 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
475 Type returnType = null;
476 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
478 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
479 "The Path Statement for Leafref Type Definition cannot be NULL!");
481 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
482 final String strXPath = xpath.toString();
484 if (strXPath != null) {
485 if (strXPath.indexOf('[') == -1) {
486 final Module module = findParentModule(schemaContext, parentNode);
487 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
489 final SchemaNode dataNode;
490 if (xpath.isAbsolute()) {
491 dataNode = findDataSchemaNode(schemaContext, module, xpath);
493 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
495 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
496 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
498 if (leafContainsEnumDefinition(dataNode)) {
499 returnType = referencedTypes.get(dataNode.getPath());
500 } else if (leafListContainsEnumDefinition(dataNode)) {
501 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
503 returnType = resolveTypeFromDataSchemaNode(dataNode);
506 returnType = Types.typeForClass(Object.class);
509 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
510 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
515 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
516 * so then checks if it is of type <code>EnumTypeDefinition</code>.
519 * data schema node for which is checked if it is leaf and if it
521 * @return boolean value
523 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
524 * <li>false - other cases</li>
527 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
528 if (dataNode instanceof LeafSchemaNode) {
529 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
530 if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
538 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
539 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
542 * data schema node for which is checked if it is leaflist and if
544 * @return boolean value
546 * <li>true - if <code>dataNode</code> is leaflist of type
548 * <li>false - other cases</li>
551 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
552 if (dataNode instanceof LeafListSchemaNode) {
553 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
554 if (leafList.getType() instanceof EnumTypeDefinition) {
562 * Converts <code>enumTypeDef</code> to
563 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
567 * enumeration type definition which is converted to enumeration
569 * string with name which is used as the enumeration name
570 * @return enumeration type which is built with data (name, enum values)
571 * from <code>enumTypeDef</code>
572 * @throws IllegalArgumentException
574 * <li>if <code>enumTypeDef</code> equals null</li>
575 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
576 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
577 * <li>if name of <code>enumTypeDef</code> equal null</li>
580 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName, final SchemaNode parentNode) {
581 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
582 Preconditions.checkArgument(enumTypeDef.getValues() != null,
583 "EnumTypeDefinition MUST contain at least ONE value definition!");
584 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
585 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
586 "Local Name in EnumTypeDefinition QName cannot be NULL!");
588 final String enumerationName = BindingMapping.getClassName(enumName);
590 Module module = findParentModule(schemaContext, parentNode);
591 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
593 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
594 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
595 enumBuilder.setDescription(enumTypedefDescription);
596 enumBuilder.setReference(enumTypeDef.getReference());
597 enumBuilder.setModuleName(module.getName());
598 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
599 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
600 return enumBuilder.toInstance(null);
604 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
605 * taken from <code>enumTypeDef</code>.
608 * enumeration type definition is source of enumeration data for
609 * <code>typeBuilder</code>
611 * string with the name of enumeration
613 * generated type builder to which is enumeration added
614 * @return enumeration type which contains enumeration data form
615 * <code>enumTypeDef</code>
616 * @throws IllegalArgumentException
618 * <li>if <code>enumTypeDef</code> equals null</li>
619 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
620 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
621 * <li>if name of <code>enumTypeDef</code> equal null</li>
622 * <li>if name of <code>typeBuilder</code> equal null</li>
626 private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
627 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
628 Preconditions.checkArgument(enumTypeDef.getValues() != null,
629 "EnumTypeDefinition MUST contain at least ONE value definition!");
630 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
631 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
632 "Local Name in EnumTypeDefinition QName cannot be NULL!");
633 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
635 final String enumerationName = BindingMapping.getClassName(enumName);
637 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
638 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
639 enumBuilder.setDescription(enumTypedefDescription);
640 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
641 return enumBuilder.toInstance(enumBuilder);
645 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
648 * contains information about YANG type
649 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
651 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
652 Type returnType = null;
653 if (dataNode != null) {
654 if (dataNode instanceof LeafSchemaNode) {
655 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
656 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
657 returnType = javaTypeForSchemaDefinitionType(type, leaf);
658 } else if (dataNode instanceof LeafListSchemaNode) {
659 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
660 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
667 * Passes through all modules and through all its type definitions and
668 * convert it to generated types.
670 * The modules are firstly sorted by mutual dependencies. The modules are
671 * sequentially passed. All type definitions of a module are at the
672 * beginning sorted so that type definition with less amount of references
673 * to other type definition are processed first.<br />
674 * For each module is created mapping record in the map
675 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
676 * which map current module name to the map which maps type names to
677 * returned types (generated types).
680 private void resolveTypeDefsFromContext() {
681 final Set<Module> modules = schemaContext.getModules();
682 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
683 final Module[] modulesArray = new Module[modules.size()];
685 for (Module modul : modules) {
686 modulesArray[i++] = modul;
688 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
691 for (final Module module : modulesSortedByDependency) {
692 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
693 if (dateTypeMap == null) {
694 dateTypeMap = new HashMap<>();
696 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
697 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
700 for (final Module module : modulesSortedByDependency) {
701 if (module != null) {
702 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
703 if (basePackageName != null) {
704 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
705 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
706 if (listTypeDefinitions != null) {
707 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
708 typedefToGeneratedType(basePackageName, module, typedef);
718 * @param basePackageName
719 * string with name of package to which the module belongs
721 * string with the name of the module for to which the
722 * <code>typedef</code> belongs
724 * type definition of the node for which should be creted JAVA
725 * <code>Type</code> (usually generated TO)
726 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
727 * <code>null</code> value if <code>basePackageName</code> or
728 * <code>modulName</code> or <code>typedef</code> or Q name of
729 * <code>typedef</code> equals <code>null</code>
731 private Type typedefToGeneratedType(final String basePackageName, final Module module, final TypeDefinition<?> typedef) {
732 final String moduleName = module.getName();
733 final Date moduleRevision = module.getRevision();
734 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
735 final String typedefName = typedef.getQName().getLocalName();
736 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
737 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
738 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
739 Type returnType = null;
740 if (innerTypeDefinition.getBaseType() != null) {
741 returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName, module.getName());
742 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
743 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
744 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
745 genTOBuilder.setTypedef(true);
746 genTOBuilder.setIsUnion(true);
747 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
748 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
749 returnType = genTOBuilder.toInstance();
751 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
752 genTOBuilder.getName() + "Builder");
753 unionBuilder.setIsUnionBuilder(true);
754 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
755 method.setReturnType(returnType);
756 method.addParameter(Types.STRING, "defaultValue");
757 method.setAccessModifier(AccessModifier.PUBLIC);
758 method.setStatic(true);
759 Set<Type> types = additionalTypes.get(module);
761 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
762 additionalTypes.put(module, types);
764 types.add(unionBuilder.toInstance());
766 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
767 // enums are automatically Serializable
768 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
769 // TODO units for typedef enum
770 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
771 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
772 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
773 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
774 basePackageName, bitsTypeDefinition, typedefName, module.getName());
775 genTOBuilder.setTypedef(true);
776 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
777 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
778 returnType = genTOBuilder.toInstance();
780 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
781 innerTypeDefinition, typedef);
782 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
784 if (returnType != null) {
785 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
786 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
787 if (typeMap != null) {
788 if (typeMap.isEmpty()) {
789 typeMap = new HashMap<>(4);
790 modulesByDate.put(moduleRevision, typeMap);
792 typeMap.put(typedefName, returnType);
802 * Wraps base YANG type to generated TO.
804 * @param basePackageName
805 * string with name of package to which the module belongs
807 * type definition which is converted to the TO
809 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
810 * @return generated transfer object which represent<code>javaType</code>
812 private static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef, final Type javaType, final String moduleName) {
813 Preconditions.checkNotNull(javaType, "javaType cannot be null");
814 final String propertyName = "value";
816 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
817 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
818 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
819 genPropBuilder.setReturnType(javaType);
820 genTOBuilder.addEqualsIdentity(genPropBuilder);
821 genTOBuilder.addHashIdentity(genPropBuilder);
822 genTOBuilder.addToStringProperty(genPropBuilder);
823 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
824 final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
825 addStringRegExAsConstant(genTOBuilder, regExps);
827 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
828 genTOBuilder.setTypedef(true);
829 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
830 return genTOBuilder.toInstance();
834 * Converts output list of generated TO builders to one TO builder (first
835 * from list) which contains the remaining builders as its enclosing TO.
837 * @param basePackageName
838 * string with name of package to which the module belongs
840 * type definition which should be of type
841 * <code>UnionTypeDefinition</code>
843 * string with name for generated TO
844 * @return generated TO builder with the list of enclosed generated TO
847 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName, final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
848 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
849 typedef, typeDefName, parentNode);
850 GeneratedTOBuilder resultTOBuilder = null;
851 if (genTOBuilders.isEmpty()) {
852 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typedef);
855 resultTOBuilder = genTOBuilders.remove(0);
856 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
857 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
860 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
861 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
862 resultTOBuilder.addEqualsIdentity(genPropBuilder);
863 resultTOBuilder.addHashIdentity(genPropBuilder);
864 resultTOBuilder.addToStringProperty(genPropBuilder);
866 return resultTOBuilder;
870 * Converts <code>typedef</code> to generated TO with
871 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
872 * added to generated TO builder as property.
874 * @param basePackageName
875 * string with name of package to which the module belongs
877 * type definition which should be of type
878 * <code>UnionTypeDefinition</code>
880 * string with name for generated TO
881 * @return generated TO builder which represents <code>typedef</code>
882 * @throws NullPointerException
884 * <li>if <code>basePackageName</code> is null</li>
885 * <li>if <code>typedef</code> is null</li>
886 * <li>if Qname of <code>typedef</code> is null</li>
889 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName, final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
890 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
891 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
892 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
894 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
895 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
896 final Module module = findParentModule(schemaContext, parentNode);
898 final GeneratedTOBuilderImpl unionGenTOBuilder;
899 if (typeDefName != null && !typeDefName.isEmpty()) {
900 final String typeName = BindingMapping.getClassName(typeDefName);
901 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
902 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
903 unionGenTOBuilder.setDescription(typedefDescription);
904 unionGenTOBuilder.setReference(typedef.getReference());
905 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
906 unionGenTOBuilder.setModuleName(module.getName());
908 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
911 generatedTOBuilders.add(unionGenTOBuilder);
912 unionGenTOBuilder.setIsUnion(true);
913 final List<String> regularExpressions = new ArrayList<String>();
914 for (final TypeDefinition<?> unionType : unionTypes) {
915 final String unionTypeName = unionType.getQName().getLocalName();
916 if (unionType.getBaseType() != null) {
917 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, regularExpressions,
919 } else if (unionType instanceof UnionTypeDefinition) {
920 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionTypeDefinition) unionType,
921 basePackageName, parentNode));
922 } else if (unionType instanceof EnumTypeDefinition) {
923 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
924 unionTypeName, unionGenTOBuilder);
925 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
927 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
929 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
932 if (!regularExpressions.isEmpty()) {
933 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
936 storeGenTO(typedef, unionGenTOBuilder, parentNode);
938 return generatedTOBuilders;
942 * Wraps code which handle case when union subtype is also of the type
943 * <code>UnionType</code>.
945 * In this case the new generated TO is created for union subtype (recursive
947 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
948 * String, SchemaNode)}
949 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
950 * <code>parentUnionGenTOBuilder</code> is created property which type is
951 * equal to new generated TO.
953 * @param parentUnionGenTOBuilder
954 * generated TO builder to which is the property with the child
955 * union subtype added
956 * @param basePackageName
957 * string with the name of the module package
958 * @param unionSubtype
959 * type definition which represents union subtype
960 * @return list of generated TO builders. The number of the builders can be
961 * bigger one due to recursive call of
962 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
964 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
965 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
966 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
967 basePackageName, unionSubtype, newTOBuilderName, parentNode);
969 final GeneratedPropertyBuilder propertyBuilder;
970 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
971 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
972 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
973 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
975 return subUnionGenTOBUilders;
979 * Wraps code which handle case when union subtype is of the type
980 * <code>ExtendedType</code>.
982 * If TO for this type already exists it is used for the creation of the
983 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
984 * type is used for the property creation.
986 * @param parentUnionGenTOBuilder
987 * generated TO builder in which new property is created
988 * @param unionSubtype
989 * type definition of the <code>ExtendedType</code> type which
990 * represents union subtype
991 * @param regularExpressions
992 * list of strings with the regular expressions
994 * parent Schema Node for Extended Subtype
997 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final TypeDefinition<?> unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
998 final String unionTypeName = unionSubtype.getQName().getLocalName();
999 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1000 if (genTO != null) {
1001 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1003 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1004 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1005 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1007 if (javaType != null) {
1008 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1011 if (baseType instanceof StringTypeDefinition) {
1012 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
1018 * Searches for generated TO for <code>searchedTypeDef</code> type
1019 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1021 * @param searchedTypeName
1022 * string with name of <code>searchedTypeDef</code>
1023 * @return generated TO for <code>searchedTypeDef</code> or
1024 * <code>null</code> it it doesn't exist
1026 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1027 final Module typeModule = findParentModule(schemaContext, parentNode);
1028 if (typeModule != null && typeModule.getName() != null) {
1029 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1030 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1031 if (genTOs != null) {
1032 return genTOs.get(searchedTypeName);
1039 * Stores generated TO created from <code>genTOBuilder</code> for
1040 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1041 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1044 * type definition for which is <code>genTOBuilder</code> created
1045 * @param genTOBuilder
1046 * generated TO builder which is converted to generated TO and
1049 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1050 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1051 final Module parentModule = findParentModule(schemaContext, parentNode);
1052 if (parentModule != null && parentModule.getName() != null) {
1053 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1054 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1055 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1061 * Adds a new property with the name <code>propertyName</code> and with type
1062 * <code>type</code> to <code>unonGenTransObject</code>.
1064 * @param unionGenTransObject
1065 * generated TO to which should be property added
1067 * JAVA <code>type</code> of the property which should be added
1068 * to <code>unionGentransObject</code>
1069 * @param propertyName
1070 * string with name of property which should be added to
1071 * <code>unionGentransObject</code>
1073 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1074 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1075 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1076 .addProperty(BindingMapping.getPropertyName(propertyName));
1077 propBuilder.setReturnType(type);
1079 unionGenTransObject.addEqualsIdentity(propBuilder);
1080 unionGenTransObject.addHashIdentity(propBuilder);
1081 unionGenTransObject.addToStringProperty(propBuilder);
1086 * Converts <code>typedef</code> to the generated TO builder.
1088 * @param basePackageName
1089 * string with name of package to which the module belongs
1091 * type definition from which is the generated TO builder created
1092 * @return generated TO builder which contains data from
1093 * <code>typedef</code> and <code>basePackageName</code>
1095 private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef, final String moduleName) {
1097 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1098 final String typeDefTOName = typedef.getQName().getLocalName();
1100 if ((packageName != null) && (typeDefTOName != null)) {
1101 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1102 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1103 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
1105 newType.setDescription(typedefDescription);
1106 newType.setReference(typedef.getReference());
1107 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1108 newType.setModuleName(moduleName);
1116 * Converts <code>typeDef</code> which should be of the type
1117 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1119 * All the bits of the typeDef are added to returning generated TO as
1122 * @param basePackageName
1123 * string with name of package to which the module belongs
1125 * type definition from which is the generated TO builder created
1126 * @param typeDefName
1127 * string with the name for generated TO builder
1128 * @return generated TO builder which represents <code>typeDef</code>
1129 * @throws IllegalArgumentException
1131 * <li>if <code>typeDef</code> equals null</li>
1132 * <li>if <code>basePackageName</code> equals null</li>
1135 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName, final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1137 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1138 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1140 if (typeDef instanceof BitsTypeDefinition) {
1141 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1143 final String typeName = BindingMapping.getClassName(typeDefName);
1144 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1145 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1147 genTOBuilder.setDescription(typedefDescription);
1148 genTOBuilder.setReference(typeDef.getReference());
1149 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1150 genTOBuilder.setModuleName(moduleName);
1151 genTOBuilder.setBaseType(typeDef);
1153 final List<Bit> bitList = bitsTypeDefinition.getBits();
1154 GeneratedPropertyBuilder genPropertyBuilder;
1155 for (final Bit bit : bitList) {
1156 String name = bit.getName();
1157 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1158 genPropertyBuilder.setReadOnly(true);
1159 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1161 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1162 genTOBuilder.addHashIdentity(genPropertyBuilder);
1163 genTOBuilder.addToStringProperty(genPropertyBuilder);
1166 return genTOBuilder;
1172 * Converts the pattern constraints from <code>typedef</code> to the list of
1173 * the strings which represents these constraints.
1176 * extended type in which are the pattern constraints sought
1177 * @return list of strings which represents the constraint patterns
1178 * @throws IllegalArgumentException
1179 * if <code>typedef</code> equals null
1182 private static List<String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
1183 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1185 final List<PatternConstraint> patternConstraints;
1186 if (typedef instanceof ExtendedType) {
1187 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1188 if (strTypeDef instanceof StringTypeDefinition) {
1189 patternConstraints = ((ExtendedType)typedef).getPatternConstraints();
1191 patternConstraints = ImmutableList.of();
1193 } else if (typedef instanceof StringTypeDefinition) {
1194 // FIXME: run diff against base
1195 patternConstraints = ((StringTypeDefinition) typedef).getPatternConstraints();
1197 patternConstraints = ImmutableList.of();
1200 final List<String> regExps = new ArrayList<>(patternConstraints.size());
1201 for (PatternConstraint patternConstraint : patternConstraints) {
1202 final String regEx = patternConstraint.getRegularExpression();
1203 final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1204 regExps.add(modifiedRegEx);
1212 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1213 * expressions from the <code>regularExpressions</code>
1215 * @param genTOBuilder
1216 * generated TO builder to which are
1217 * <code>regular expressions</code> added
1218 * @param regularExpressions
1219 * list of string which represent regular expressions
1220 * @throws IllegalArgumentException
1222 * <li>if <code>genTOBuilder</code> equals null</li>
1223 * <li>if <code>regularExpressions</code> equals null</li>
1226 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1227 if (genTOBuilder == null) {
1228 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1230 if (regularExpressions == null) {
1231 throw new IllegalArgumentException("List of regular expressions can't be null");
1233 if (!regularExpressions.isEmpty()) {
1234 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1235 regularExpressions);
1240 * Creates generated TO with data about inner extended type
1241 * <code>innerExtendedType</code>, about the package name
1242 * <code>typedefName</code> and about the generated TO name
1243 * <code>typedefName</code>.
1245 * It is supposed that <code>innerExtendedType</code> is already present in
1246 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1247 * be possible set it as extended type for the returning generated TO.
1251 * @param innerExtendedType
1252 * extended type which is part of some other extended type
1253 * @param basePackageName
1254 * string with the package name of the module
1257 * @return generated TO which extends generated TO for
1258 * <code>innerExtendedType</code>
1259 * @throws IllegalArgumentException
1261 * <li>if <code>extendedType</code> equals null</li>
1262 * <li>if <code>basePackageName</code> equals null</li>
1263 * <li>if <code>typedefName</code> equals null</li>
1266 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef, final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1267 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1268 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1270 final String typedefName = typedef.getQName().getLocalName();
1271 final String classTypedefName = BindingMapping.getClassName(typedefName);
1272 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1273 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1274 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
1276 genTOBuilder.setDescription(typedefDescription);
1277 genTOBuilder.setReference(typedef.getReference());
1278 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1279 genTOBuilder.setModuleName(moduleName);
1280 genTOBuilder.setTypedef(true);
1281 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1282 genTOBuilder.setRestrictions(r);
1284 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1285 genTOBuilder.setIsUnion(true);
1288 Map<Date, Map<String, Type>> modulesByDate = null;
1289 Map<String, Type> typeMap = null;
1290 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1291 if (parentModule != null) {
1292 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1293 typeMap = modulesByDate.get(parentModule.getRevision());
1296 if (typeMap != null) {
1297 Type type = typeMap.get(innerTypeDef);
1298 if (type instanceof GeneratedTransferObject) {
1299 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1302 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1303 makeSerializable(genTOBuilder);
1305 return genTOBuilder.toInstance();
1309 * Add {@link Serializable} to implemented interfaces of this TO. Also
1310 * compute and add serialVersionUID property.
1313 * transfer object which needs to be serializable
1315 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1316 gto.addImplementsType(Types.typeForClass(Serializable.class));
1317 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1318 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1323 * Finds out for each type definition how many immersion (depth) is
1324 * necessary to get to the base type. Every type definition is inserted to
1325 * the map which key is depth and value is list of type definitions with
1326 * equal depth. In next step are lists from this map concatenated to one
1327 * list in ascending order according to their depth. All type definitions
1328 * are in the list behind all type definitions on which depends.
1330 * @param unsortedTypeDefinitions
1331 * list of type definitions which should be sorted by depth
1332 * @return list of type definitions sorted according their each other
1333 * dependencies (type definitions which are depend on other type
1334 * definitions are in list behind them).
1336 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1337 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1338 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1340 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1341 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1342 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1343 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1344 if (typeDefinitionsConcreteDepth == null) {
1345 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1346 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1348 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1351 // SortedMap guarantees order corresponding to keys in ascending order
1352 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1353 sortedTypeDefinition.addAll(v);
1356 return sortedTypeDefinition;
1360 * Returns how many immersion is necessary to get from the type definition
1363 * @param typeDefinition
1364 * type definition for which is depth sought.
1365 * @return number of immersions which are necessary to get from the type
1366 * definition to the base type
1368 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1369 // FIXME: rewrite this in a non-recursive manner, without ExtendedType and UnionType
1370 if (typeDefinition == null) {
1373 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1374 if (baseType == null) {
1379 if (baseType.getBaseType() != null) {
1380 depth = depth + getTypeDefinitionDepth(baseType);
1381 } else if (baseType instanceof UnionTypeDefinition) {
1382 List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1383 int maxChildDepth = 0;
1385 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1386 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1387 if (childDepth > maxChildDepth) {
1388 maxChildDepth = childDepth;
1391 return maxChildDepth;
1397 * Returns string which contains the same value as <code>name</code> but
1398 * integer suffix is incremented by one. If <code>name</code> contains no
1399 * number suffix then number 1 is added.
1402 * string with name of augmented node
1403 * @return string with the number suffix incremented by one (or 1 is added)
1405 private static String provideAvailableNameForGenTOBuilder(final String name) {
1406 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1408 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1409 return name.substring(0, mtch.start()) + newSuffix;
1415 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1416 if (!Strings.isNullOrEmpty(units)) {
1417 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1418 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1419 prop.setReturnType(Types.STRING);
1420 to.addToStringProperty(prop);
1425 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1426 return getTypeDefaultConstruction(node, node.getDefault());
1429 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1430 TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1431 QName typeQName = type.getQName();
1432 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1433 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1434 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1437 StringBuilder sb = new StringBuilder();
1438 String result = null;
1439 if (base instanceof BinaryTypeDefinition) {
1440 result = binaryToDef(defaultValue);
1441 } else if (base instanceof BitsTypeDefinition) {
1444 Module parent = getParentModule(node);
1445 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1447 if (!(path.hasNext())) {
1448 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1449 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1450 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1452 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1453 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1454 parentName = BindingMapping.getClassName(parent.getName());
1455 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1457 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1458 } else if (base instanceof BooleanTypeDefinition) {
1459 result = typeToDef(Boolean.class, defaultValue);
1460 } else if (base instanceof DecimalTypeDefinition) {
1461 result = typeToDef(BigDecimal.class, defaultValue);
1462 } else if (base instanceof EmptyTypeDefinition) {
1463 result = typeToDef(Boolean.class, defaultValue);
1464 } else if (base instanceof EnumTypeDefinition) {
1465 char[] defValArray = defaultValue.toCharArray();
1466 char first = Character.toUpperCase(defaultValue.charAt(0));
1467 defValArray[0] = first;
1468 String newDefVal = new String(defValArray);
1470 if (type.getBaseType() != null) {
1471 Module m = getParentModule(type);
1472 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1473 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1474 className = packageName + "." + BindingMapping.getClassName(typeQName);
1476 Module parentModule = getParentModule(node);
1477 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1478 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1479 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1481 result = className + "." + newDefVal;
1482 } else if (base instanceof IdentityrefTypeDefinition) {
1483 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1484 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1485 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1486 } else if (BaseTypes.isInt8(base)) {
1487 result = typeToDef(Byte.class, defaultValue);
1488 } else if (BaseTypes.isInt16(base)) {
1489 result = typeToDef(Short.class, defaultValue);
1490 } else if (BaseTypes.isInt32(base)) {
1491 result = typeToDef(Integer.class, defaultValue);
1492 } else if (BaseTypes.isInt64(base)) {
1493 result = typeToDef(Long.class, defaultValue);
1494 } else if (base instanceof LeafrefTypeDefinition) {
1495 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1496 } else if (base instanceof StringTypeDefinition) {
1497 result = "\"" + defaultValue + "\"";
1498 } else if (BaseTypes.isUint8(base)) {
1499 result = typeToDef(Short.class, defaultValue);
1500 } else if (BaseTypes.isUint16(base)) {
1501 result = typeToDef(Integer.class, defaultValue);
1502 } else if (BaseTypes.isUint32(base)) {
1503 result = typeToDef(Long.class, defaultValue);
1504 } else if (BaseTypes.isUint64(base)) {
1505 result = typeToDef(BigInteger.class, defaultValue);
1506 } else if (base instanceof UnionTypeDefinition) {
1507 result = unionToDef(node);
1513 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1514 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1515 Module m = getParentModule(type);
1516 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1517 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1518 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1519 sb.insert(0, "new " + className + "(");
1520 sb.insert(sb.length(), ')');
1523 return sb.toString();
1526 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1527 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1530 private static String binaryToDef(final String defaultValue) {
1531 StringBuilder sb = new StringBuilder();
1532 BaseEncoding en = BaseEncoding.base64();
1533 byte[] encoded = en.decode(defaultValue);
1534 sb.append("new byte[] {");
1535 for (int i = 0; i < encoded.length; i++) {
1536 sb.append(encoded[i]);
1537 if (i != encoded.length - 1) {
1542 return sb.toString();
1545 private static final Comparator<Bit> BIT_NAME_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
1547 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1548 List<Bit> bits = new ArrayList<>(type.getBits());
1549 Collections.sort(bits, BIT_NAME_COMPARATOR);
1550 StringBuilder sb = new StringBuilder();
1553 sb.append(className);
1556 for (int i = 0; i < bits.size(); i++) {
1557 if (bits.get(i).getName().equals(defaultValue)) {
1562 if (i != bits.size() - 1) {
1569 return sb.toString();
1572 private Module getParentModule(final SchemaNode node) {
1573 QName qname = node.getPath().getPathFromRoot().iterator().next();
1574 URI namespace = qname.getNamespace();
1575 Date revision = qname.getRevision();
1576 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1579 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1580 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1581 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1582 "The Path Statement for Leafref Type Definition cannot be NULL!");
1584 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1585 final String strXPath = xpath.toString();
1587 if (strXPath != null) {
1588 if (strXPath.indexOf('[') == -1) {
1589 final Module module = findParentModule(schemaContext, parentNode);
1590 if (module != null) {
1591 final SchemaNode dataNode;
1592 if (xpath.isAbsolute()) {
1593 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1595 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1597 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1601 return "new java.lang.Object()";
1608 private String unionToDef(final LeafSchemaNode node) {
1609 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1613 if (type.getBaseType() != null) {
1614 QName typeQName = type.getQName();
1615 Module module = null;
1616 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1617 if (modules.size() > 1) {
1618 for (Module m : modules) {
1619 if (m.getRevision().equals(typeQName.getRevision())) {
1624 if (module == null) {
1625 List<Module> modulesList = new ArrayList<>(modules);
1626 Collections.sort(modulesList, (o1, o2) -> o1.getRevision().compareTo(o2.getRevision()));
1627 module = modulesList.get(0);
1630 module = modules.iterator().next();
1633 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1634 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1636 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1637 QName first = path.next();
1638 if (!(path.hasNext())) {
1639 URI namespace = first.getNamespace();
1640 Date revision = first.getRevision();
1641 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1642 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1643 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1644 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1646 URI namespace = first.getNamespace();
1647 Date revision = first.getRevision();
1648 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1649 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1651 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
1652 // the case, as unions are emitted to their correct schema path. Create a proxy instance to meet the
1653 // codepath's expectations
1654 final SchemaPath typePath;
1655 if (type instanceof UnionType) {
1656 typePath = type.getPath();
1658 typePath = UnionType.create(((UnionTypeDefinition)type).getTypes()).getPath();
1661 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typePath);
1662 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1665 return union(className, node.getDefault(), node);
1668 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1669 StringBuilder sb = new StringBuilder();
1671 sb.append(className);
1673 sb.append(defaultValue);
1674 sb.append("\".toCharArray())");
1675 return sb.toString();
1679 public String getConstructorPropertyName(final SchemaNode node) {
1680 if (node instanceof TypeDefinition<?>) {
1688 public String getParamNameFromType(final TypeDefinition<?> type) {
1689 return BindingMapping.getPropertyName(type.getQName().getLocalName());