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.yang.model.util.SchemaContextUtil.findDataSchemaNode;
11 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
12 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.Sets;
17 import com.google.common.io.BaseEncoding;
18 import java.io.Serializable;
19 import java.math.BigDecimal;
20 import java.math.BigInteger;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
32 import java.util.TreeMap;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35 import org.apache.commons.lang3.StringEscapeUtils;
36 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
37 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
38 import org.opendaylight.yangtools.binding.generator.util.Types;
39 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
40 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
41 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
42 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
43 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
44 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
45 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
46 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty;
47 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
48 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
49 import org.opendaylight.yangtools.sal.binding.model.api.Type;
50 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
51 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
53 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
54 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
55 import org.opendaylight.yangtools.yang.binding.BindingMapping;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
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.Decimal64;
82 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
83 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
84 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
85 import org.opendaylight.yangtools.yang.model.util.StringType;
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,
191 final Restrictions r) {
192 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
193 Preconditions.checkArgument(typeDefinition.getQName() != null,
194 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
195 String typedefName = typeDefinition.getQName().getLocalName();
196 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
198 // Deal with leafrefs/identityrefs first
199 Type returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
200 if (returnType != null) {
204 // Now deal with base types
205 if (typeDefinition.getBaseType() == null) {
206 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
207 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
208 // a base type which holds these constraints -- and the class is not a Decimal64.
209 if (typeDefinition instanceof DecimalTypeDefinition && !(typeDefinition instanceof Decimal64)) {
210 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
214 if (returnType == null) {
215 // FIXME: it looks as though we could be using the same codepath as above...
216 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
220 if (returnType == null) {
221 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
224 // FIXME: what about base types with restrictions?
228 returnType = javaTypeForExtendedType(typeDefinition);
229 if (r != null && returnType instanceof GeneratedTransferObject) {
230 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
231 Module module = findParentModule(schemaContext, parentNode);
232 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
233 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
234 typeDefinition.getPath());
235 String genTOName = BindingMapping.getClassName(typedefName);
236 String name = packageName + "." + genTOName;
237 if (!(returnType.getFullyQualifiedName().equals(name))) {
238 returnType = shadedTOWithRestrictions(gto, r);
244 private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
245 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
246 GeneratedTransferObject parent = gto.getSuperType();
247 if (parent != null) {
248 gtob.setExtendsType(parent);
250 gtob.setRestrictions(r);
251 for (GeneratedProperty gp : gto.getProperties()) {
252 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
253 gpb.setValue(gp.getValue());
254 gpb.setReadOnly(gp.isReadOnly());
255 gpb.setAccessModifier(gp.getAccessModifier());
256 gpb.setReturnType(gp.getReturnType());
257 gpb.setFinal(gp.isFinal());
258 gpb.setStatic(gp.isStatic());
260 return gtob.toInstance();
263 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
264 final SchemaNode leafRefValueNode;
265 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
266 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
267 .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute());
269 ///// skip leafrefs in augments - they're checked once augments are resolved
270 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
271 boolean isAugmenting = false;
272 DataNodeContainer current = null;
273 DataSchemaNode dataChildByName;
275 while (iterator.hasNext() && !isAugmenting) {
276 final QName next = iterator.next();
277 if (current == null) {
278 dataChildByName = schemaContext.getDataChildByName(next);
280 dataChildByName = current.getDataChildByName(next);
282 if (dataChildByName != null) {
283 isAugmenting = dataChildByName.isAugmenting();
287 if (dataChildByName instanceof DataNodeContainer) {
288 current = (DataNodeContainer) dataChildByName;
296 Module parentModule = getParentModule(parentNode);
297 if (!leafRefStrippedXPath.isAbsolute()) {
298 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
299 parentNode, leafRefStrippedXPath);
301 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
303 return (leafRefValueNode != null) ? leafRefValueNode.equals(parentNode) : false;
307 * Returns JAVA <code>Type</code> for instances of the type
308 * <code>LeafrefTypeDefinition</code> or
309 * <code>IdentityrefTypeDefinition</code>.
311 * @param typeDefinition
312 * type definition which is converted to JAVA <code>Type</code>
313 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
315 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
316 if (typeDefinition instanceof LeafrefTypeDefinition) {
317 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
318 if (isLeafRefSelfReference(leafref, parentNode)) {
319 throw new YangValidationException("Leafref " + leafref.toString() + " is referencing itself, incoming" +
320 " StackOverFlowError detected.");
322 return provideTypeForLeafref(leafref, parentNode);
323 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
324 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
325 return provideTypeForIdentityref(idref);
332 * Returns JAVA <code>Type</code> for instances of the type
333 * <code>ExtendedType</code>.
335 * @param typeDefinition
336 * type definition which is converted to JAVA <code>Type</code>
337 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
339 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
340 final String typedefName = typeDefinition.getQName().getLocalName();
341 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
342 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
343 if (returnType == null) {
344 if (baseTypeDef instanceof EnumTypeDefinition) {
345 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
346 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
348 final Module module = findParentModule(schemaContext, typeDefinition);
349 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
350 if (module != null) {
351 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
352 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
353 if (genTOs != null) {
354 returnType = genTOs.get(typedefName);
356 if (returnType == null) {
357 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
358 baseTypeDef, typeDefinition, r);
367 * Seeks for identity reference <code>idref</code> the JAVA
368 * <code>type</code>.<br />
372 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
373 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
376 * identityref type definition for which JAVA <code>Type</code>
378 * @return JAVA <code>Type</code> of the identity which is refrenced through
381 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
382 QName baseIdQName = idref.getIdentity().getQName();
383 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
384 baseIdQName.getRevision());
385 IdentitySchemaNode identity = null;
386 for (IdentitySchemaNode id : module.getIdentities()) {
387 if (id.getQName().equals(baseIdQName)) {
391 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
393 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
394 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath());
395 final String genTypeName = BindingMapping.getClassName(identity.getQName());
397 Type baseType = Types.typeForClass(Class.class);
398 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
399 return Types.parameterizedTypeFor(baseType, paramType);
403 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
405 * @param typeDefinition
406 * type definition which should be converted to JAVA
408 * @return JAVA <code>Type</code> which represents
409 * <code>typeDefinition</code>
410 * @throws IllegalArgumentException
412 * <li>if <code>typeDefinition</code> equal null</li>
413 * <li>if Q name of <code>typeDefinition</code></li>
414 * <li>if name of <code>typeDefinition</code></li>
417 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
418 final SchemaNode parentNode) {
419 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
420 if (typeDefinition.getQName() == null) {
421 throw new IllegalArgumentException(
422 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
424 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
425 "Type Definitions Local Name cannot be NULL!");
427 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
428 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
429 final Module module = findParentModule(schemaContext, parentNode);
431 if (module != null) {
432 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
433 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
434 if (genTOs != null) {
435 return genTOs.get(typeDefinition.getQName().getLocalName());
443 * Gets base type definition for <code>extendTypeDef</code>. The method is
444 * recursively called until non <code>ExtendedType</code> type is found.
446 * @param extendTypeDef
447 * type definition for which is the base type definition sought
448 * @return type definition which is base type for <code>extendTypeDef</code>
449 * @throws IllegalArgumentException
450 * if <code>extendTypeDef</code> equal null
452 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
453 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
455 TypeDefinition<?> ret = extendTypeDef;
456 while (ret.getBaseType() != null) {
457 ret = ret.getBaseType();
464 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
466 * The path of <code>leafrefType</code> is followed to find referenced node
467 * and its <code>Type</code> is returned.
470 * leafref type definition for which is the type sought
471 * @return JAVA <code>Type</code> of data schema node which is referenced in
472 * <code>leafrefType</code>
473 * @throws IllegalArgumentException
475 * <li>if <code>leafrefType</code> equal null</li>
476 * <li>if path statement of <code>leafrefType</code> equal null</li>
480 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
481 Type returnType = null;
482 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
484 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
485 "The Path Statement for Leafref Type Definition cannot be NULL!");
487 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
488 final String strXPath = xpath.toString();
490 if (strXPath != null) {
491 if (strXPath.indexOf('[') == -1) {
492 final Module module = findParentModule(schemaContext, parentNode);
493 if (module != null) {
494 final SchemaNode dataNode;
495 if (xpath.isAbsolute()) {
496 dataNode = findDataSchemaNode(schemaContext, module, xpath);
498 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
501 if (leafContainsEnumDefinition(dataNode)) {
502 returnType = referencedTypes.get(dataNode.getPath());
503 } else if (leafListContainsEnumDefinition(dataNode)) {
504 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
506 returnType = resolveTypeFromDataSchemaNode(dataNode);
510 returnType = Types.typeForClass(Object.class);
513 if (returnType == null) {
514 throw new IllegalArgumentException("Failed to find leafref target: " + strXPath);
520 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
521 * so then checks if it is of type <code>EnumTypeDefinition</code>.
524 * data schema node for which is checked if it is leaf and if it
526 * @return boolean value
528 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
529 * <li>false - other cases</li>
532 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
533 if (dataNode instanceof LeafSchemaNode) {
534 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
535 if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
543 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
544 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
547 * data schema node for which is checked if it is leaflist and if
549 * @return boolean value
551 * <li>true - if <code>dataNode</code> is leaflist of type
553 * <li>false - other cases</li>
556 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
557 if (dataNode instanceof LeafListSchemaNode) {
558 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
559 if (leafList.getType() instanceof EnumTypeDefinition) {
567 * Converts <code>enumTypeDef</code> to
568 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
572 * enumeration type definition which is converted to enumeration
574 * string with name which is used as the enumeration name
575 * @return enumeration type which is built with data (name, enum values)
576 * from <code>enumTypeDef</code>
577 * @throws IllegalArgumentException
579 * <li>if <code>enumTypeDef</code> equals null</li>
580 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
581 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
582 * <li>if name of <code>enumTypeDef</code> equal null</li>
585 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
586 final SchemaNode parentNode) {
587 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
588 Preconditions.checkArgument(enumTypeDef.getValues() != null,
589 "EnumTypeDefinition MUST contain at least ONE value definition!");
590 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
591 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
592 "Local Name in EnumTypeDefinition QName cannot be NULL!");
594 final String enumerationName = BindingMapping.getClassName(enumName);
596 Module module = findParentModule(schemaContext, parentNode);
597 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
599 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
600 enumBuilder.setDescription(enumTypeDef.getDescription());
601 enumBuilder.setReference(enumTypeDef.getReference());
602 enumBuilder.setModuleName(module.getName());
603 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
604 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
605 return enumBuilder.toInstance(null);
609 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
610 * taken from <code>enumTypeDef</code>.
613 * enumeration type definition is source of enumeration data for
614 * <code>typeBuilder</code>
616 * string with the name of enumeration
618 * generated type builder to which is enumeration added
619 * @return enumeration type which contains enumeration data form
620 * <code>enumTypeDef</code>
621 * @throws IllegalArgumentException
623 * <li>if <code>enumTypeDef</code> equals null</li>
624 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
625 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
626 * <li>if name of <code>enumTypeDef</code> equal null</li>
627 * <li>if name of <code>typeBuilder</code> equal null</li>
631 private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
632 final GeneratedTypeBuilderBase<?> typeBuilder) {
633 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
634 Preconditions.checkArgument(enumTypeDef.getValues() != null,
635 "EnumTypeDefinition MUST contain at least ONE value definition!");
636 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
637 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
638 "Local Name in EnumTypeDefinition QName cannot be NULL!");
639 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
641 final String enumerationName = BindingMapping.getClassName(enumName);
643 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
644 enumBuilder.setDescription(enumTypeDef.getDescription());
645 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
646 return enumBuilder.toInstance(enumBuilder);
650 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
653 * contains information about YANG type
654 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
656 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
657 Type returnType = null;
658 if (dataNode != null) {
659 if (dataNode instanceof LeafSchemaNode) {
660 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
661 returnType = javaTypeForSchemaDefinitionType(CompatUtils.compatLeafType(leaf), leaf);
662 } else if (dataNode instanceof LeafListSchemaNode) {
663 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
664 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
671 * Passes through all modules and through all its type definitions and
672 * convert it to generated types.
674 * The modules are firstly sorted by mutual dependencies. The modules are
675 * sequentially passed. All type definitions of a module are at the
676 * beginning sorted so that type definition with less amount of references
677 * to other type definition are processed first.<br />
678 * For each module is created mapping record in the map
679 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
680 * which map current module name to the map which maps type names to
681 * returned types (generated types).
684 private void resolveTypeDefsFromContext() {
685 final Set<Module> modules = schemaContext.getModules();
686 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
687 final Module[] modulesArray = new Module[modules.size()];
689 for (Module modul : modules) {
690 modulesArray[i++] = modul;
692 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
695 for (final Module module : modulesSortedByDependency) {
696 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
697 if (dateTypeMap == null) {
698 dateTypeMap = new HashMap<>();
700 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
701 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
704 for (final Module module : modulesSortedByDependency) {
705 if (module != null) {
706 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
707 if (basePackageName != null) {
708 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
709 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
710 if (listTypeDefinitions != null) {
711 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
712 typedefToGeneratedType(basePackageName, module, typedef);
722 * @param basePackageName
723 * string with name of package to which the module belongs
725 * string with the name of the module for to which the
726 * <code>typedef</code> belongs
728 * type definition of the node for which should be creted JAVA
729 * <code>Type</code> (usually generated TO)
730 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
731 * <code>null</code> value if <code>basePackageName</code> or
732 * <code>modulName</code> or <code>typedef</code> or Q name of
733 * <code>typedef</code> equals <code>null</code>
735 private Type typedefToGeneratedType(final String basePackageName, final Module module,
736 final TypeDefinition<?> typedef) {
737 final String moduleName = module.getName();
738 final Date moduleRevision = module.getRevision();
739 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
740 final String typedefName = typedef.getQName().getLocalName();
741 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
742 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
743 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
744 Type returnType = null;
745 if (innerTypeDefinition.getBaseType() != null) {
746 returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName,
748 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
749 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
750 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
751 genTOBuilder.setTypedef(true);
752 genTOBuilder.setIsUnion(true);
753 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
754 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
755 returnType = genTOBuilder.toInstance();
757 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
758 genTOBuilder.getName() + "Builder");
759 unionBuilder.setIsUnionBuilder(true);
760 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
761 method.setReturnType(returnType);
762 method.addParameter(Types.STRING, "defaultValue");
763 method.setAccessModifier(AccessModifier.PUBLIC);
764 method.setStatic(true);
765 Set<Type> types = additionalTypes.get(module);
767 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
768 additionalTypes.put(module, types);
770 types.add(unionBuilder.toInstance());
772 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
773 // enums are automatically Serializable
774 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
775 // TODO units for typedef enum
776 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
777 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
778 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
779 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
780 basePackageName, bitsTypeDefinition, typedefName, module.getName());
781 genTOBuilder.setTypedef(true);
782 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
783 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
784 returnType = genTOBuilder.toInstance();
786 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
787 innerTypeDefinition, typedef);
788 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
790 if (returnType != null) {
791 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
792 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
793 if (typeMap != null) {
794 if (typeMap.isEmpty()) {
795 typeMap = new HashMap<>(4);
796 modulesByDate.put(moduleRevision, typeMap);
798 typeMap.put(typedefName, returnType);
808 * Wraps base YANG type to generated TO.
810 * @param basePackageName
811 * string with name of package to which the module belongs
813 * type definition which is converted to the TO
815 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
816 * @return generated transfer object which represent<code>javaType</code>
818 private static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
819 final Type javaType, final String moduleName) {
820 Preconditions.checkNotNull(javaType, "javaType cannot be null");
821 final String propertyName = "value";
823 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
824 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
825 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
826 genPropBuilder.setReturnType(javaType);
827 genTOBuilder.addEqualsIdentity(genPropBuilder);
828 genTOBuilder.addHashIdentity(genPropBuilder);
829 genTOBuilder.addToStringProperty(genPropBuilder);
830 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
831 final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
832 addStringRegExAsConstant(genTOBuilder, regExps);
834 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
835 genTOBuilder.setTypedef(true);
836 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
837 return genTOBuilder.toInstance();
841 * Converts output list of generated TO builders to one TO builder (first
842 * from list) which contains the remaining builders as its enclosing TO.
844 * @param basePackageName
845 * string with name of package to which the module belongs
847 * type definition which should be of type
848 * <code>UnionTypeDefinition</code>
850 * string with name for generated TO
851 * @return generated TO builder with the list of enclosed generated TO
854 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
855 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
856 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
857 typedef, typeDefName, parentNode);
858 GeneratedTOBuilder resultTOBuilder = null;
859 if (genTOBuilders.isEmpty()) {
860 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typedef);
863 resultTOBuilder = genTOBuilders.remove(0);
864 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
865 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
868 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
869 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
870 resultTOBuilder.addEqualsIdentity(genPropBuilder);
871 resultTOBuilder.addHashIdentity(genPropBuilder);
872 resultTOBuilder.addToStringProperty(genPropBuilder);
874 return resultTOBuilder;
878 * Converts <code>typedef</code> to generated TO with
879 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
880 * added to generated TO builder as property.
882 * @param basePackageName
883 * string with name of package to which the module belongs
885 * type definition which should be of type
886 * <code>UnionTypeDefinition</code>
888 * string with name for generated TO
889 * @return generated TO builder which represents <code>typedef</code>
890 * @throws NullPointerException
892 * <li>if <code>basePackageName</code> is null</li>
893 * <li>if <code>typedef</code> is null</li>
894 * <li>if Qname of <code>typedef</code> is null</li>
897 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
898 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
899 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
900 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
901 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
903 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
904 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
905 final Module module = findParentModule(schemaContext, parentNode);
907 final GeneratedTOBuilderImpl unionGenTOBuilder;
908 if (typeDefName != null && !typeDefName.isEmpty()) {
909 final String typeName = BindingMapping.getClassName(typeDefName);
910 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
911 unionGenTOBuilder.setDescription(typedef.getDescription());
912 unionGenTOBuilder.setReference(typedef.getReference());
913 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
914 unionGenTOBuilder.setModuleName(module.getName());
916 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
919 generatedTOBuilders.add(unionGenTOBuilder);
920 unionGenTOBuilder.setIsUnion(true);
921 final List<String> regularExpressions = new ArrayList<String>();
922 for (final TypeDefinition<?> unionType : unionTypes) {
923 final String unionTypeName = unionType.getQName().getLocalName();
924 if (unionType.getBaseType() != null) {
925 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, regularExpressions,
927 } else if (unionType instanceof UnionTypeDefinition) {
928 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionTypeDefinition) unionType,
929 basePackageName, parentNode));
930 } else if (unionType instanceof EnumTypeDefinition) {
931 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
932 unionTypeName, unionGenTOBuilder);
933 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
935 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
937 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
940 if (!regularExpressions.isEmpty()) {
941 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
944 storeGenTO(typedef, unionGenTOBuilder, parentNode);
946 return generatedTOBuilders;
950 * Wraps code which handle case when union subtype is also of the type
951 * <code>UnionType</code>.
953 * In this case the new generated TO is created for union subtype (recursive
955 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
956 * String, SchemaNode)}
957 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
958 * <code>parentUnionGenTOBuilder</code> is created property which type is
959 * equal to new generated TO.
961 * @param parentUnionGenTOBuilder
962 * generated TO builder to which is the property with the child
963 * union subtype added
964 * @param basePackageName
965 * string with the name of the module package
966 * @param unionSubtype
967 * type definition which represents union subtype
968 * @return list of generated TO builders. The number of the builders can be
969 * bigger one due to recursive call of
970 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
972 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
973 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
974 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
975 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
976 basePackageName, unionSubtype, newTOBuilderName, parentNode);
978 final GeneratedPropertyBuilder propertyBuilder;
979 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
980 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
981 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
982 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
984 return subUnionGenTOBUilders;
988 * Wraps code which handle case when union subtype is of the type
989 * <code>ExtendedType</code>.
991 * If TO for this type already exists it is used for the creation of the
992 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
993 * type is used for the property creation.
995 * @param parentUnionGenTOBuilder
996 * generated TO builder in which new property is created
997 * @param unionSubtype
998 * type definition of the <code>ExtendedType</code> type which
999 * represents union subtype
1000 * @param regularExpressions
1001 * list of strings with the regular expressions
1003 * parent Schema Node for Extended Subtype
1006 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1007 final TypeDefinition<?> unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
1008 final String unionTypeName = unionSubtype.getQName().getLocalName();
1009 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1010 if (genTO != null) {
1011 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1013 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1014 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1015 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1017 if (javaType != null) {
1018 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1021 if (baseType instanceof StringType) {
1022 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
1028 * Searches for generated TO for <code>searchedTypeDef</code> type
1029 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1031 * @param searchedTypeName
1032 * string with name of <code>searchedTypeDef</code>
1033 * @return generated TO for <code>searchedTypeDef</code> or
1034 * <code>null</code> it it doesn't exist
1036 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1037 final Module typeModule = findParentModule(schemaContext, parentNode);
1038 if (typeModule != null && typeModule.getName() != null) {
1039 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1040 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1041 if (genTOs != null) {
1042 return genTOs.get(searchedTypeName);
1049 * Stores generated TO created from <code>genTOBuilder</code> for
1050 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1051 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1054 * type definition for which is <code>genTOBuilder</code> created
1055 * @param genTOBuilder
1056 * generated TO builder which is converted to generated TO and
1059 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1060 final SchemaNode parentNode) {
1061 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1062 final Module parentModule = findParentModule(schemaContext, parentNode);
1063 if (parentModule != null && parentModule.getName() != null) {
1064 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1065 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1066 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1072 * Adds a new property with the name <code>propertyName</code> and with type
1073 * <code>type</code> to <code>unonGenTransObject</code>.
1075 * @param unionGenTransObject
1076 * generated TO to which should be property added
1078 * JAVA <code>type</code> of the property which should be added
1079 * to <code>unionGentransObject</code>
1080 * @param propertyName
1081 * string with name of property which should be added to
1082 * <code>unionGentransObject</code>
1084 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1085 final String propertyName) {
1086 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1087 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1088 .addProperty(BindingMapping.getPropertyName(propertyName));
1089 propBuilder.setReturnType(type);
1091 unionGenTransObject.addEqualsIdentity(propBuilder);
1092 unionGenTransObject.addHashIdentity(propBuilder);
1093 unionGenTransObject.addToStringProperty(propBuilder);
1098 * Converts <code>typedef</code> to the generated TO builder.
1100 * @param basePackageName
1101 * string with name of package to which the module belongs
1103 * type definition from which is the generated TO builder created
1104 * @return generated TO builder which contains data from
1105 * <code>typedef</code> and <code>basePackageName</code>
1107 private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName,
1108 final TypeDefinition<?> typedef, final String moduleName) {
1110 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1111 final String typeDefTOName = typedef.getQName().getLocalName();
1113 if ((packageName != null) && (typeDefTOName != null)) {
1114 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1115 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1117 newType.setDescription(typedef.getDescription());
1118 newType.setReference(typedef.getReference());
1119 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1120 newType.setModuleName(moduleName);
1128 * Converts <code>typeDef</code> which should be of the type
1129 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1131 * All the bits of the typeDef are added to returning generated TO as
1134 * @param basePackageName
1135 * string with name of package to which the module belongs
1137 * type definition from which is the generated TO builder created
1138 * @param typeDefName
1139 * string with the name for generated TO builder
1140 * @return generated TO builder which represents <code>typeDef</code>
1141 * @throws IllegalArgumentException
1143 * <li>if <code>typeDef</code> equals null</li>
1144 * <li>if <code>basePackageName</code> equals null</li>
1147 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1148 final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1150 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1151 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1153 if (typeDef instanceof BitsTypeDefinition) {
1154 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1156 final String typeName = BindingMapping.getClassName(typeDefName);
1157 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1159 genTOBuilder.setDescription(typeDef.getDescription());
1160 genTOBuilder.setReference(typeDef.getReference());
1161 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1162 genTOBuilder.setModuleName(moduleName);
1163 genTOBuilder.setBaseType(typeDef);
1165 final List<Bit> bitList = bitsTypeDefinition.getBits();
1166 GeneratedPropertyBuilder genPropertyBuilder;
1167 for (final Bit bit : bitList) {
1168 String name = bit.getName();
1169 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1170 genPropertyBuilder.setReadOnly(true);
1171 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1173 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1174 genTOBuilder.addHashIdentity(genPropertyBuilder);
1175 genTOBuilder.addToStringProperty(genPropertyBuilder);
1178 return genTOBuilder;
1184 * Converts the pattern constraints from <code>typedef</code> to the list of
1185 * the strings which represents these constraints.
1188 * extended type in which are the pattern constraints sought
1189 * @return list of strings which represents the constraint patterns
1190 * @throws IllegalArgumentException
1191 * if <code>typedef</code> equals null
1194 private static List<String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
1195 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1197 final List<PatternConstraint> patternConstraints;
1198 if (typedef instanceof ExtendedType) {
1199 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1200 if (strTypeDef instanceof StringType) {
1201 patternConstraints = ((ExtendedType)typedef).getPatternConstraints();
1203 patternConstraints = ImmutableList.of();
1205 } else if (typedef instanceof StringTypeDefinition) {
1206 // FIXME: run diff against base
1207 patternConstraints = ((StringTypeDefinition) typedef).getPatternConstraints();
1209 patternConstraints = ImmutableList.of();
1212 final List<String> regExps = new ArrayList<>(patternConstraints.size());
1213 for (PatternConstraint patternConstraint : patternConstraints) {
1214 final String regEx = patternConstraint.getRegularExpression();
1215 final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1216 regExps.add(modifiedRegEx);
1224 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1225 * expressions from the <code>regularExpressions</code>
1227 * @param genTOBuilder
1228 * generated TO builder to which are
1229 * <code>regular expressions</code> added
1230 * @param regularExpressions
1231 * list of string which represent regular expressions
1232 * @throws IllegalArgumentException
1234 * <li>if <code>genTOBuilder</code> equals null</li>
1235 * <li>if <code>regularExpressions</code> equals null</li>
1238 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1239 if (genTOBuilder == null) {
1240 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1242 if (regularExpressions == null) {
1243 throw new IllegalArgumentException("List of regular expressions can't be null");
1245 if (!regularExpressions.isEmpty()) {
1246 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1247 regularExpressions);
1252 * Creates generated TO with data about inner extended type
1253 * <code>innerExtendedType</code>, about the package name
1254 * <code>typedefName</code> and about the generated TO name
1255 * <code>typedefName</code>.
1257 * It is supposed that <code>innerExtendedType</code> is already present in
1258 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1259 * be possible set it as extended type for the returning generated TO.
1263 * @param innerExtendedType
1264 * extended type which is part of some other extended type
1265 * @param basePackageName
1266 * string with the package name of the module
1269 * @return generated TO which extends generated TO for
1270 * <code>innerExtendedType</code>
1271 * @throws IllegalArgumentException
1273 * <li>if <code>extendedType</code> equals null</li>
1274 * <li>if <code>basePackageName</code> equals null</li>
1275 * <li>if <code>typedefName</code> equals null</li>
1278 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1279 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1280 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1281 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1283 final String typedefName = typedef.getQName().getLocalName();
1284 final String classTypedefName = BindingMapping.getClassName(typedefName);
1285 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1286 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1288 genTOBuilder.setDescription(typedef.getDescription());
1289 genTOBuilder.setReference(typedef.getReference());
1290 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1291 genTOBuilder.setModuleName(moduleName);
1292 genTOBuilder.setTypedef(true);
1293 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1294 genTOBuilder.setRestrictions(r);
1296 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1297 genTOBuilder.setIsUnion(true);
1300 Map<Date, Map<String, Type>> modulesByDate = null;
1301 Map<String, Type> typeMap = null;
1302 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1303 if (parentModule != null) {
1304 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1305 typeMap = modulesByDate.get(parentModule.getRevision());
1308 if (typeMap != null) {
1309 Type type = typeMap.get(innerTypeDef);
1310 if (type instanceof GeneratedTransferObject) {
1311 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1314 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1315 makeSerializable(genTOBuilder);
1317 return genTOBuilder.toInstance();
1321 * Add {@link Serializable} to implemented interfaces of this TO. Also
1322 * compute and add serialVersionUID property.
1325 * transfer object which needs to be serializable
1327 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1328 gto.addImplementsType(Types.typeForClass(Serializable.class));
1329 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1330 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1335 * Finds out for each type definition how many immersion (depth) is
1336 * necessary to get to the base type. Every type definition is inserted to
1337 * the map which key is depth and value is list of type definitions with
1338 * equal depth. In next step are lists from this map concatenated to one
1339 * list in ascending order according to their depth. All type definitions
1340 * are in the list behind all type definitions on which depends.
1342 * @param unsortedTypeDefinitions
1343 * list of type definitions which should be sorted by depth
1344 * @return list of type definitions sorted according their each other
1345 * dependencies (type definitions which are depend on other type
1346 * definitions are in list behind them).
1348 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1349 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1350 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1352 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1353 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1354 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1355 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1356 if (typeDefinitionsConcreteDepth == null) {
1357 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1358 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1360 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1363 // SortedMap guarantees order corresponding to keys in ascending order
1364 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1365 sortedTypeDefinition.addAll(v);
1368 return sortedTypeDefinition;
1372 * Returns how many immersion is necessary to get from the type definition
1375 * @param typeDefinition
1376 * type definition for which is depth sought.
1377 * @return number of immersions which are necessary to get from the type
1378 * definition to the base type
1380 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1381 // FIXME: rewrite this in a non-recursive manner, without ExtendedType and UnionType
1382 if (typeDefinition == null) {
1386 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1388 if (baseType instanceof ExtendedType) {
1389 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1390 } else if (baseType instanceof UnionType) {
1391 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1392 int maxChildDepth = 0;
1394 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1395 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1396 if (childDepth > maxChildDepth) {
1397 maxChildDepth = childDepth;
1400 return maxChildDepth;
1406 * Returns string which contains the same value as <code>name</code> but
1407 * integer suffix is incremented by one. If <code>name</code> contains no
1408 * number suffix then number 1 is added.
1411 * string with name of augmented node
1412 * @return string with the number suffix incremented by one (or 1 is added)
1414 private static String provideAvailableNameForGenTOBuilder(final String name) {
1415 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1417 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1418 return name.substring(0, mtch.start()) + newSuffix;
1424 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1425 if (!Strings.isNullOrEmpty(units)) {
1426 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1427 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1428 prop.setReturnType(Types.STRING);
1429 to.addToStringProperty(prop);
1434 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1435 return getTypeDefaultConstruction(node, node.getDefault());
1438 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1439 TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1440 QName typeQName = type.getQName();
1441 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1442 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1443 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1446 StringBuilder sb = new StringBuilder();
1447 String result = null;
1448 if (base instanceof BinaryTypeDefinition) {
1449 result = binaryToDef(defaultValue);
1450 } else if (base instanceof BitsTypeDefinition) {
1453 Module parent = getParentModule(node);
1454 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1456 if (!(path.hasNext())) {
1457 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1458 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1459 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1461 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1462 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1463 parentName = BindingMapping.getClassName(parent.getName());
1464 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1466 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1467 } else if (base instanceof BooleanTypeDefinition) {
1468 result = typeToDef(Boolean.class, defaultValue);
1469 } else if (base instanceof DecimalTypeDefinition) {
1470 result = typeToDef(BigDecimal.class, defaultValue);
1471 } else if (base instanceof EmptyTypeDefinition) {
1472 result = typeToDef(Boolean.class, defaultValue);
1473 } else if (base instanceof EnumTypeDefinition) {
1474 char[] defValArray = defaultValue.toCharArray();
1475 char first = Character.toUpperCase(defaultValue.charAt(0));
1476 defValArray[0] = first;
1477 String newDefVal = new String(defValArray);
1479 if (type.getBaseType() != null) {
1480 Module m = getParentModule(type);
1481 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1482 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1483 className = packageName + "." + BindingMapping.getClassName(typeQName);
1485 Module parentModule = getParentModule(node);
1486 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1487 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1488 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1490 result = className + "." + newDefVal;
1491 } else if (base instanceof IdentityrefTypeDefinition) {
1492 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1493 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1494 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1495 } else if (BaseTypes.isInt8(base)) {
1496 result = typeToDef(Byte.class, defaultValue);
1497 } else if (BaseTypes.isInt16(base)) {
1498 result = typeToDef(Short.class, defaultValue);
1499 } else if (BaseTypes.isInt32(base)) {
1500 result = typeToDef(Integer.class, defaultValue);
1501 } else if (BaseTypes.isInt64(base)) {
1502 result = typeToDef(Long.class, defaultValue);
1503 } else if (base instanceof LeafrefTypeDefinition) {
1504 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1505 } else if (base instanceof StringTypeDefinition) {
1506 result = "\"" + defaultValue + "\"";
1507 } else if (BaseTypes.isUint8(base)) {
1508 result = typeToDef(Short.class, defaultValue);
1509 } else if (BaseTypes.isUint16(base)) {
1510 result = typeToDef(Integer.class, defaultValue);
1511 } else if (BaseTypes.isUint32(base)) {
1512 result = typeToDef(Long.class, defaultValue);
1513 } else if (BaseTypes.isUint64(base)) {
1514 result = typeToDef(BigInteger.class, defaultValue);
1515 } else if (base instanceof UnionTypeDefinition) {
1516 result = unionToDef(node);
1522 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1523 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1524 Module m = getParentModule(type);
1525 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1526 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1527 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1528 sb.insert(0, "new " + className + "(");
1529 sb.insert(sb.length(), ')');
1532 return sb.toString();
1535 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1536 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1539 private static String binaryToDef(final String defaultValue) {
1540 StringBuilder sb = new StringBuilder();
1541 BaseEncoding en = BaseEncoding.base64();
1542 byte[] encoded = en.decode(defaultValue);
1543 sb.append("new byte[] {");
1544 for (int i = 0; i < encoded.length; i++) {
1545 sb.append(encoded[i]);
1546 if (i != encoded.length - 1) {
1551 return sb.toString();
1554 private static final Comparator<Bit> BIT_NAME_COMPARATOR = new Comparator<Bit>() {
1556 public int compare(final Bit o1, final Bit o2) {
1557 return o1.getName().compareTo(o2.getName());
1561 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1562 final boolean isExt) {
1563 List<Bit> bits = new ArrayList<>(type.getBits());
1564 Collections.sort(bits, BIT_NAME_COMPARATOR);
1565 StringBuilder sb = new StringBuilder();
1568 sb.append(className);
1571 for (int i = 0; i < bits.size(); i++) {
1572 if (bits.get(i).getName().equals(defaultValue)) {
1577 if (i != bits.size() - 1) {
1584 return sb.toString();
1587 private Module getParentModule(final SchemaNode node) {
1588 QName qname = node.getPath().getPathFromRoot().iterator().next();
1589 URI namespace = qname.getNamespace();
1590 Date revision = qname.getRevision();
1591 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1594 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1595 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1596 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1597 "The Path Statement for Leafref Type Definition cannot be NULL!");
1599 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1600 final String strXPath = xpath.toString();
1602 if (strXPath != null) {
1603 if (strXPath.indexOf('[') == -1) {
1604 final Module module = findParentModule(schemaContext, parentNode);
1605 if (module != null) {
1606 final SchemaNode dataNode;
1607 if (xpath.isAbsolute()) {
1608 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1610 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1612 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1616 return "new java.lang.Object()";
1623 private String unionToDef(final LeafSchemaNode node) {
1624 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1628 if (type.getBaseType() != null) {
1629 QName typeQName = type.getQName();
1630 Module module = null;
1631 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1632 if (modules.size() > 1) {
1633 for (Module m : modules) {
1634 if (m.getRevision().equals(typeQName.getRevision())) {
1639 if (module == null) {
1640 List<Module> modulesList = new ArrayList<>(modules);
1641 Collections.sort(modulesList, new Comparator<Module>() {
1643 public int compare(final Module o1, final Module o2) {
1644 return o1.getRevision().compareTo(o2.getRevision());
1647 module = modulesList.get(0);
1650 module = modules.iterator().next();
1653 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1654 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1656 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1657 QName first = path.next();
1658 if (!(path.hasNext())) {
1659 URI namespace = first.getNamespace();
1660 Date revision = first.getRevision();
1661 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1662 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1663 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1664 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1666 URI namespace = first.getNamespace();
1667 Date revision = first.getRevision();
1668 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1669 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1670 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1671 node.getType().getPath());
1672 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1675 return union(className, node.getDefault(), node);
1678 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1679 StringBuilder sb = new StringBuilder();
1681 sb.append(className);
1683 sb.append(defaultValue);
1684 sb.append("\".toCharArray())");
1685 return sb.toString();
1689 public String getConstructorPropertyName(final SchemaNode node) {
1690 if (node instanceof TypeDefinition<?>) {
1698 public String getParamNameFromType(final TypeDefinition<?> type) {
1699 return BindingMapping.getPropertyName(type.getQName().getLocalName());