2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.sal.binding.yang.types;
10 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
11 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
12 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.Sets;
18 import com.google.common.io.BaseEncoding;
19 import java.io.Serializable;
20 import java.math.BigDecimal;
21 import java.math.BigInteger;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.Date;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
33 import java.util.TreeMap;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import org.apache.commons.lang3.StringEscapeUtils;
37 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
38 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
39 import org.opendaylight.yangtools.binding.generator.util.Types;
40 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
41 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
42 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
43 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
44 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
45 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
46 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
47 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty;
48 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
49 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
50 import org.opendaylight.yangtools.sal.binding.model.api.Type;
51 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
53 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
54 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
55 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
56 import org.opendaylight.yangtools.yang.binding.BindingMapping;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
59 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.Module;
64 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
68 import org.opendaylight.yangtools.yang.model.api.Status;
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.RevisionAwareXPathImpl;
84 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
85 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
86 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
87 import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
91 public final class TypeProviderImpl implements TypeProvider {
92 private static final Logger LOG = LoggerFactory.getLogger(TypeProviderImpl.class);
93 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
95 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
96 // the case, as unions are emitted to their correct schema path.
97 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
98 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
101 * Contains the schema data red from YANG files.
103 private final SchemaContext schemaContext;
106 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
108 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
111 * The map which maps schema paths to JAVA <code>Type</code>.
113 private final Map<SchemaPath, Type> referencedTypes;
114 private final Map<Module, Set<Type>> additionalTypes;
117 * Creates new instance of class <code>TypeProviderImpl</code>.
119 * @param schemaContext
120 * contains the schema data red from YANG files
121 * @throws IllegalArgumentException
122 * if <code>schemaContext</code> equal null.
124 public TypeProviderImpl(final SchemaContext schemaContext) {
125 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
127 this.schemaContext = schemaContext;
128 this.genTypeDefsContextMap = new HashMap<>();
129 this.referencedTypes = new HashMap<>();
130 this.additionalTypes = new HashMap<>();
131 resolveTypeDefsFromContext();
135 * Puts <code>refType</code> to map with key <code>refTypePath</code>
138 * schema path used as the map key
140 * type which represents the map value
141 * @throws IllegalArgumentException
143 * <li>if <code>refTypePath</code> equal null</li>
144 * <li>if <code>refType</code> equal null</li>
148 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
149 Preconditions.checkArgument(refTypePath != null,
150 "Path reference of Enumeration Type Definition cannot be NULL!");
151 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
152 referencedTypes.put(refTypePath, refType);
155 public Map<Module, Set<Type>> getAdditionalTypes() {
156 return additionalTypes;
161 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
164 * string with YANG name of type
165 * @return JAVA <code>Type</code> for YANG type <code>type</code>
166 * @see TypeProvider#javaTypeForYangType(String)
170 public Type javaTypeForYangType(final String type) {
171 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
175 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
176 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
180 * Converts schema definition type <code>typeDefinition</code> to JAVA
183 * @param typeDefinition
184 * type definition which is converted to JAVA type
185 * @throws IllegalArgumentException
187 * <li>if <code>typeDefinition</code> equal null</li>
188 * <li>if Qname of <code>typeDefinition</code> equal null</li>
189 * <li>if name of <code>typeDefinition</code> equal null</li>
193 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode, final Restrictions r) {
194 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
195 Preconditions.checkArgument(typeDefinition.getQName() != null,
196 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
197 String typedefName = typeDefinition.getQName().getLocalName();
198 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
200 // Deal with base types
201 if (typeDefinition.getBaseType() == null) {
202 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
203 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
204 // a base type which holds these constraints.
205 if (typeDefinition instanceof DecimalTypeDefinition) {
206 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition, parentNode, r);
212 // Deal with leafrefs/identityrefs
213 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
218 // FIXME: it looks as though we could be using the same codepath as above...
219 ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName().getLocalName());
221 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
227 Type returnType = javaTypeForExtendedType(typeDefinition);
228 if (r != null && returnType instanceof GeneratedTransferObject) {
229 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
230 Module module = findParentModule(schemaContext, parentNode);
231 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
232 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
233 String genTOName = BindingMapping.getClassName(typedefName);
234 String name = packageName + "." + genTOName;
235 if (!(returnType.getFullyQualifiedName().equals(name))) {
236 returnType = shadedTOWithRestrictions(gto, r);
242 private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
243 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
244 GeneratedTransferObject parent = gto.getSuperType();
245 if (parent != null) {
246 gtob.setExtendsType(parent);
248 gtob.setRestrictions(r);
249 for (GeneratedProperty gp : gto.getProperties()) {
250 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
251 gpb.setValue(gp.getValue());
252 gpb.setReadOnly(gp.isReadOnly());
253 gpb.setAccessModifier(gp.getAccessModifier());
254 gpb.setReturnType(gp.getReturnType());
255 gpb.setFinal(gp.isFinal());
256 gpb.setStatic(gp.isStatic());
258 return gtob.toInstance();
261 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
262 final SchemaNode leafRefValueNode;
263 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
264 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
265 .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute());
267 ///// skip leafrefs in augments - they're checked once augments are resolved
268 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
269 boolean isAugmenting = false;
270 DataNodeContainer current = null;
271 DataSchemaNode dataChildByName;
273 while (iterator.hasNext() && !isAugmenting) {
274 final QName next = iterator.next();
275 if (current == null) {
276 dataChildByName = schemaContext.getDataChildByName(next);
278 dataChildByName = current.getDataChildByName(next);
280 if (dataChildByName != null) {
281 isAugmenting = dataChildByName.isAugmenting();
285 if (dataChildByName instanceof DataNodeContainer) {
286 current = (DataNodeContainer) dataChildByName;
294 Module parentModule = getParentModule(parentNode);
295 if (!leafRefStrippedXPath.isAbsolute()) {
296 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
297 parentNode, leafRefStrippedXPath);
299 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
301 return (leafRefValueNode != null) ? leafRefValueNode.equals(parentNode) : false;
305 * Returns JAVA <code>Type</code> for instances of the type
306 * <code>LeafrefTypeDefinition</code> or
307 * <code>IdentityrefTypeDefinition</code>.
309 * @param typeDefinition
310 * type definition which is converted to JAVA <code>Type</code>
311 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
313 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
314 if (typeDefinition instanceof LeafrefTypeDefinition) {
315 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
316 if (isLeafRefSelfReference(leafref, parentNode)) {
317 throw new YangValidationException("Leafref " + leafref.toString() + " is referencing itself, incoming" +
318 " StackOverFlowError detected.");
320 return provideTypeForLeafref(leafref, parentNode);
321 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
322 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
323 return provideTypeForIdentityref(idref);
330 * Returns JAVA <code>Type</code> for instances of the type
331 * <code>ExtendedType</code>.
333 * @param typeDefinition
334 * type definition which is converted to JAVA <code>Type</code>
335 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
337 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
338 final String typedefName = typeDefinition.getQName().getLocalName();
339 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
340 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
341 if (returnType == null) {
342 if (baseTypeDef instanceof EnumTypeDefinition) {
343 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
344 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
346 final Module module = findParentModule(schemaContext, typeDefinition);
347 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
348 if (module != null) {
349 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
350 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
351 if (genTOs != null) {
352 returnType = genTOs.get(typedefName);
354 if (returnType == null) {
355 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
356 baseTypeDef, typeDefinition, r);
365 * Seeks for identity reference <code>idref</code> the JAVA
366 * <code>type</code>.<br />
370 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
371 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
374 * identityref type definition for which JAVA <code>Type</code>
376 * @return JAVA <code>Type</code> of the identity which is refrenced through
379 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
380 QName baseIdQName = idref.getIdentity().getQName();
381 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
382 baseIdQName.getRevision());
383 IdentitySchemaNode identity = null;
384 for (IdentitySchemaNode id : module.getIdentities()) {
385 if (id.getQName().equals(baseIdQName)) {
389 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
391 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
392 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath());
393 final String genTypeName = BindingMapping.getClassName(identity.getQName());
395 Type baseType = Types.typeForClass(Class.class);
396 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
397 return Types.parameterizedTypeFor(baseType, paramType);
401 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
403 * @param typeDefinition
404 * type definition which should be converted to JAVA
406 * @return JAVA <code>Type</code> which represents
407 * <code>typeDefinition</code>
408 * @throws IllegalArgumentException
410 * <li>if <code>typeDefinition</code> equal null</li>
411 * <li>if Q name of <code>typeDefinition</code></li>
412 * <li>if name of <code>typeDefinition</code></li>
415 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
416 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
417 if (typeDefinition.getQName() == null) {
418 throw new IllegalArgumentException(
419 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
421 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
422 "Type Definitions Local Name cannot be NULL!");
424 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
425 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
426 final Module module = findParentModule(schemaContext, parentNode);
428 if (module != null) {
429 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
430 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
431 if (genTOs != null) {
432 return genTOs.get(typeDefinition.getQName().getLocalName());
440 * Gets base type definition for <code>extendTypeDef</code>. The method is
441 * recursively called until non <code>ExtendedType</code> type is found.
443 * @param extendTypeDef
444 * type definition for which is the base type definition sought
445 * @return type definition which is base type for <code>extendTypeDef</code>
446 * @throws IllegalArgumentException
447 * if <code>extendTypeDef</code> equal null
449 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
450 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
452 TypeDefinition<?> ret = extendTypeDef;
453 while (ret.getBaseType() != null) {
454 ret = ret.getBaseType();
461 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
463 * The path of <code>leafrefType</code> is followed to find referenced node
464 * and its <code>Type</code> is returned.
467 * leafref type definition for which is the type sought
468 * @return JAVA <code>Type</code> of data schema node which is referenced in
469 * <code>leafrefType</code>
470 * @throws IllegalArgumentException
472 * <li>if <code>leafrefType</code> equal null</li>
473 * <li>if path statement of <code>leafrefType</code> equal null</li>
477 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
478 Type returnType = null;
479 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
481 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
482 "The Path Statement for Leafref Type Definition cannot be NULL!");
484 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
485 final String strXPath = xpath.toString();
487 if (strXPath != null) {
488 if (strXPath.indexOf('[') == -1) {
489 final Module module = findParentModule(schemaContext, parentNode);
490 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
492 final SchemaNode dataNode;
493 if (xpath.isAbsolute()) {
494 dataNode = findDataSchemaNode(schemaContext, module, xpath);
496 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
498 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
499 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
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);
509 returnType = Types.typeForClass(Object.class);
512 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
513 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
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
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 = javaTypeForSchemaDefinitionType(innerTypeDefinition, typedef);
784 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
786 if (returnType != null) {
787 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
788 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
789 if (typeMap != null) {
790 if (typeMap.isEmpty()) {
791 typeMap = new HashMap<>(4);
792 modulesByDate.put(moduleRevision, typeMap);
794 typeMap.put(typedefName, returnType);
804 * Wraps base YANG type to generated TO.
806 * @param basePackageName
807 * string with name of package to which the module belongs
809 * type definition which is converted to the TO
811 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
812 * @return generated transfer object which represent<code>javaType</code>
814 private static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef, final Type javaType, final String moduleName) {
815 Preconditions.checkNotNull(javaType, "javaType cannot be null");
816 final String propertyName = "value";
818 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
819 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
820 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
821 genPropBuilder.setReturnType(javaType);
822 genTOBuilder.addEqualsIdentity(genPropBuilder);
823 genTOBuilder.addHashIdentity(genPropBuilder);
824 genTOBuilder.addToStringProperty(genPropBuilder);
825 if (typedef.getStatus() == Status.DEPRECATED) {
826 genTOBuilder.addAnnotation("", "Deprecated");
828 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
829 final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
830 addStringRegExAsConstant(genTOBuilder, regExps);
832 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
833 genTOBuilder.setTypedef(true);
834 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
835 return genTOBuilder.toInstance();
839 * Converts output list of generated TO builders to one TO builder (first
840 * from list) which contains the remaining builders as its enclosing TO.
842 * @param basePackageName
843 * string with name of package to which the module belongs
845 * type definition which should be of type
846 * <code>UnionTypeDefinition</code>
848 * string with name for generated TO
849 * @return generated TO builder with the list of enclosed generated TO
852 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
853 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
854 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
855 typedef, typeDefName, parentNode);
856 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
858 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
859 for (GeneratedTOBuilder genTOBuilder : builders) {
860 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
863 resultTOBuilder.addProperty("value").setReturnType(Types.CHAR_ARRAY);
864 return resultTOBuilder;
868 * Converts <code>typedef</code> to generated TO with
869 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
870 * added to generated TO builder as property.
872 * @param basePackageName
873 * string with name of package to which the module belongs
875 * type definition which should be of type
876 * <code>UnionTypeDefinition</code>
878 * string with name for generated TO
879 * @return generated TO builder which represents <code>typedef</code>
880 * @throws NullPointerException
882 * <li>if <code>basePackageName</code> is null</li>
883 * <li>if <code>typedef</code> is null</li>
884 * <li>if Qname of <code>typedef</code> is null</li>
887 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName, final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
888 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
889 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
890 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
892 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
893 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
894 final Module module = findParentModule(schemaContext, parentNode);
896 final GeneratedTOBuilderImpl unionGenTOBuilder;
897 if (typeDefName != null && !typeDefName.isEmpty()) {
898 final String typeName = BindingMapping.getClassName(typeDefName);
899 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
900 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
901 unionGenTOBuilder.setDescription(typedefDescription);
902 unionGenTOBuilder.setReference(typedef.getReference());
903 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
904 unionGenTOBuilder.setModuleName(module.getName());
906 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
909 generatedTOBuilders.add(unionGenTOBuilder);
910 unionGenTOBuilder.setIsUnion(true);
911 final List<String> regularExpressions = new ArrayList<String>();
912 for (final TypeDefinition<?> unionType : unionTypes) {
913 final String unionTypeName = unionType.getQName().getLocalName();
914 if (unionType.getBaseType() != null) {
915 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, regularExpressions,
917 } else if (unionType instanceof UnionTypeDefinition) {
918 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionTypeDefinition) unionType,
919 basePackageName, parentNode));
920 } else if (unionType instanceof EnumTypeDefinition) {
921 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
922 unionTypeName, unionGenTOBuilder);
923 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
925 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
926 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
929 if (!regularExpressions.isEmpty()) {
930 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
933 storeGenTO(typedef, unionGenTOBuilder, parentNode);
935 return generatedTOBuilders;
939 * Wraps code which handle case when union subtype is also of the type
940 * <code>UnionType</code>.
942 * In this case the new generated TO is created for union subtype (recursive
944 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
945 * String, SchemaNode)}
946 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
947 * <code>parentUnionGenTOBuilder</code> is created property which type is
948 * equal to new generated TO.
950 * @param parentUnionGenTOBuilder
951 * generated TO builder to which is the property with the child
952 * union subtype added
953 * @param basePackageName
954 * string with the name of the module package
955 * @param unionSubtype
956 * type definition which represents union subtype
957 * @return list of generated TO builders. The number of the builders can be
958 * bigger one due to recursive call of
959 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
961 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
962 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
963 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
964 basePackageName, unionSubtype, newTOBuilderName, parentNode);
966 final GeneratedPropertyBuilder propertyBuilder;
967 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
968 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
969 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
970 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
972 return subUnionGenTOBUilders;
976 * Wraps code which handle case when union subtype is of the type
977 * <code>ExtendedType</code>.
979 * If TO for this type already exists it is used for the creation of the
980 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
981 * type is used for the property creation.
983 * @param parentUnionGenTOBuilder
984 * generated TO builder in which new property is created
985 * @param unionSubtype
986 * type definition of the <code>ExtendedType</code> type which
987 * represents union subtype
988 * @param regularExpressions
989 * list of strings with the regular expressions
991 * parent Schema Node for Extended Subtype
994 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final TypeDefinition<?> unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
995 final String unionTypeName = unionSubtype.getQName().getLocalName();
996 final Type genTO = findGenTO(unionTypeName, unionSubtype);
998 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1000 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1001 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1002 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1004 if (javaType != null) {
1005 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1008 if (baseType instanceof StringTypeDefinition) {
1009 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
1015 * Searches for generated TO for <code>searchedTypeDef</code> type
1016 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1018 * @param searchedTypeName
1019 * string with name of <code>searchedTypeDef</code>
1020 * @return generated TO for <code>searchedTypeDef</code> or
1021 * <code>null</code> it it doesn't exist
1023 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1024 final Module typeModule = findParentModule(schemaContext, parentNode);
1025 if (typeModule != null && typeModule.getName() != null) {
1026 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1027 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1028 if (genTOs != null) {
1029 return genTOs.get(searchedTypeName);
1036 * Stores generated TO created from <code>genTOBuilder</code> for
1037 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1038 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1041 * type definition for which is <code>genTOBuilder</code> created
1042 * @param genTOBuilder
1043 * generated TO builder which is converted to generated TO and
1046 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1047 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1048 final Module parentModule = findParentModule(schemaContext, parentNode);
1049 if (parentModule != null && parentModule.getName() != null) {
1050 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1051 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1052 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1058 * Adds a new property with the name <code>propertyName</code> and with type
1059 * <code>type</code> to <code>unonGenTransObject</code>.
1061 * @param unionGenTransObject
1062 * generated TO to which should be property added
1064 * JAVA <code>type</code> of the property which should be added
1065 * to <code>unionGentransObject</code>
1066 * @param propertyName
1067 * string with name of property which should be added to
1068 * <code>unionGentransObject</code>
1070 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1071 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1072 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1073 .addProperty(BindingMapping.getPropertyName(propertyName));
1074 propBuilder.setReturnType(type);
1076 unionGenTransObject.addEqualsIdentity(propBuilder);
1077 unionGenTransObject.addHashIdentity(propBuilder);
1078 unionGenTransObject.addToStringProperty(propBuilder);
1083 * Converts <code>typedef</code> to the generated TO builder.
1085 * @param basePackageName
1086 * string with name of package to which the module belongs
1088 * type definition from which is the generated TO builder created
1089 * @return generated TO builder which contains data from
1090 * <code>typedef</code> and <code>basePackageName</code>
1092 private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef, final String moduleName) {
1094 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1095 final String typeDefTOName = typedef.getQName().getLocalName();
1097 if ((packageName != null) && (typeDefTOName != null)) {
1098 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1099 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1100 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
1102 newType.setDescription(typedefDescription);
1103 newType.setReference(typedef.getReference());
1104 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1105 newType.setModuleName(moduleName);
1113 * Converts <code>typeDef</code> which should be of the type
1114 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1116 * All the bits of the typeDef are added to returning generated TO as
1119 * @param basePackageName
1120 * string with name of package to which the module belongs
1122 * type definition from which is the generated TO builder created
1123 * @param typeDefName
1124 * string with the name for generated TO builder
1125 * @return generated TO builder which represents <code>typeDef</code>
1126 * @throws IllegalArgumentException
1128 * <li>if <code>typeDef</code> equals null</li>
1129 * <li>if <code>basePackageName</code> equals null</li>
1132 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName, final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1134 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1135 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1137 if (typeDef instanceof BitsTypeDefinition) {
1138 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1140 final String typeName = BindingMapping.getClassName(typeDefName);
1141 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1142 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1144 genTOBuilder.setDescription(typedefDescription);
1145 genTOBuilder.setReference(typeDef.getReference());
1146 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1147 genTOBuilder.setModuleName(moduleName);
1148 genTOBuilder.setBaseType(typeDef);
1150 final List<Bit> bitList = bitsTypeDefinition.getBits();
1151 GeneratedPropertyBuilder genPropertyBuilder;
1152 for (final Bit bit : bitList) {
1153 String name = bit.getName();
1154 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1155 genPropertyBuilder.setReadOnly(true);
1156 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1158 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1159 genTOBuilder.addHashIdentity(genPropertyBuilder);
1160 genTOBuilder.addToStringProperty(genPropertyBuilder);
1163 return genTOBuilder;
1169 * Converts the pattern constraints from <code>typedef</code> to the list of
1170 * the strings which represents these constraints.
1173 * extended type in which are the pattern constraints sought
1174 * @return list of strings which represents the constraint patterns
1175 * @throws IllegalArgumentException
1176 * if <code>typedef</code> equals null
1179 private static List<String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
1180 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1182 final List<PatternConstraint> patternConstraints;
1183 if (typedef instanceof StringTypeDefinition) {
1184 // FIXME: run diff against base
1185 patternConstraints = ((StringTypeDefinition) typedef).getPatternConstraints();
1187 patternConstraints = ImmutableList.of();
1190 final List<String> regExps = new ArrayList<>(patternConstraints.size());
1191 for (PatternConstraint patternConstraint : patternConstraints) {
1192 final String regEx = patternConstraint.getRegularExpression();
1193 final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1194 regExps.add(modifiedRegEx);
1202 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1203 * expressions from the <code>regularExpressions</code>
1205 * @param genTOBuilder
1206 * generated TO builder to which are
1207 * <code>regular expressions</code> added
1208 * @param regularExpressions
1209 * list of string which represent regular expressions
1210 * @throws IllegalArgumentException
1212 * <li>if <code>genTOBuilder</code> equals null</li>
1213 * <li>if <code>regularExpressions</code> equals null</li>
1216 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1217 if (genTOBuilder == null) {
1218 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1220 if (regularExpressions == null) {
1221 throw new IllegalArgumentException("List of regular expressions can't be null");
1223 if (!regularExpressions.isEmpty()) {
1224 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1225 regularExpressions);
1230 * Creates generated TO with data about inner extended type
1231 * <code>innerExtendedType</code>, about the package name
1232 * <code>typedefName</code> and about the generated TO name
1233 * <code>typedefName</code>.
1235 * It is supposed that <code>innerExtendedType</code> is already present in
1236 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1237 * be possible set it as extended type for the returning generated TO.
1241 * @param innerExtendedType
1242 * extended type which is part of some other extended type
1243 * @param basePackageName
1244 * string with the package name of the module
1247 * @return generated TO which extends generated TO for
1248 * <code>innerExtendedType</code>
1249 * @throws IllegalArgumentException
1251 * <li>if <code>extendedType</code> equals null</li>
1252 * <li>if <code>basePackageName</code> equals null</li>
1253 * <li>if <code>typedefName</code> equals null</li>
1256 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef, final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1257 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1258 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1260 final String typedefName = typedef.getQName().getLocalName();
1261 final String classTypedefName = BindingMapping.getClassName(typedefName);
1262 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1263 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1264 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
1266 genTOBuilder.setDescription(typedefDescription);
1267 genTOBuilder.setReference(typedef.getReference());
1268 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1269 genTOBuilder.setModuleName(moduleName);
1270 genTOBuilder.setTypedef(true);
1271 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1272 genTOBuilder.setRestrictions(r);
1273 if (typedef.getStatus() == Status.DEPRECATED) {
1274 genTOBuilder.addAnnotation("", "Deprecated");
1277 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1278 genTOBuilder.setIsUnion(true);
1281 Map<Date, Map<String, Type>> modulesByDate = null;
1282 Map<String, Type> typeMap = null;
1283 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1284 if (parentModule != null) {
1285 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1286 typeMap = modulesByDate.get(parentModule.getRevision());
1289 if (typeMap != null) {
1290 Type type = typeMap.get(innerTypeDef);
1291 if (type instanceof GeneratedTransferObject) {
1292 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1295 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1296 makeSerializable(genTOBuilder);
1298 return genTOBuilder.toInstance();
1302 * Add {@link Serializable} to implemented interfaces of this TO. Also
1303 * compute and add serialVersionUID property.
1306 * transfer object which needs to be serializable
1308 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1309 gto.addImplementsType(Types.typeForClass(Serializable.class));
1310 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1311 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1316 * Finds out for each type definition how many immersion (depth) is
1317 * necessary to get to the base type. Every type definition is inserted to
1318 * the map which key is depth and value is list of type definitions with
1319 * equal depth. In next step are lists from this map concatenated to one
1320 * list in ascending order according to their depth. All type definitions
1321 * are in the list behind all type definitions on which depends.
1323 * @param unsortedTypeDefinitions
1324 * list of type definitions which should be sorted by depth
1325 * @return list of type definitions sorted according their each other
1326 * dependencies (type definitions which are depend on other type
1327 * definitions are in list behind them).
1329 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1330 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1331 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1333 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1334 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1335 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1336 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1337 if (typeDefinitionsConcreteDepth == null) {
1338 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1339 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1341 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1344 // SortedMap guarantees order corresponding to keys in ascending order
1345 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1346 sortedTypeDefinition.addAll(v);
1349 return sortedTypeDefinition;
1353 * Returns how many immersion is necessary to get from the type definition
1356 * @param typeDefinition
1357 * type definition for which is depth sought.
1358 * @return number of immersions which are necessary to get from the type
1359 * definition to the base type
1361 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1362 // FIXME: rewrite this in a non-recursive manner
1363 if (typeDefinition == null) {
1366 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1367 if (baseType == null) {
1372 if (baseType.getBaseType() != null) {
1373 depth = depth + getTypeDefinitionDepth(baseType);
1374 } else if (baseType instanceof UnionTypeDefinition) {
1375 List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1376 int maxChildDepth = 0;
1378 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1379 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1380 if (childDepth > maxChildDepth) {
1381 maxChildDepth = childDepth;
1384 return maxChildDepth;
1390 * Returns string which contains the same value as <code>name</code> but
1391 * integer suffix is incremented by one. If <code>name</code> contains no
1392 * number suffix then number 1 is added.
1395 * string with name of augmented node
1396 * @return string with the number suffix incremented by one (or 1 is added)
1398 private static String provideAvailableNameForGenTOBuilder(final String name) {
1399 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1401 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1402 return name.substring(0, mtch.start()) + newSuffix;
1408 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1409 if (!Strings.isNullOrEmpty(units)) {
1410 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1411 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1412 prop.setReturnType(Types.STRING);
1413 to.addToStringProperty(prop);
1418 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1419 return getTypeDefaultConstruction(node, node.getDefault());
1422 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1423 TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1424 QName typeQName = type.getQName();
1425 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1426 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1427 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1430 StringBuilder sb = new StringBuilder();
1431 String result = null;
1432 if (base instanceof BinaryTypeDefinition) {
1433 result = binaryToDef(defaultValue);
1434 } else if (base instanceof BitsTypeDefinition) {
1437 Module parent = getParentModule(node);
1438 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1440 if (!(path.hasNext())) {
1441 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1442 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1443 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1445 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1446 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1447 parentName = BindingMapping.getClassName(parent.getName());
1448 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1450 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1451 } else if (base instanceof BooleanTypeDefinition) {
1452 result = typeToDef(Boolean.class, defaultValue);
1453 } else if (base instanceof DecimalTypeDefinition) {
1454 result = typeToDef(BigDecimal.class, defaultValue);
1455 } else if (base instanceof EmptyTypeDefinition) {
1456 result = typeToDef(Boolean.class, defaultValue);
1457 } else if (base instanceof EnumTypeDefinition) {
1458 char[] defValArray = defaultValue.toCharArray();
1459 char first = Character.toUpperCase(defaultValue.charAt(0));
1460 defValArray[0] = first;
1461 String newDefVal = new String(defValArray);
1463 if (type.getBaseType() != null) {
1464 Module m = getParentModule(type);
1465 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1466 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1467 className = packageName + "." + BindingMapping.getClassName(typeQName);
1469 Module parentModule = getParentModule(node);
1470 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1471 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1472 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1474 result = className + "." + newDefVal;
1475 } else if (base instanceof IdentityrefTypeDefinition) {
1476 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1477 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1478 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1479 } else if (BaseTypes.isInt8(base)) {
1480 result = typeToDef(Byte.class, defaultValue);
1481 } else if (BaseTypes.isInt16(base)) {
1482 result = typeToDef(Short.class, defaultValue);
1483 } else if (BaseTypes.isInt32(base)) {
1484 result = typeToDef(Integer.class, defaultValue);
1485 } else if (BaseTypes.isInt64(base)) {
1486 result = typeToDef(Long.class, defaultValue);
1487 } else if (base instanceof LeafrefTypeDefinition) {
1488 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1489 } else if (base instanceof StringTypeDefinition) {
1490 result = "\"" + defaultValue + "\"";
1491 } else if (BaseTypes.isUint8(base)) {
1492 result = typeToDef(Short.class, defaultValue);
1493 } else if (BaseTypes.isUint16(base)) {
1494 result = typeToDef(Integer.class, defaultValue);
1495 } else if (BaseTypes.isUint32(base)) {
1496 result = typeToDef(Long.class, defaultValue);
1497 } else if (BaseTypes.isUint64(base)) {
1498 result = typeToDef(BigInteger.class, defaultValue);
1499 } else if (base instanceof UnionTypeDefinition) {
1500 result = unionToDef(node);
1506 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1507 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1508 Module m = getParentModule(type);
1509 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1510 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1511 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1512 sb.insert(0, "new " + className + "(");
1513 sb.insert(sb.length(), ')');
1516 return sb.toString();
1519 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1520 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1523 private static String binaryToDef(final String defaultValue) {
1524 StringBuilder sb = new StringBuilder();
1525 BaseEncoding en = BaseEncoding.base64();
1526 byte[] encoded = en.decode(defaultValue);
1527 sb.append("new byte[] {");
1528 for (int i = 0; i < encoded.length; i++) {
1529 sb.append(encoded[i]);
1530 if (i != encoded.length - 1) {
1535 return sb.toString();
1538 private static final Comparator<Bit> BIT_NAME_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
1540 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1541 List<Bit> bits = new ArrayList<>(type.getBits());
1542 Collections.sort(bits, BIT_NAME_COMPARATOR);
1543 StringBuilder sb = new StringBuilder();
1546 sb.append(className);
1549 for (int i = 0; i < bits.size(); i++) {
1550 if (bits.get(i).getName().equals(defaultValue)) {
1555 if (i != bits.size() - 1) {
1562 return sb.toString();
1565 private Module getParentModule(final SchemaNode node) {
1566 QName qname = node.getPath().getPathFromRoot().iterator().next();
1567 URI namespace = qname.getNamespace();
1568 Date revision = qname.getRevision();
1569 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1572 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1573 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1574 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1575 "The Path Statement for Leafref Type Definition cannot be NULL!");
1577 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1578 final String strXPath = xpath.toString();
1580 if (strXPath != null) {
1581 if (strXPath.indexOf('[') == -1) {
1582 final Module module = findParentModule(schemaContext, parentNode);
1583 if (module != null) {
1584 final SchemaNode dataNode;
1585 if (xpath.isAbsolute()) {
1586 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1588 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1590 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1594 return "new java.lang.Object()";
1601 private String unionToDef(final LeafSchemaNode node) {
1602 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1606 if (type.getBaseType() != null) {
1607 QName typeQName = type.getQName();
1608 Module module = null;
1609 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1610 if (modules.size() > 1) {
1611 for (Module m : modules) {
1612 if (m.getRevision().equals(typeQName.getRevision())) {
1617 if (module == null) {
1618 List<Module> modulesList = new ArrayList<>(modules);
1619 Collections.sort(modulesList, (o1, o2) -> o1.getRevision().compareTo(o2.getRevision()));
1620 module = modulesList.get(0);
1623 module = modules.iterator().next();
1626 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1627 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1629 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1630 QName first = path.next();
1631 if (!(path.hasNext())) {
1632 URI namespace = first.getNamespace();
1633 Date revision = first.getRevision();
1634 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1635 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1636 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1637 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1639 URI namespace = first.getNamespace();
1640 Date revision = first.getRevision();
1641 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1642 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1643 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
1644 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1647 return union(className, node.getDefault(), node);
1650 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1651 StringBuilder sb = new StringBuilder();
1653 sb.append(className);
1655 sb.append(defaultValue);
1656 sb.append("\".toCharArray())");
1657 return sb.toString();
1661 public String getConstructorPropertyName(final SchemaNode node) {
1662 if (node instanceof TypeDefinition<?>) {
1670 public String getParamNameFromType(final TypeDefinition<?> type) {
1671 return BindingMapping.getPropertyName(type.getQName().getLocalName());