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;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.Sets;
19 import com.google.common.io.BaseEncoding;
20 import java.io.Serializable;
21 import java.math.BigDecimal;
22 import java.math.BigInteger;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.Date;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
34 import java.util.TreeMap;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37 import org.apache.commons.lang3.StringEscapeUtils;
38 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
39 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
40 import org.opendaylight.yangtools.binding.generator.util.Types;
41 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
42 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
43 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
44 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
45 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
46 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
47 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
48 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty;
49 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
50 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
51 import org.opendaylight.yangtools.sal.binding.model.api.Type;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
53 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
54 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
55 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
56 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
57 import org.opendaylight.yangtools.yang.binding.BindingMapping;
58 import org.opendaylight.yangtools.yang.common.QName;
59 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
60 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.Module;
65 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
67 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
69 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
73 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
81 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.util.Decimal64;
84 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
85 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
86 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
87 import org.opendaylight.yangtools.yang.model.util.UnionType;
88 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
89 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
90 import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
94 public final class TypeProviderImpl implements TypeProvider {
95 private static final Logger LOG = LoggerFactory.getLogger(TypeProviderImpl.class);
96 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
99 * Contains the schema data red from YANG files.
101 private final SchemaContext schemaContext;
104 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
106 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
109 * The map which maps schema paths to JAVA <code>Type</code>.
111 private final Map<SchemaPath, Type> referencedTypes;
112 private final Map<Module, Set<Type>> additionalTypes;
115 * Creates new instance of class <code>TypeProviderImpl</code>.
117 * @param schemaContext
118 * contains the schema data red from YANG files
119 * @throws IllegalArgumentException
120 * if <code>schemaContext</code> equal null.
122 public TypeProviderImpl(final SchemaContext schemaContext) {
123 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
125 this.schemaContext = schemaContext;
126 this.genTypeDefsContextMap = new HashMap<>();
127 this.referencedTypes = new HashMap<>();
128 this.additionalTypes = new HashMap<>();
129 resolveTypeDefsFromContext();
133 * Puts <code>refType</code> to map with key <code>refTypePath</code>
136 * schema path used as the map key
138 * type which represents the map value
139 * @throws IllegalArgumentException
141 * <li>if <code>refTypePath</code> equal null</li>
142 * <li>if <code>refType</code> equal null</li>
146 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
147 Preconditions.checkArgument(refTypePath != null,
148 "Path reference of Enumeration Type Definition cannot be NULL!");
149 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
150 referencedTypes.put(refTypePath, refType);
153 public Map<Module, Set<Type>> getAdditionalTypes() {
154 return additionalTypes;
159 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
162 * string with YANG name of type
163 * @return JAVA <code>Type</code> for YANG type <code>type</code>
164 * @see TypeProvider#javaTypeForYangType(String)
168 public Type javaTypeForYangType(final String type) {
169 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
173 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
174 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
178 * Converts schema definition type <code>typeDefinition</code> to JAVA
181 * @param typeDefinition
182 * type definition which is converted to JAVA type
183 * @throws IllegalArgumentException
185 * <li>if <code>typeDefinition</code> equal null</li>
186 * <li>if Qname of <code>typeDefinition</code> equal null</li>
187 * <li>if name of <code>typeDefinition</code> equal null</li>
191 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode, 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 base types
199 if (typeDefinition.getBaseType() == null) {
200 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
201 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
202 // a base type which holds these constraints -- and the class is not a Decimal64.
203 if (typeDefinition instanceof DecimalTypeDefinition && !(typeDefinition instanceof Decimal64)) {
204 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition, parentNode, r);
210 // Deal with leafrefs/identityrefs
211 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
216 // FIXME: it looks as though we could be using the same codepath as above...
217 ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName().getLocalName());
219 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
225 Type returnType = javaTypeForExtendedType(typeDefinition);
226 if (r != null && returnType instanceof GeneratedTransferObject) {
227 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
228 Module module = findParentModule(schemaContext, parentNode);
229 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
230 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
231 String genTOName = BindingMapping.getClassName(typedefName);
232 String name = packageName + "." + genTOName;
233 if (!(returnType.getFullyQualifiedName().equals(name))) {
234 returnType = shadedTOWithRestrictions(gto, r);
240 private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
241 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
242 GeneratedTransferObject parent = gto.getSuperType();
243 if (parent != null) {
244 gtob.setExtendsType(parent);
246 gtob.setRestrictions(r);
247 for (GeneratedProperty gp : gto.getProperties()) {
248 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
249 gpb.setValue(gp.getValue());
250 gpb.setReadOnly(gp.isReadOnly());
251 gpb.setAccessModifier(gp.getAccessModifier());
252 gpb.setReturnType(gp.getReturnType());
253 gpb.setFinal(gp.isFinal());
254 gpb.setStatic(gp.isStatic());
256 return gtob.toInstance();
259 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
260 final SchemaNode leafRefValueNode;
261 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
262 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
263 .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute());
265 ///// skip leafrefs in augments - they're checked once augments are resolved
266 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
267 boolean isAugmenting = false;
268 DataNodeContainer current = null;
269 DataSchemaNode dataChildByName;
271 while (iterator.hasNext() && !isAugmenting) {
272 final QName next = iterator.next();
273 if (current == null) {
274 dataChildByName = schemaContext.getDataChildByName(next);
276 dataChildByName = current.getDataChildByName(next);
278 if (dataChildByName != null) {
279 isAugmenting = dataChildByName.isAugmenting();
283 if (dataChildByName instanceof DataNodeContainer) {
284 current = (DataNodeContainer) dataChildByName;
292 Module parentModule = getParentModule(parentNode);
293 if (!leafRefStrippedXPath.isAbsolute()) {
294 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
295 parentNode, leafRefStrippedXPath);
297 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
299 return (leafRefValueNode != null) ? leafRefValueNode.equals(parentNode) : false;
303 * Returns JAVA <code>Type</code> for instances of the type
304 * <code>LeafrefTypeDefinition</code> or
305 * <code>IdentityrefTypeDefinition</code>.
307 * @param typeDefinition
308 * type definition which is converted to JAVA <code>Type</code>
309 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
311 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
312 if (typeDefinition instanceof LeafrefTypeDefinition) {
313 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
314 if (isLeafRefSelfReference(leafref, parentNode)) {
315 throw new YangValidationException("Leafref " + leafref.toString() + " is referencing itself, incoming" +
316 " StackOverFlowError detected.");
318 return provideTypeForLeafref(leafref, parentNode);
319 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
320 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
321 return provideTypeForIdentityref(idref);
328 * Returns JAVA <code>Type</code> for instances of the type
329 * <code>ExtendedType</code>.
331 * @param typeDefinition
332 * type definition which is converted to JAVA <code>Type</code>
333 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
335 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
336 final String typedefName = typeDefinition.getQName().getLocalName();
337 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
338 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
339 if (returnType == null) {
340 if (baseTypeDef instanceof EnumTypeDefinition) {
341 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
342 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
344 final Module module = findParentModule(schemaContext, typeDefinition);
345 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
346 if (module != null) {
347 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
348 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
349 if (genTOs != null) {
350 returnType = genTOs.get(typedefName);
352 if (returnType == null) {
353 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
354 baseTypeDef, typeDefinition, r);
363 * Seeks for identity reference <code>idref</code> the JAVA
364 * <code>type</code>.<br />
368 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
369 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
372 * identityref type definition for which JAVA <code>Type</code>
374 * @return JAVA <code>Type</code> of the identity which is refrenced through
377 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
378 QName baseIdQName = idref.getIdentity().getQName();
379 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
380 baseIdQName.getRevision());
381 IdentitySchemaNode identity = null;
382 for (IdentitySchemaNode id : module.getIdentities()) {
383 if (id.getQName().equals(baseIdQName)) {
387 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
389 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
390 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath());
391 final String genTypeName = BindingMapping.getClassName(identity.getQName());
393 Type baseType = Types.typeForClass(Class.class);
394 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
395 return Types.parameterizedTypeFor(baseType, paramType);
399 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
401 * @param typeDefinition
402 * type definition which should be converted to JAVA
404 * @return JAVA <code>Type</code> which represents
405 * <code>typeDefinition</code>
406 * @throws IllegalArgumentException
408 * <li>if <code>typeDefinition</code> equal null</li>
409 * <li>if Q name of <code>typeDefinition</code></li>
410 * <li>if name of <code>typeDefinition</code></li>
413 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
414 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
415 if (typeDefinition.getQName() == null) {
416 throw new IllegalArgumentException(
417 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
419 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
420 "Type Definitions Local Name cannot be NULL!");
422 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
423 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
424 final Module module = findParentModule(schemaContext, parentNode);
426 if (module != null) {
427 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
428 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
429 if (genTOs != null) {
430 return genTOs.get(typeDefinition.getQName().getLocalName());
438 * Gets base type definition for <code>extendTypeDef</code>. The method is
439 * recursively called until non <code>ExtendedType</code> type is found.
441 * @param extendTypeDef
442 * type definition for which is the base type definition sought
443 * @return type definition which is base type for <code>extendTypeDef</code>
444 * @throws IllegalArgumentException
445 * if <code>extendTypeDef</code> equal null
447 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
448 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
450 TypeDefinition<?> ret = extendTypeDef;
451 while (ret.getBaseType() != null) {
452 ret = ret.getBaseType();
459 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
461 * The path of <code>leafrefType</code> is followed to find referenced node
462 * and its <code>Type</code> is returned.
465 * leafref type definition for which is the type sought
466 * @return JAVA <code>Type</code> of data schema node which is referenced in
467 * <code>leafrefType</code>
468 * @throws IllegalArgumentException
470 * <li>if <code>leafrefType</code> equal null</li>
471 * <li>if path statement of <code>leafrefType</code> equal null</li>
475 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
476 Type returnType = null;
477 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
479 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
480 "The Path Statement for Leafref Type Definition cannot be NULL!");
482 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
483 final String strXPath = xpath.toString();
485 if (strXPath != null) {
486 if (strXPath.indexOf('[') == -1) {
487 final Module module = findParentModule(schemaContext, parentNode);
488 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
490 final SchemaNode dataNode;
491 if (xpath.isAbsolute()) {
492 dataNode = findDataSchemaNode(schemaContext, module, xpath);
494 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
496 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s) at %s",
497 strXPath, this.getParentModule(parentNode).getName(),
498 parentNode.getQName().getModule(), this.getParentModule(parentNode).getModuleSourcePath());
500 if (leafContainsEnumDefinition(dataNode)) {
501 returnType = referencedTypes.get(dataNode.getPath());
502 } else if (leafListContainsEnumDefinition(dataNode)) {
503 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
505 returnType = resolveTypeFromDataSchemaNode(dataNode);
508 returnType = Types.typeForClass(Object.class);
511 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s) at %s",
512 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this
513 .getParentModule(parentNode).getModuleSourcePath());
518 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
519 * so then checks if it is of type <code>EnumTypeDefinition</code>.
522 * data schema node for which is checked if it is leaf and if it
524 * @return boolean value
526 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
527 * <li>false - other cases</li>
530 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
531 if (dataNode instanceof LeafSchemaNode) {
532 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
533 if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
541 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
542 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
545 * data schema node for which is checked if it is leaflist and if
547 * @return boolean value
549 * <li>true - if <code>dataNode</code> is leaflist of type
551 * <li>false - other cases</li>
554 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
555 if (dataNode instanceof LeafListSchemaNode) {
556 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
557 if (leafList.getType() instanceof EnumTypeDefinition) {
565 * Converts <code>enumTypeDef</code> to
566 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
570 * enumeration type definition which is converted to enumeration
572 * string with name which is used as the enumeration name
573 * @return enumeration type which is built with data (name, enum values)
574 * from <code>enumTypeDef</code>
575 * @throws IllegalArgumentException
577 * <li>if <code>enumTypeDef</code> equals null</li>
578 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
579 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
580 * <li>if name of <code>enumTypeDef</code> equal null</li>
583 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName, final SchemaNode parentNode) {
584 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
585 Preconditions.checkArgument(enumTypeDef.getValues() != null,
586 "EnumTypeDefinition MUST contain at least ONE value definition!");
587 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
588 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
589 "Local Name in EnumTypeDefinition QName cannot be NULL!");
591 final String enumerationName = BindingMapping.getClassName(enumName);
593 Module module = findParentModule(schemaContext, parentNode);
594 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
596 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
597 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
598 enumBuilder.setDescription(enumTypedefDescription);
599 enumBuilder.setReference(enumTypeDef.getReference());
600 enumBuilder.setModuleName(module.getName());
601 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
602 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
603 return enumBuilder.toInstance(null);
607 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
608 * taken from <code>enumTypeDef</code>.
611 * enumeration type definition is source of enumeration data for
612 * <code>typeBuilder</code>
614 * string with the name of enumeration
616 * generated type builder to which is enumeration added
617 * @return enumeration type which contains enumeration data form
618 * <code>enumTypeDef</code>
619 * @throws IllegalArgumentException
621 * <li>if <code>enumTypeDef</code> equals null</li>
622 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
623 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
624 * <li>if name of <code>enumTypeDef</code> equal null</li>
625 * <li>if name of <code>typeBuilder</code> equal null</li>
629 private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
630 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
631 Preconditions.checkArgument(enumTypeDef.getValues() != null,
632 "EnumTypeDefinition MUST contain at least ONE value definition!");
633 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
634 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
635 "Local Name in EnumTypeDefinition QName cannot be NULL!");
636 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
638 final String enumerationName = BindingMapping.getClassName(enumName);
640 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
641 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
642 enumBuilder.setDescription(enumTypedefDescription);
643 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
644 return enumBuilder.toInstance(enumBuilder);
648 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
651 * contains information about YANG type
652 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
654 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
655 Type returnType = null;
656 if (dataNode != null) {
657 if (dataNode instanceof LeafSchemaNode) {
658 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
659 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
660 returnType = javaTypeForSchemaDefinitionType(type, leaf);
661 } else if (dataNode instanceof LeafListSchemaNode) {
662 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
663 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
670 * Passes through all modules and through all its type definitions and
671 * convert it to generated types.
673 * The modules are firstly sorted by mutual dependencies. The modules are
674 * sequentially passed. All type definitions of a module are at the
675 * beginning sorted so that type definition with less amount of references
676 * to other type definition are processed first.<br />
677 * For each module is created mapping record in the map
678 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
679 * which map current module name to the map which maps type names to
680 * returned types (generated types).
683 private void resolveTypeDefsFromContext() {
684 final Set<Module> modules = schemaContext.getModules();
685 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
686 final Module[] modulesArray = new Module[modules.size()];
688 for (Module modul : modules) {
689 modulesArray[i++] = modul;
691 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
694 for (final Module module : modulesSortedByDependency) {
695 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
696 if (dateTypeMap == null) {
697 dateTypeMap = new HashMap<>();
699 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
700 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
703 for (final Module module : modulesSortedByDependency) {
704 if (module != null) {
705 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
706 if (basePackageName != null) {
707 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
708 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
709 if (listTypeDefinitions != null) {
710 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
711 typedefToGeneratedType(basePackageName, module, typedef);
721 * @param basePackageName
722 * string with name of package to which the module belongs
724 * string with the name of the module for to which the
725 * <code>typedef</code> belongs
727 * type definition of the node for which should be creted JAVA
728 * <code>Type</code> (usually generated TO)
729 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
730 * <code>null</code> value if <code>basePackageName</code> or
731 * <code>modulName</code> or <code>typedef</code> or Q name of
732 * <code>typedef</code> equals <code>null</code>
734 private Type typedefToGeneratedType(final String basePackageName, final Module module, final TypeDefinition<?> typedef) {
735 final String moduleName = module.getName();
736 final Date moduleRevision = module.getRevision();
737 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
738 final String typedefName = typedef.getQName().getLocalName();
739 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
740 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
741 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
742 Type returnType = null;
743 if (innerTypeDefinition.getBaseType() != null) {
744 returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName, module.getName());
745 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
746 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
747 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
748 genTOBuilder.setTypedef(true);
749 genTOBuilder.setIsUnion(true);
750 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
751 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
752 returnType = genTOBuilder.toInstance();
754 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
755 genTOBuilder.getName() + "Builder");
756 unionBuilder.setIsUnionBuilder(true);
757 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
758 method.setReturnType(returnType);
759 method.addParameter(Types.STRING, "defaultValue");
760 method.setAccessModifier(AccessModifier.PUBLIC);
761 method.setStatic(true);
762 Set<Type> types = additionalTypes.get(module);
764 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
765 additionalTypes.put(module, types);
767 types.add(unionBuilder.toInstance());
769 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
770 // enums are automatically Serializable
771 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
772 // TODO units for typedef enum
773 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
774 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
775 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
776 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
777 basePackageName, bitsTypeDefinition, typedefName, module.getName());
778 genTOBuilder.setTypedef(true);
779 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
780 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
781 returnType = genTOBuilder.toInstance();
783 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
784 innerTypeDefinition, typedef);
785 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
787 if (returnType != null) {
788 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
789 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
790 if (typeMap != null) {
791 if (typeMap.isEmpty()) {
792 typeMap = new HashMap<>(4);
793 modulesByDate.put(moduleRevision, typeMap);
795 typeMap.put(typedefName, returnType);
805 * Wraps base YANG type to generated TO.
807 * @param basePackageName
808 * string with name of package to which the module belongs
810 * type definition which is converted to the TO
812 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
813 * @return generated transfer object which represent<code>javaType</code>
815 private static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef, final Type javaType, final String moduleName) {
816 Preconditions.checkNotNull(javaType, "javaType cannot be null");
817 final String propertyName = "value";
819 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
820 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
821 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
822 genPropBuilder.setReturnType(javaType);
823 genTOBuilder.addEqualsIdentity(genPropBuilder);
824 genTOBuilder.addHashIdentity(genPropBuilder);
825 genTOBuilder.addToStringProperty(genPropBuilder);
826 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
827 final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
828 addStringRegExAsConstant(genTOBuilder, regExps);
830 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
831 genTOBuilder.setTypedef(true);
832 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
833 return genTOBuilder.toInstance();
837 * Converts output list of generated TO builders to one TO builder (first
838 * from list) which contains the remaining builders as its enclosing TO.
840 * @param basePackageName
841 * string with name of package to which the module belongs
843 * type definition which should be of type
844 * <code>UnionTypeDefinition</code>
846 * string with name for generated TO
847 * @return generated TO builder with the list of enclosed generated TO
850 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName, final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
851 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
852 typedef, typeDefName, parentNode);
853 GeneratedTOBuilder resultTOBuilder = null;
854 if (genTOBuilders.isEmpty()) {
855 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typedef);
858 resultTOBuilder = genTOBuilders.remove(0);
859 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
860 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
863 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
864 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
865 resultTOBuilder.addEqualsIdentity(genPropBuilder);
866 resultTOBuilder.addHashIdentity(genPropBuilder);
867 resultTOBuilder.addToStringProperty(genPropBuilder);
869 return resultTOBuilder;
873 * Converts <code>typedef</code> to generated TO with
874 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
875 * added to generated TO builder as property.
877 * @param basePackageName
878 * string with name of package to which the module belongs
880 * type definition which should be of type
881 * <code>UnionTypeDefinition</code>
883 * string with name for generated TO
884 * @return generated TO builder which represents <code>typedef</code>
885 * @throws NullPointerException
887 * <li>if <code>basePackageName</code> is null</li>
888 * <li>if <code>typedef</code> is null</li>
889 * <li>if Qname of <code>typedef</code> is null</li>
892 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName, final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
893 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
894 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
895 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
897 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
898 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
899 final Module module = findParentModule(schemaContext, parentNode);
901 final GeneratedTOBuilderImpl unionGenTOBuilder;
902 if (typeDefName != null && !typeDefName.isEmpty()) {
903 final String typeName = BindingMapping.getClassName(typeDefName);
904 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
905 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
906 unionGenTOBuilder.setDescription(typedefDescription);
907 unionGenTOBuilder.setReference(typedef.getReference());
908 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
909 unionGenTOBuilder.setModuleName(module.getName());
911 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
914 generatedTOBuilders.add(unionGenTOBuilder);
915 unionGenTOBuilder.setIsUnion(true);
916 final List<String> regularExpressions = new ArrayList<String>();
917 for (final TypeDefinition<?> unionType : unionTypes) {
918 final String unionTypeName = unionType.getQName().getLocalName();
919 if (unionType.getBaseType() != null) {
920 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, regularExpressions,
922 } else if (unionType instanceof UnionTypeDefinition) {
923 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionTypeDefinition) unionType,
924 basePackageName, parentNode));
925 } else if (unionType instanceof EnumTypeDefinition) {
926 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
927 unionTypeName, unionGenTOBuilder);
928 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
930 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
932 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
935 if (!regularExpressions.isEmpty()) {
936 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
939 storeGenTO(typedef, unionGenTOBuilder, parentNode);
941 return generatedTOBuilders;
945 * Wraps code which handle case when union subtype is also of the type
946 * <code>UnionType</code>.
948 * In this case the new generated TO is created for union subtype (recursive
950 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
951 * String, SchemaNode)}
952 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
953 * <code>parentUnionGenTOBuilder</code> is created property which type is
954 * equal to new generated TO.
956 * @param parentUnionGenTOBuilder
957 * generated TO builder to which is the property with the child
958 * union subtype added
959 * @param basePackageName
960 * string with the name of the module package
961 * @param unionSubtype
962 * type definition which represents union subtype
963 * @return list of generated TO builders. The number of the builders can be
964 * bigger one due to recursive call of
965 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
967 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
968 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
969 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
970 basePackageName, unionSubtype, newTOBuilderName, parentNode);
972 final GeneratedPropertyBuilder propertyBuilder;
973 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
974 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
975 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
976 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
978 return subUnionGenTOBUilders;
982 * Wraps code which handle case when union subtype is of the type
983 * <code>ExtendedType</code>.
985 * If TO for this type already exists it is used for the creation of the
986 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
987 * type is used for the property creation.
989 * @param parentUnionGenTOBuilder
990 * generated TO builder in which new property is created
991 * @param unionSubtype
992 * type definition of the <code>ExtendedType</code> type which
993 * represents union subtype
994 * @param regularExpressions
995 * list of strings with the regular expressions
997 * parent Schema Node for Extended Subtype
1000 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final TypeDefinition<?> unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
1001 final String unionTypeName = unionSubtype.getQName().getLocalName();
1002 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1003 if (genTO != null) {
1004 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1006 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1007 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1008 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1010 if (javaType != null) {
1011 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1014 if (baseType instanceof StringTypeDefinition) {
1015 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
1021 * Searches for generated TO for <code>searchedTypeDef</code> type
1022 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1024 * @param searchedTypeName
1025 * string with name of <code>searchedTypeDef</code>
1026 * @return generated TO for <code>searchedTypeDef</code> or
1027 * <code>null</code> it it doesn't exist
1029 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1030 final Module typeModule = findParentModule(schemaContext, parentNode);
1031 if (typeModule != null && typeModule.getName() != null) {
1032 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1033 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1034 if (genTOs != null) {
1035 return genTOs.get(searchedTypeName);
1042 * Stores generated TO created from <code>genTOBuilder</code> for
1043 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1044 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1047 * type definition for which is <code>genTOBuilder</code> created
1048 * @param genTOBuilder
1049 * generated TO builder which is converted to generated TO and
1052 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1053 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1054 final Module parentModule = findParentModule(schemaContext, parentNode);
1055 if (parentModule != null && parentModule.getName() != null) {
1056 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1057 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1058 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1064 * Adds a new property with the name <code>propertyName</code> and with type
1065 * <code>type</code> to <code>unonGenTransObject</code>.
1067 * @param unionGenTransObject
1068 * generated TO to which should be property added
1070 * JAVA <code>type</code> of the property which should be added
1071 * to <code>unionGentransObject</code>
1072 * @param propertyName
1073 * string with name of property which should be added to
1074 * <code>unionGentransObject</code>
1076 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1077 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1078 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1079 .addProperty(BindingMapping.getPropertyName(propertyName));
1080 propBuilder.setReturnType(type);
1082 unionGenTransObject.addEqualsIdentity(propBuilder);
1083 unionGenTransObject.addHashIdentity(propBuilder);
1084 unionGenTransObject.addToStringProperty(propBuilder);
1089 * Converts <code>typedef</code> to the generated TO builder.
1091 * @param basePackageName
1092 * string with name of package to which the module belongs
1094 * type definition from which is the generated TO builder created
1095 * @return generated TO builder which contains data from
1096 * <code>typedef</code> and <code>basePackageName</code>
1098 private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef, final String moduleName) {
1100 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1101 final String typeDefTOName = typedef.getQName().getLocalName();
1103 if ((packageName != null) && (typeDefTOName != null)) {
1104 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1105 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1106 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
1108 newType.setDescription(typedefDescription);
1109 newType.setReference(typedef.getReference());
1110 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1111 newType.setModuleName(moduleName);
1119 * Converts <code>typeDef</code> which should be of the type
1120 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1122 * All the bits of the typeDef are added to returning generated TO as
1125 * @param basePackageName
1126 * string with name of package to which the module belongs
1128 * type definition from which is the generated TO builder created
1129 * @param typeDefName
1130 * string with the name for generated TO builder
1131 * @return generated TO builder which represents <code>typeDef</code>
1132 * @throws IllegalArgumentException
1134 * <li>if <code>typeDef</code> equals null</li>
1135 * <li>if <code>basePackageName</code> equals null</li>
1138 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName, final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1140 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1141 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1143 if (typeDef instanceof BitsTypeDefinition) {
1144 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1146 final String typeName = BindingMapping.getClassName(typeDefName);
1147 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1148 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1150 genTOBuilder.setDescription(typedefDescription);
1151 genTOBuilder.setReference(typeDef.getReference());
1152 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1153 genTOBuilder.setModuleName(moduleName);
1154 genTOBuilder.setBaseType(typeDef);
1156 final List<Bit> bitList = bitsTypeDefinition.getBits();
1157 GeneratedPropertyBuilder genPropertyBuilder;
1158 for (final Bit bit : bitList) {
1159 String name = bit.getName();
1160 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1161 genPropertyBuilder.setReadOnly(true);
1162 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1164 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1165 genTOBuilder.addHashIdentity(genPropertyBuilder);
1166 genTOBuilder.addToStringProperty(genPropertyBuilder);
1169 return genTOBuilder;
1175 * Converts the pattern constraints from <code>typedef</code> to the list of
1176 * the strings which represents these constraints.
1179 * extended type in which are the pattern constraints sought
1180 * @return list of strings which represents the constraint patterns
1181 * @throws IllegalArgumentException
1182 * if <code>typedef</code> equals null
1185 private static List<String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
1186 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1188 final List<PatternConstraint> patternConstraints;
1189 if (typedef instanceof ExtendedType) {
1190 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1191 if (strTypeDef instanceof StringTypeDefinition) {
1192 patternConstraints = ((ExtendedType)typedef).getPatternConstraints();
1194 patternConstraints = ImmutableList.of();
1196 } else if (typedef instanceof StringTypeDefinition) {
1197 // FIXME: run diff against base
1198 patternConstraints = ((StringTypeDefinition) typedef).getPatternConstraints();
1200 patternConstraints = ImmutableList.of();
1203 final List<String> regExps = new ArrayList<>(patternConstraints.size());
1204 for (PatternConstraint patternConstraint : patternConstraints) {
1205 final String regEx = patternConstraint.getRegularExpression();
1206 final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1207 regExps.add(modifiedRegEx);
1215 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1216 * expressions from the <code>regularExpressions</code>
1218 * @param genTOBuilder
1219 * generated TO builder to which are
1220 * <code>regular expressions</code> added
1221 * @param regularExpressions
1222 * list of string which represent regular expressions
1223 * @throws IllegalArgumentException
1225 * <li>if <code>genTOBuilder</code> equals null</li>
1226 * <li>if <code>regularExpressions</code> equals null</li>
1229 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1230 if (genTOBuilder == null) {
1231 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1233 if (regularExpressions == null) {
1234 throw new IllegalArgumentException("List of regular expressions can't be null");
1236 if (!regularExpressions.isEmpty()) {
1237 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1238 regularExpressions);
1243 * Creates generated TO with data about inner extended type
1244 * <code>innerExtendedType</code>, about the package name
1245 * <code>typedefName</code> and about the generated TO name
1246 * <code>typedefName</code>.
1248 * It is supposed that <code>innerExtendedType</code> is already present in
1249 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1250 * be possible set it as extended type for the returning generated TO.
1254 * @param innerExtendedType
1255 * extended type which is part of some other extended type
1256 * @param basePackageName
1257 * string with the package name of the module
1260 * @return generated TO which extends generated TO for
1261 * <code>innerExtendedType</code>
1262 * @throws IllegalArgumentException
1264 * <li>if <code>extendedType</code> equals null</li>
1265 * <li>if <code>basePackageName</code> equals null</li>
1266 * <li>if <code>typedefName</code> equals null</li>
1269 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef, final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1270 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1271 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1273 final String typedefName = typedef.getQName().getLocalName();
1274 final String classTypedefName = BindingMapping.getClassName(typedefName);
1275 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1276 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1277 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
1279 genTOBuilder.setDescription(typedefDescription);
1280 genTOBuilder.setReference(typedef.getReference());
1281 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1282 genTOBuilder.setModuleName(moduleName);
1283 genTOBuilder.setTypedef(true);
1284 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1285 genTOBuilder.setRestrictions(r);
1287 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1288 genTOBuilder.setIsUnion(true);
1291 Map<Date, Map<String, Type>> modulesByDate = null;
1292 Map<String, Type> typeMap = null;
1293 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1294 if (parentModule != null) {
1295 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1296 typeMap = modulesByDate.get(parentModule.getRevision());
1299 if (typeMap != null) {
1300 Type type = typeMap.get(innerTypeDef);
1301 if (type instanceof GeneratedTransferObject) {
1302 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1305 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1306 makeSerializable(genTOBuilder);
1308 return genTOBuilder.toInstance();
1312 * Add {@link Serializable} to implemented interfaces of this TO. Also
1313 * compute and add serialVersionUID property.
1316 * transfer object which needs to be serializable
1318 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1319 gto.addImplementsType(Types.typeForClass(Serializable.class));
1320 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1321 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1326 * Finds out for each type definition how many immersion (depth) is
1327 * necessary to get to the base type. Every type definition is inserted to
1328 * the map which key is depth and value is list of type definitions with
1329 * equal depth. In next step are lists from this map concatenated to one
1330 * list in ascending order according to their depth. All type definitions
1331 * are in the list behind all type definitions on which depends.
1333 * @param unsortedTypeDefinitions
1334 * list of type definitions which should be sorted by depth
1335 * @return list of type definitions sorted according their each other
1336 * dependencies (type definitions which are depend on other type
1337 * definitions are in list behind them).
1339 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1340 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1341 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1343 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1344 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1345 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1346 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1347 if (typeDefinitionsConcreteDepth == null) {
1348 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1349 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1351 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1354 // SortedMap guarantees order corresponding to keys in ascending order
1355 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1356 sortedTypeDefinition.addAll(v);
1359 return sortedTypeDefinition;
1363 * Returns how many immersion is necessary to get from the type definition
1366 * @param typeDefinition
1367 * type definition for which is depth sought.
1368 * @return number of immersions which are necessary to get from the type
1369 * definition to the base type
1371 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1372 // FIXME: rewrite this in a non-recursive manner, without ExtendedType and UnionType
1373 if (typeDefinition == null) {
1376 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1377 if (baseType == null) {
1382 if (baseType.getBaseType() != null) {
1383 depth = depth + getTypeDefinitionDepth(baseType);
1384 } else if (baseType instanceof UnionTypeDefinition) {
1385 List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1386 int maxChildDepth = 0;
1388 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1389 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1390 if (childDepth > maxChildDepth) {
1391 maxChildDepth = childDepth;
1394 return maxChildDepth;
1400 * Returns string which contains the same value as <code>name</code> but
1401 * integer suffix is incremented by one. If <code>name</code> contains no
1402 * number suffix then number 1 is added.
1405 * string with name of augmented node
1406 * @return string with the number suffix incremented by one (or 1 is added)
1408 private static String provideAvailableNameForGenTOBuilder(final String name) {
1409 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1411 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1412 return name.substring(0, mtch.start()) + newSuffix;
1418 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1419 if (!Strings.isNullOrEmpty(units)) {
1420 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1421 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1422 prop.setReturnType(Types.STRING);
1423 to.addToStringProperty(prop);
1428 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1429 return getTypeDefaultConstruction(node, node.getDefault());
1432 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1433 TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1434 QName typeQName = type.getQName();
1435 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1436 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1437 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1440 StringBuilder sb = new StringBuilder();
1441 String result = null;
1442 if (base instanceof BinaryTypeDefinition) {
1443 result = binaryToDef(defaultValue);
1444 } else if (base instanceof BitsTypeDefinition) {
1447 Module parent = getParentModule(node);
1448 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1450 if (!(path.hasNext())) {
1451 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1452 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1453 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1455 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1456 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1457 parentName = BindingMapping.getClassName(parent.getName());
1458 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1460 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1461 } else if (base instanceof BooleanTypeDefinition) {
1462 result = typeToDef(Boolean.class, defaultValue);
1463 } else if (base instanceof DecimalTypeDefinition) {
1464 result = typeToDef(BigDecimal.class, defaultValue);
1465 } else if (base instanceof EmptyTypeDefinition) {
1466 result = typeToDef(Boolean.class, defaultValue);
1467 } else if (base instanceof EnumTypeDefinition) {
1468 char[] defValArray = defaultValue.toCharArray();
1469 char first = Character.toUpperCase(defaultValue.charAt(0));
1470 defValArray[0] = first;
1471 String newDefVal = new String(defValArray);
1473 if (type.getBaseType() != null) {
1474 Module m = getParentModule(type);
1475 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1476 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1477 className = packageName + "." + BindingMapping.getClassName(typeQName);
1479 Module parentModule = getParentModule(node);
1480 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1481 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1482 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1484 result = className + "." + newDefVal;
1485 } else if (base instanceof IdentityrefTypeDefinition) {
1486 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1487 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1488 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1489 } else if (BaseTypes.isInt8(base)) {
1490 result = typeToDef(Byte.class, defaultValue);
1491 } else if (BaseTypes.isInt16(base)) {
1492 result = typeToDef(Short.class, defaultValue);
1493 } else if (BaseTypes.isInt32(base)) {
1494 result = typeToDef(Integer.class, defaultValue);
1495 } else if (BaseTypes.isInt64(base)) {
1496 result = typeToDef(Long.class, defaultValue);
1497 } else if (base instanceof LeafrefTypeDefinition) {
1498 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1499 } else if (base instanceof StringTypeDefinition) {
1500 result = "\"" + defaultValue + "\"";
1501 } else if (BaseTypes.isUint8(base)) {
1502 result = typeToDef(Short.class, defaultValue);
1503 } else if (BaseTypes.isUint16(base)) {
1504 result = typeToDef(Integer.class, defaultValue);
1505 } else if (BaseTypes.isUint32(base)) {
1506 result = typeToDef(Long.class, defaultValue);
1507 } else if (BaseTypes.isUint64(base)) {
1508 result = typeToDef(BigInteger.class, defaultValue);
1509 } else if (base instanceof UnionTypeDefinition) {
1510 result = unionToDef(node);
1516 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1517 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1518 Module m = getParentModule(type);
1519 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1520 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1521 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1522 sb.insert(0, "new " + className + "(");
1523 sb.insert(sb.length(), ')');
1526 return sb.toString();
1529 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1530 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1533 private static String binaryToDef(final String defaultValue) {
1534 StringBuilder sb = new StringBuilder();
1535 BaseEncoding en = BaseEncoding.base64();
1536 byte[] encoded = en.decode(defaultValue);
1537 sb.append("new byte[] {");
1538 for (int i = 0; i < encoded.length; i++) {
1539 sb.append(encoded[i]);
1540 if (i != encoded.length - 1) {
1545 return sb.toString();
1548 private static final Comparator<Bit> BIT_NAME_COMPARATOR = new Comparator<Bit>() {
1550 public int compare(final Bit o1, final Bit o2) {
1551 return o1.getName().compareTo(o2.getName());
1555 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1556 List<Bit> bits = new ArrayList<>(type.getBits());
1557 Collections.sort(bits, BIT_NAME_COMPARATOR);
1558 StringBuilder sb = new StringBuilder();
1561 sb.append(className);
1564 for (int i = 0; i < bits.size(); i++) {
1565 if (bits.get(i).getName().equals(defaultValue)) {
1570 if (i != bits.size() - 1) {
1577 return sb.toString();
1580 private Module getParentModule(final SchemaNode node) {
1581 QName qname = node.getPath().getPathFromRoot().iterator().next();
1582 URI namespace = qname.getNamespace();
1583 Date revision = qname.getRevision();
1584 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1587 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1588 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1589 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1590 "The Path Statement for Leafref Type Definition cannot be NULL!");
1592 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1593 final String strXPath = xpath.toString();
1595 if (strXPath != null) {
1596 if (strXPath.indexOf('[') == -1) {
1597 final Module module = findParentModule(schemaContext, parentNode);
1598 if (module != null) {
1599 final SchemaNode dataNode;
1600 if (xpath.isAbsolute()) {
1601 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1603 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1605 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1609 return "new java.lang.Object()";
1616 private String unionToDef(final LeafSchemaNode node) {
1617 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1621 if (type.getBaseType() != null) {
1622 QName typeQName = type.getQName();
1623 Module module = null;
1624 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1625 if (modules.size() > 1) {
1626 for (Module m : modules) {
1627 if (m.getRevision().equals(typeQName.getRevision())) {
1632 if (module == null) {
1633 List<Module> modulesList = new ArrayList<>(modules);
1634 Collections.sort(modulesList, new Comparator<Module>() {
1636 public int compare(final Module o1, final Module o2) {
1637 return o1.getRevision().compareTo(o2.getRevision());
1640 module = modulesList.get(0);
1643 module = modules.iterator().next();
1646 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1647 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1649 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1650 QName first = path.next();
1651 if (!(path.hasNext())) {
1652 URI namespace = first.getNamespace();
1653 Date revision = first.getRevision();
1654 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1655 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1656 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1657 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1659 URI namespace = first.getNamespace();
1660 Date revision = first.getRevision();
1661 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1662 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1664 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
1665 // the case, as unions are emitted to their correct schema path. Create a proxy instance to meet the
1666 // codepath's expectations
1667 final SchemaPath typePath;
1668 if (type instanceof UnionType) {
1669 typePath = type.getPath();
1671 typePath = UnionType.create(((UnionTypeDefinition)type).getTypes()).getPath();
1674 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typePath);
1675 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1678 return union(className, node.getDefault(), node);
1681 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1682 StringBuilder sb = new StringBuilder();
1684 sb.append(className);
1686 sb.append(defaultValue);
1687 sb.append("\".toCharArray())");
1688 return sb.toString();
1692 public String getConstructorPropertyName(final SchemaNode node) {
1693 if (node instanceof TypeDefinition<?>) {
1701 public String getParamNameFromType(final TypeDefinition<?> type) {
1702 return BindingMapping.getPropertyName(type.getQName().getLocalName());