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.mdsal.binding.yang.types;
10 import static org.opendaylight.mdsal.binding.model.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.mdsal.binding.generator.spi.TypeProvider;
39 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
40 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
41 import org.opendaylight.mdsal.binding.model.api.Enumeration;
42 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
43 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
44 import org.opendaylight.mdsal.binding.model.api.Restrictions;
45 import org.opendaylight.mdsal.binding.model.api.Type;
46 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
47 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
48 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
49 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
50 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
51 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
52 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
53 import org.opendaylight.mdsal.binding.model.util.Types;
54 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.EnumerationBuilderImpl;
55 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
56 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTOBuilderImpl;
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.Status;
70 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
74 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
82 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
85 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
86 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
87 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
88 import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
92 public final class TypeProviderImpl implements TypeProvider {
93 private static final Logger LOG = LoggerFactory.getLogger(TypeProviderImpl.class);
94 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
96 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
97 // the case, as unions are emitted to their correct schema path.
98 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
99 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
102 * Contains the schema data red from YANG files.
104 private final SchemaContext schemaContext;
107 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
109 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
112 * The map which maps schema paths to JAVA <code>Type</code>.
114 private final Map<SchemaPath, Type> referencedTypes;
115 private final Map<Module, Set<Type>> additionalTypes;
118 * Creates new instance of class <code>TypeProviderImpl</code>.
120 * @param schemaContext
121 * contains the schema data red from YANG files
122 * @throws IllegalArgumentException
123 * if <code>schemaContext</code> equal null.
125 public TypeProviderImpl(final SchemaContext schemaContext) {
126 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
128 this.schemaContext = schemaContext;
129 this.genTypeDefsContextMap = new HashMap<>();
130 this.referencedTypes = new HashMap<>();
131 this.additionalTypes = new HashMap<>();
132 resolveTypeDefsFromContext();
136 * Puts <code>refType</code> to map with key <code>refTypePath</code>
139 * schema path used as the map key
141 * type which represents the map value
142 * @throws IllegalArgumentException
144 * <li>if <code>refTypePath</code> equal null</li>
145 * <li>if <code>refType</code> equal null</li>
149 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
150 Preconditions.checkArgument(refTypePath != null,
151 "Path reference of Enumeration Type Definition cannot be NULL!");
152 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
153 referencedTypes.put(refTypePath, refType);
156 public Map<Module, Set<Type>> getAdditionalTypes() {
157 return additionalTypes;
162 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
165 * string with YANG name of type
166 * @return JAVA <code>Type</code> for YANG type <code>type</code>
167 * @see TypeProvider#javaTypeForYangType(String)
171 public Type javaTypeForYangType(final String type) {
172 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
176 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
177 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
181 * Converts schema definition type <code>typeDefinition</code> to JAVA
184 * @param typeDefinition
185 * type definition which is converted to JAVA type
186 * @throws IllegalArgumentException
188 * <li>if <code>typeDefinition</code> equal null</li>
189 * <li>if Qname of <code>typeDefinition</code> equal null</li>
190 * <li>if name of <code>typeDefinition</code> equal null</li>
194 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode, final Restrictions r) {
195 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
196 Preconditions.checkArgument(typeDefinition.getQName() != null,
197 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
198 String typedefName = typeDefinition.getQName().getLocalName();
199 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
201 // Deal with base types
202 if (typeDefinition.getBaseType() == null) {
203 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
204 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
205 // a base type which holds these constraints.
206 if (typeDefinition instanceof DecimalTypeDefinition) {
207 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition, parentNode, r);
213 // Deal with leafrefs/identityrefs
214 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
219 // FIXME: it looks as though we could be using the same codepath as above...
220 ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName().getLocalName());
222 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
228 Type returnType = javaTypeForExtendedType(typeDefinition);
229 if (r != null && returnType instanceof GeneratedTransferObject) {
230 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
231 Module module = findParentModule(schemaContext, parentNode);
232 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
233 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
234 String genTOName = BindingMapping.getClassName(typedefName);
235 String name = packageName + "." + genTOName;
236 if (!(returnType.getFullyQualifiedName().equals(name))) {
237 returnType = shadedTOWithRestrictions(gto, r);
243 private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
244 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
245 GeneratedTransferObject parent = gto.getSuperType();
246 if (parent != null) {
247 gtob.setExtendsType(parent);
249 gtob.setRestrictions(r);
250 for (GeneratedProperty gp : gto.getProperties()) {
251 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
252 gpb.setValue(gp.getValue());
253 gpb.setReadOnly(gp.isReadOnly());
254 gpb.setAccessModifier(gp.getAccessModifier());
255 gpb.setReturnType(gp.getReturnType());
256 gpb.setFinal(gp.isFinal());
257 gpb.setStatic(gp.isStatic());
259 return gtob.toInstance();
262 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
263 final SchemaNode leafRefValueNode;
264 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
265 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
266 .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute());
268 ///// skip leafrefs in augments - they're checked once augments are resolved
269 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
270 boolean isAugmenting = false;
271 DataNodeContainer current = null;
272 DataSchemaNode dataChildByName;
274 while (iterator.hasNext() && !isAugmenting) {
275 final QName next = iterator.next();
276 if (current == null) {
277 dataChildByName = schemaContext.getDataChildByName(next);
279 dataChildByName = current.getDataChildByName(next);
281 if (dataChildByName != null) {
282 isAugmenting = dataChildByName.isAugmenting();
286 if (dataChildByName instanceof DataNodeContainer) {
287 current = (DataNodeContainer) dataChildByName;
295 Module parentModule = getParentModule(parentNode);
296 if (!leafRefStrippedXPath.isAbsolute()) {
297 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
298 parentNode, leafRefStrippedXPath);
300 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
302 return (leafRefValueNode != null) ? leafRefValueNode.equals(parentNode) : false;
306 * Returns JAVA <code>Type</code> for instances of the type
307 * <code>LeafrefTypeDefinition</code> or
308 * <code>IdentityrefTypeDefinition</code>.
310 * @param typeDefinition
311 * type definition which is converted to JAVA <code>Type</code>
312 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
314 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
315 if (typeDefinition instanceof LeafrefTypeDefinition) {
316 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
317 if (isLeafRefSelfReference(leafref, parentNode)) {
318 throw new YangValidationException("Leafref " + leafref.toString() + " is referencing itself, incoming" +
319 " StackOverFlowError detected.");
321 return provideTypeForLeafref(leafref, parentNode);
322 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
323 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
324 return provideTypeForIdentityref(idref);
331 * Returns JAVA <code>Type</code> for instances of the type
332 * <code>ExtendedType</code>.
334 * @param typeDefinition
335 * type definition which is converted to JAVA <code>Type</code>
336 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
338 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
339 final String typedefName = typeDefinition.getQName().getLocalName();
340 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
341 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
342 if (returnType == null) {
343 if (baseTypeDef instanceof EnumTypeDefinition) {
344 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
345 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
347 final Module module = findParentModule(schemaContext, typeDefinition);
348 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
349 if (module != null) {
350 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
351 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
352 if (genTOs != null) {
353 returnType = genTOs.get(typedefName);
355 if (returnType == null) {
356 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
357 baseTypeDef, typeDefinition, r);
366 * Seeks for identity reference <code>idref</code> the JAVA
367 * <code>type</code>.<br />
371 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
372 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
375 * identityref type definition for which JAVA <code>Type</code>
377 * @return JAVA <code>Type</code> of the identity which is refrenced through
380 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
381 QName baseIdQName = idref.getIdentity().getQName();
382 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
383 baseIdQName.getRevision());
384 IdentitySchemaNode identity = null;
385 for (IdentitySchemaNode id : module.getIdentities()) {
386 if (id.getQName().equals(baseIdQName)) {
390 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
392 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
393 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath());
394 final String genTypeName = BindingMapping.getClassName(identity.getQName());
396 Type baseType = Types.typeForClass(Class.class);
397 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
398 return Types.parameterizedTypeFor(baseType, paramType);
402 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
404 * @param typeDefinition
405 * type definition which should be converted to JAVA
407 * @return JAVA <code>Type</code> which represents
408 * <code>typeDefinition</code>
409 * @throws IllegalArgumentException
411 * <li>if <code>typeDefinition</code> equal null</li>
412 * <li>if Q name of <code>typeDefinition</code></li>
413 * <li>if name of <code>typeDefinition</code></li>
416 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
417 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
418 if (typeDefinition.getQName() == null) {
419 throw new IllegalArgumentException(
420 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
422 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
423 "Type Definitions Local Name cannot be NULL!");
425 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
426 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
427 final Module module = findParentModule(schemaContext, parentNode);
429 if (module != null) {
430 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
431 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
432 if (genTOs != null) {
433 return genTOs.get(typeDefinition.getQName().getLocalName());
441 * Gets base type definition for <code>extendTypeDef</code>. The method is
442 * recursively called until non <code>ExtendedType</code> type is found.
444 * @param extendTypeDef
445 * type definition for which is the base type definition sought
446 * @return type definition which is base type for <code>extendTypeDef</code>
447 * @throws IllegalArgumentException
448 * if <code>extendTypeDef</code> equal null
450 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
451 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
453 TypeDefinition<?> ret = extendTypeDef;
454 while (ret.getBaseType() != null) {
455 ret = ret.getBaseType();
462 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
464 * The path of <code>leafrefType</code> is followed to find referenced node
465 * and its <code>Type</code> is returned.
468 * leafref type definition for which is the type sought
469 * @return JAVA <code>Type</code> of data schema node which is referenced in
470 * <code>leafrefType</code>
471 * @throws IllegalArgumentException
473 * <li>if <code>leafrefType</code> equal null</li>
474 * <li>if path statement of <code>leafrefType</code> equal null</li>
478 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
479 Type returnType = null;
480 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
482 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
483 "The Path Statement for Leafref Type Definition cannot be NULL!");
485 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
486 final String strXPath = xpath.toString();
488 if (strXPath != null) {
489 if (strXPath.indexOf('[') == -1) {
490 final Module module = findParentModule(schemaContext, parentNode);
491 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
493 final SchemaNode dataNode;
494 if (xpath.isAbsolute()) {
495 dataNode = findDataSchemaNode(schemaContext, module, xpath);
497 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
499 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
500 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
502 if (leafContainsEnumDefinition(dataNode)) {
503 returnType = referencedTypes.get(dataNode.getPath());
504 } else if (leafListContainsEnumDefinition(dataNode)) {
505 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
507 returnType = resolveTypeFromDataSchemaNode(dataNode);
510 returnType = Types.typeForClass(Object.class);
513 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
514 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
519 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
520 * so then checks if it is of type <code>EnumTypeDefinition</code>.
523 * data schema node for which is checked if it is leaf and if it
525 * @return boolean value
527 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
528 * <li>false - other cases</li>
531 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
532 if (dataNode instanceof LeafSchemaNode) {
533 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
534 if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
542 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
543 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
546 * data schema node for which is checked if it is leaflist and if
548 * @return boolean value
550 * <li>true - if <code>dataNode</code> is leaflist of type
552 * <li>false - other cases</li>
555 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
556 if (dataNode instanceof LeafListSchemaNode) {
557 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
558 if (leafList.getType() instanceof EnumTypeDefinition) {
566 * Converts <code>enumTypeDef</code> to
571 * enumeration type definition which is converted to enumeration
573 * string with name which is used as the enumeration name
574 * @return enumeration type which is built with data (name, enum values)
575 * from <code>enumTypeDef</code>
576 * @throws IllegalArgumentException
578 * <li>if <code>enumTypeDef</code> equals null</li>
579 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
580 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
581 * <li>if name of <code>enumTypeDef</code> equal null</li>
584 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName, final SchemaNode parentNode) {
585 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
586 Preconditions.checkArgument(enumTypeDef.getValues() != null,
587 "EnumTypeDefinition MUST contain at least ONE value definition!");
588 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
589 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
590 "Local Name in EnumTypeDefinition QName cannot be NULL!");
592 final String enumerationName = BindingMapping.getClassName(enumName);
594 Module module = findParentModule(schemaContext, parentNode);
595 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
597 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
598 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
599 enumBuilder.setDescription(enumTypedefDescription);
600 enumBuilder.setReference(enumTypeDef.getReference());
601 enumBuilder.setModuleName(module.getName());
602 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
603 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
604 return enumBuilder.toInstance(null);
608 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
609 * taken from <code>enumTypeDef</code>.
612 * enumeration type definition is source of enumeration data for
613 * <code>typeBuilder</code>
615 * string with the name of enumeration
617 * generated type builder to which is enumeration added
618 * @return enumeration type which contains enumeration data form
619 * <code>enumTypeDef</code>
620 * @throws IllegalArgumentException
622 * <li>if <code>enumTypeDef</code> equals null</li>
623 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
624 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
625 * <li>if name of <code>enumTypeDef</code> equal null</li>
626 * <li>if name of <code>typeBuilder</code> equal null</li>
630 private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
631 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
632 Preconditions.checkArgument(enumTypeDef.getValues() != null,
633 "EnumTypeDefinition MUST contain at least ONE value definition!");
634 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
635 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
636 "Local Name in EnumTypeDefinition QName cannot be NULL!");
637 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
639 final String enumerationName = BindingMapping.getClassName(enumName);
641 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
642 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
643 enumBuilder.setDescription(enumTypedefDescription);
644 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
645 return enumBuilder.toInstance(enumBuilder);
649 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
652 * contains information about YANG type
653 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
655 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
656 Type returnType = null;
657 if (dataNode != null) {
658 if (dataNode instanceof LeafSchemaNode) {
659 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
660 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
661 returnType = javaTypeForSchemaDefinitionType(type, leaf);
662 } else if (dataNode instanceof LeafListSchemaNode) {
663 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
664 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
671 * Passes through all modules and through all its type definitions and
672 * convert it to generated types.
674 * The modules are firstly sorted by mutual dependencies. The modules are
675 * sequentially passed. All type definitions of a module are at the
676 * beginning sorted so that type definition with less amount of references
677 * to other type definition are processed first.<br />
678 * For each module is created mapping record in the map
679 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
680 * which map current module name to the map which maps type names to
681 * returned types (generated types).
684 private void resolveTypeDefsFromContext() {
685 final Set<Module> modules = schemaContext.getModules();
686 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
687 final Module[] modulesArray = new Module[modules.size()];
689 for (Module modul : modules) {
690 modulesArray[i++] = modul;
692 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
695 for (final Module module : modulesSortedByDependency) {
696 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
697 if (dateTypeMap == null) {
698 dateTypeMap = new HashMap<>();
700 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
701 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
704 for (final Module module : modulesSortedByDependency) {
705 if (module != null) {
706 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
707 if (basePackageName != null) {
708 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
709 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
710 if (listTypeDefinitions != null) {
711 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
712 typedefToGeneratedType(basePackageName, module, typedef);
722 * @param basePackageName
723 * string with name of package to which the module belongs
725 * string with the name of the module for to which the
726 * <code>typedef</code> belongs
728 * type definition of the node for which should be creted JAVA
729 * <code>Type</code> (usually generated TO)
730 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
731 * <code>null</code> value if <code>basePackageName</code> or
732 * <code>modulName</code> or <code>typedef</code> or Q name of
733 * <code>typedef</code> equals <code>null</code>
735 private Type typedefToGeneratedType(final String basePackageName, final Module module, final TypeDefinition<?> typedef) {
736 final String moduleName = module.getName();
737 final Date moduleRevision = module.getRevision();
738 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
739 final String typedefName = typedef.getQName().getLocalName();
740 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
741 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
742 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
743 Type returnType = null;
744 if (innerTypeDefinition.getBaseType() != null) {
745 returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName, module.getName());
746 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
747 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
748 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
749 genTOBuilder.setTypedef(true);
750 genTOBuilder.setIsUnion(true);
751 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
752 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
753 returnType = genTOBuilder.toInstance();
755 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
756 genTOBuilder.getName() + "Builder");
757 unionBuilder.setIsUnionBuilder(true);
758 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
759 method.setReturnType(returnType);
760 method.addParameter(Types.STRING, "defaultValue");
761 method.setAccessModifier(AccessModifier.PUBLIC);
762 method.setStatic(true);
763 Set<Type> types = additionalTypes.get(module);
765 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
766 additionalTypes.put(module, types);
768 types.add(unionBuilder.toInstance());
770 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
771 // enums are automatically Serializable
772 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
773 // TODO units for typedef enum
774 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
775 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
776 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
777 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
778 basePackageName, bitsTypeDefinition, typedefName, module.getName());
779 genTOBuilder.setTypedef(true);
780 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
781 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
782 returnType = genTOBuilder.toInstance();
784 final Type javaType = javaTypeForSchemaDefinitionType(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 (typedef.getStatus() == Status.DEPRECATED) {
827 genTOBuilder.addAnnotation("", "Deprecated");
829 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
830 final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
831 addStringRegExAsConstant(genTOBuilder, regExps);
833 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
834 genTOBuilder.setTypedef(true);
835 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
836 return genTOBuilder.toInstance();
840 * Converts output list of generated TO builders to one TO builder (first
841 * from list) which contains the remaining builders as its enclosing TO.
843 * @param basePackageName
844 * string with name of package to which the module belongs
846 * type definition which should be of type
847 * <code>UnionTypeDefinition</code>
849 * string with name for generated TO
850 * @return generated TO builder with the list of enclosed generated TO
853 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
854 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
855 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
856 typedef, typeDefName, parentNode);
857 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
859 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
860 for (GeneratedTOBuilder genTOBuilder : builders) {
861 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
864 resultTOBuilder.addProperty("value").setReturnType(Types.CHAR_ARRAY);
865 return resultTOBuilder;
869 * Converts <code>typedef</code> to generated TO with
870 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
871 * added to generated TO builder as property.
873 * @param basePackageName
874 * string with name of package to which the module belongs
876 * type definition which should be of type
877 * <code>UnionTypeDefinition</code>
879 * string with name for generated TO
880 * @return generated TO builder which represents <code>typedef</code>
881 * @throws NullPointerException
883 * <li>if <code>basePackageName</code> is null</li>
884 * <li>if <code>typedef</code> is null</li>
885 * <li>if Qname of <code>typedef</code> is null</li>
888 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName, final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
889 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
890 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
891 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
893 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
894 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
895 final Module module = findParentModule(schemaContext, parentNode);
897 final GeneratedTOBuilderImpl unionGenTOBuilder;
898 if (typeDefName != null && !typeDefName.isEmpty()) {
899 final String typeName = BindingMapping.getClassName(typeDefName);
900 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
901 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
902 unionGenTOBuilder.setDescription(typedefDescription);
903 unionGenTOBuilder.setReference(typedef.getReference());
904 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
905 unionGenTOBuilder.setModuleName(module.getName());
907 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
910 generatedTOBuilders.add(unionGenTOBuilder);
911 unionGenTOBuilder.setIsUnion(true);
912 final List<String> regularExpressions = new ArrayList<String>();
913 for (final TypeDefinition<?> unionType : unionTypes) {
914 final String unionTypeName = unionType.getQName().getLocalName();
915 if (unionType.getBaseType() != null) {
916 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, regularExpressions,
918 } else if (unionType instanceof UnionTypeDefinition) {
919 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionTypeDefinition) unionType,
920 basePackageName, parentNode));
921 } else if (unionType instanceof EnumTypeDefinition) {
922 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
923 unionTypeName, unionGenTOBuilder);
924 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
926 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
927 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
930 if (!regularExpressions.isEmpty()) {
931 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
934 storeGenTO(typedef, unionGenTOBuilder, parentNode);
936 return generatedTOBuilders;
940 * Wraps code which handle case when union subtype is also of the type
941 * <code>UnionType</code>.
943 * In this case the new generated TO is created for union subtype (recursive
945 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
946 * String, SchemaNode)}
947 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
948 * <code>parentUnionGenTOBuilder</code> is created property which type is
949 * equal to new generated TO.
951 * @param parentUnionGenTOBuilder
952 * generated TO builder to which is the property with the child
953 * union subtype added
954 * @param basePackageName
955 * string with the name of the module package
956 * @param unionSubtype
957 * type definition which represents union subtype
958 * @return list of generated TO builders. The number of the builders can be
959 * bigger one due to recursive call of
960 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
962 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
963 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
964 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
965 basePackageName, unionSubtype, newTOBuilderName, parentNode);
967 final GeneratedPropertyBuilder propertyBuilder;
968 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
969 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
970 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
971 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
973 return subUnionGenTOBUilders;
977 * Wraps code which handle case when union subtype is of the type
978 * <code>ExtendedType</code>.
980 * If TO for this type already exists it is used for the creation of the
981 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
982 * type is used for the property creation.
984 * @param parentUnionGenTOBuilder
985 * generated TO builder in which new property is created
986 * @param unionSubtype
987 * type definition of the <code>ExtendedType</code> type which
988 * represents union subtype
989 * @param regularExpressions
990 * list of strings with the regular expressions
992 * parent Schema Node for Extended Subtype
995 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final TypeDefinition<?> unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
996 final String unionTypeName = unionSubtype.getQName().getLocalName();
997 final Type genTO = findGenTO(unionTypeName, unionSubtype);
999 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1001 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1002 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1003 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1005 if (javaType != null) {
1006 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1009 if (baseType instanceof StringTypeDefinition) {
1010 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
1016 * Searches for generated TO for <code>searchedTypeDef</code> type
1017 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1019 * @param searchedTypeName
1020 * string with name of <code>searchedTypeDef</code>
1021 * @return generated TO for <code>searchedTypeDef</code> or
1022 * <code>null</code> it it doesn't exist
1024 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1025 final Module typeModule = findParentModule(schemaContext, parentNode);
1026 if (typeModule != null && typeModule.getName() != null) {
1027 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1028 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1029 if (genTOs != null) {
1030 return genTOs.get(searchedTypeName);
1037 * Stores generated TO created from <code>genTOBuilder</code> for
1038 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1039 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1042 * type definition for which is <code>genTOBuilder</code> created
1043 * @param genTOBuilder
1044 * generated TO builder which is converted to generated TO and
1047 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1048 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1049 final Module parentModule = findParentModule(schemaContext, parentNode);
1050 if (parentModule != null && parentModule.getName() != null) {
1051 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1052 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1053 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1059 * Adds a new property with the name <code>propertyName</code> and with type
1060 * <code>type</code> to <code>unonGenTransObject</code>.
1062 * @param unionGenTransObject
1063 * generated TO to which should be property added
1065 * JAVA <code>type</code> of the property which should be added
1066 * to <code>unionGentransObject</code>
1067 * @param propertyName
1068 * string with name of property which should be added to
1069 * <code>unionGentransObject</code>
1071 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1072 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1073 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1074 .addProperty(BindingMapping.getPropertyName(propertyName));
1075 propBuilder.setReturnType(type);
1077 unionGenTransObject.addEqualsIdentity(propBuilder);
1078 unionGenTransObject.addHashIdentity(propBuilder);
1079 unionGenTransObject.addToStringProperty(propBuilder);
1084 * Converts <code>typedef</code> to the generated TO builder.
1086 * @param basePackageName
1087 * string with name of package to which the module belongs
1089 * type definition from which is the generated TO builder created
1090 * @return generated TO builder which contains data from
1091 * <code>typedef</code> and <code>basePackageName</code>
1093 private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef, final String moduleName) {
1095 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1096 final String typeDefTOName = typedef.getQName().getLocalName();
1098 if ((packageName != null) && (typeDefTOName != null)) {
1099 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1100 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1101 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
1103 newType.setDescription(typedefDescription);
1104 newType.setReference(typedef.getReference());
1105 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1106 newType.setModuleName(moduleName);
1114 * Converts <code>typeDef</code> which should be of the type
1115 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1117 * All the bits of the typeDef are added to returning generated TO as
1120 * @param basePackageName
1121 * string with name of package to which the module belongs
1123 * type definition from which is the generated TO builder created
1124 * @param typeDefName
1125 * string with the name for generated TO builder
1126 * @return generated TO builder which represents <code>typeDef</code>
1127 * @throws IllegalArgumentException
1129 * <li>if <code>typeDef</code> equals null</li>
1130 * <li>if <code>basePackageName</code> equals null</li>
1133 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName, final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1135 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1136 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1138 if (typeDef instanceof BitsTypeDefinition) {
1139 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1141 final String typeName = BindingMapping.getClassName(typeDefName);
1142 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1143 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1145 genTOBuilder.setDescription(typedefDescription);
1146 genTOBuilder.setReference(typeDef.getReference());
1147 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1148 genTOBuilder.setModuleName(moduleName);
1149 genTOBuilder.setBaseType(typeDef);
1151 final List<Bit> bitList = bitsTypeDefinition.getBits();
1152 GeneratedPropertyBuilder genPropertyBuilder;
1153 for (final Bit bit : bitList) {
1154 String name = bit.getName();
1155 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1156 genPropertyBuilder.setReadOnly(true);
1157 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1159 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1160 genTOBuilder.addHashIdentity(genPropertyBuilder);
1161 genTOBuilder.addToStringProperty(genPropertyBuilder);
1164 return genTOBuilder;
1170 * Converts the pattern constraints from <code>typedef</code> to the list of
1171 * the strings which represents these constraints.
1174 * extended type in which are the pattern constraints sought
1175 * @return list of strings which represents the constraint patterns
1176 * @throws IllegalArgumentException
1177 * if <code>typedef</code> equals null
1180 private static List<String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
1181 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1183 final List<PatternConstraint> patternConstraints;
1184 if (typedef instanceof StringTypeDefinition) {
1185 // FIXME: run diff against base
1186 patternConstraints = ((StringTypeDefinition) typedef).getPatternConstraints();
1188 patternConstraints = ImmutableList.of();
1191 final List<String> regExps = new ArrayList<>(patternConstraints.size());
1192 for (PatternConstraint patternConstraint : patternConstraints) {
1193 final String regEx = patternConstraint.getRegularExpression();
1194 final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1195 regExps.add(modifiedRegEx);
1203 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1204 * expressions from the <code>regularExpressions</code>
1206 * @param genTOBuilder
1207 * generated TO builder to which are
1208 * <code>regular expressions</code> added
1209 * @param regularExpressions
1210 * list of string which represent regular expressions
1211 * @throws IllegalArgumentException
1213 * <li>if <code>genTOBuilder</code> equals null</li>
1214 * <li>if <code>regularExpressions</code> equals null</li>
1217 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1218 if (genTOBuilder == null) {
1219 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1221 if (regularExpressions == null) {
1222 throw new IllegalArgumentException("List of regular expressions can't be null");
1224 if (!regularExpressions.isEmpty()) {
1225 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1226 regularExpressions);
1231 * Creates generated TO with data about inner extended type
1232 * <code>innerExtendedType</code>, about the package name
1233 * <code>typedefName</code> and about the generated TO name
1234 * <code>typedefName</code>.
1236 * It is supposed that <code>innerExtendedType</code> is already present in
1237 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1238 * be possible set it as extended type for the returning generated TO.
1242 * @param innerExtendedType
1243 * extended type which is part of some other extended type
1244 * @param basePackageName
1245 * string with the package name of the module
1248 * @return generated TO which extends generated TO for
1249 * <code>innerExtendedType</code>
1250 * @throws IllegalArgumentException
1252 * <li>if <code>extendedType</code> equals null</li>
1253 * <li>if <code>basePackageName</code> equals null</li>
1254 * <li>if <code>typedefName</code> equals null</li>
1257 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef, final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1258 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1259 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1261 final String typedefName = typedef.getQName().getLocalName();
1262 final String classTypedefName = BindingMapping.getClassName(typedefName);
1263 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1264 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1265 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
1267 genTOBuilder.setDescription(typedefDescription);
1268 genTOBuilder.setReference(typedef.getReference());
1269 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1270 genTOBuilder.setModuleName(moduleName);
1271 genTOBuilder.setTypedef(true);
1272 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1273 genTOBuilder.setRestrictions(r);
1274 if (typedef.getStatus() == Status.DEPRECATED) {
1275 genTOBuilder.addAnnotation("", "Deprecated");
1278 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1279 genTOBuilder.setIsUnion(true);
1282 Map<Date, Map<String, Type>> modulesByDate = null;
1283 Map<String, Type> typeMap = null;
1284 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1285 if (parentModule != null) {
1286 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1287 typeMap = modulesByDate.get(parentModule.getRevision());
1290 if (typeMap != null) {
1291 Type type = typeMap.get(innerTypeDef);
1292 if (type instanceof GeneratedTransferObject) {
1293 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1296 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1297 makeSerializable(genTOBuilder);
1299 return genTOBuilder.toInstance();
1303 * Add {@link Serializable} to implemented interfaces of this TO. Also
1304 * compute and add serialVersionUID property.
1307 * transfer object which needs to be serializable
1309 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1310 gto.addImplementsType(Types.typeForClass(Serializable.class));
1311 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1312 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1317 * Finds out for each type definition how many immersion (depth) is
1318 * necessary to get to the base type. Every type definition is inserted to
1319 * the map which key is depth and value is list of type definitions with
1320 * equal depth. In next step are lists from this map concatenated to one
1321 * list in ascending order according to their depth. All type definitions
1322 * are in the list behind all type definitions on which depends.
1324 * @param unsortedTypeDefinitions
1325 * list of type definitions which should be sorted by depth
1326 * @return list of type definitions sorted according their each other
1327 * dependencies (type definitions which are depend on other type
1328 * definitions are in list behind them).
1330 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1331 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1332 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1334 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1335 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1336 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1337 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1338 if (typeDefinitionsConcreteDepth == null) {
1339 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1340 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1342 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1345 // SortedMap guarantees order corresponding to keys in ascending order
1346 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1347 sortedTypeDefinition.addAll(v);
1350 return sortedTypeDefinition;
1354 * Returns how many immersion is necessary to get from the type definition
1357 * @param typeDefinition
1358 * type definition for which is depth sought.
1359 * @return number of immersions which are necessary to get from the type
1360 * definition to the base type
1362 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1363 // FIXME: rewrite this in a non-recursive manner
1364 if (typeDefinition == null) {
1367 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1368 if (baseType == null) {
1373 if (baseType.getBaseType() != null) {
1374 depth = depth + getTypeDefinitionDepth(baseType);
1375 } else if (baseType instanceof UnionTypeDefinition) {
1376 List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1377 int maxChildDepth = 0;
1379 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1380 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1381 if (childDepth > maxChildDepth) {
1382 maxChildDepth = childDepth;
1385 return maxChildDepth;
1391 * Returns string which contains the same value as <code>name</code> but
1392 * integer suffix is incremented by one. If <code>name</code> contains no
1393 * number suffix then number 1 is added.
1396 * string with name of augmented node
1397 * @return string with the number suffix incremented by one (or 1 is added)
1399 private static String provideAvailableNameForGenTOBuilder(final String name) {
1400 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1402 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1403 return name.substring(0, mtch.start()) + newSuffix;
1409 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1410 if (!Strings.isNullOrEmpty(units)) {
1411 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1412 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1413 prop.setReturnType(Types.STRING);
1414 to.addToStringProperty(prop);
1419 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1420 return getTypeDefaultConstruction(node, node.getDefault());
1423 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1424 TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1425 QName typeQName = type.getQName();
1426 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1427 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1428 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1431 StringBuilder sb = new StringBuilder();
1432 String result = null;
1433 if (base instanceof BinaryTypeDefinition) {
1434 result = binaryToDef(defaultValue);
1435 } else if (base instanceof BitsTypeDefinition) {
1438 Module parent = getParentModule(node);
1439 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1441 if (!(path.hasNext())) {
1442 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1443 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1444 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1446 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1447 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1448 parentName = BindingMapping.getClassName(parent.getName());
1449 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1451 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1452 } else if (base instanceof BooleanTypeDefinition) {
1453 result = typeToBooleanDef(defaultValue);
1454 } else if (base instanceof DecimalTypeDefinition) {
1455 result = typeToDef(BigDecimal.class, defaultValue);
1456 } else if (base instanceof EmptyTypeDefinition) {
1457 result = typeToBooleanDef(defaultValue);
1458 } else if (base instanceof EnumTypeDefinition) {
1459 char[] defValArray = defaultValue.toCharArray();
1460 char first = Character.toUpperCase(defaultValue.charAt(0));
1461 defValArray[0] = first;
1462 String newDefVal = new String(defValArray);
1464 if (type.getBaseType() != null) {
1465 Module m = getParentModule(type);
1466 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1467 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1468 className = packageName + "." + BindingMapping.getClassName(typeQName);
1470 Module parentModule = getParentModule(node);
1471 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1472 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1473 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1475 result = className + "." + newDefVal;
1476 } else if (base instanceof IdentityrefTypeDefinition) {
1477 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1478 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1479 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1480 } else if (BaseTypes.isInt8(base)) {
1481 result = typeToValueOfDef(Byte.class, defaultValue);
1482 } else if (BaseTypes.isInt16(base)) {
1483 result = typeToValueOfDef(Short.class, defaultValue);
1484 } else if (BaseTypes.isInt32(base)) {
1485 result = typeToValueOfDef(Integer.class, defaultValue);
1486 } else if (BaseTypes.isInt64(base)) {
1487 result = typeToValueOfDef(Long.class, defaultValue);
1488 } else if (base instanceof LeafrefTypeDefinition) {
1489 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1490 } else if (base instanceof StringTypeDefinition) {
1491 result = "\"" + defaultValue + "\"";
1492 } else if (BaseTypes.isUint8(base)) {
1493 result = typeToValueOfDef(Short.class, defaultValue);
1494 } else if (BaseTypes.isUint16(base)) {
1495 result = typeToValueOfDef(Integer.class, defaultValue);
1496 } else if (BaseTypes.isUint32(base)) {
1497 result = typeToValueOfDef(Long.class, defaultValue);
1498 } else if (BaseTypes.isUint64(base)) {
1499 switch (defaultValue) {
1501 result = "java.math.BigInteger.ZERO";
1504 result = "java.math.BigInteger.ONE";
1507 result = "java.math.BigInteger.TEN";
1510 result = typeToDef(BigInteger.class, defaultValue);
1512 } else if (base instanceof UnionTypeDefinition) {
1513 result = unionToDef(node);
1519 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1520 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1521 Module m = getParentModule(type);
1522 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1523 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1524 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1525 sb.insert(0, "new " + className + "(");
1526 sb.insert(sb.length(), ')');
1529 return sb.toString();
1532 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1533 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1536 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1537 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1540 private static String typeToBooleanDef(final String defaultValue) {
1541 switch (defaultValue) {
1543 return "java.lang.Boolean.FALSE";
1545 return "java.lang.Boolean.TRUE";
1547 return typeToValueOfDef(Boolean.class, defaultValue);
1551 private static String binaryToDef(final String defaultValue) {
1552 StringBuilder sb = new StringBuilder();
1553 BaseEncoding en = BaseEncoding.base64();
1554 byte[] encoded = en.decode(defaultValue);
1555 sb.append("new byte[] {");
1556 for (int i = 0; i < encoded.length; i++) {
1557 sb.append(encoded[i]);
1558 if (i != encoded.length - 1) {
1563 return sb.toString();
1566 private static final Comparator<Bit> BIT_NAME_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
1568 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1569 List<Bit> bits = new ArrayList<>(type.getBits());
1570 Collections.sort(bits, BIT_NAME_COMPARATOR);
1571 StringBuilder sb = new StringBuilder();
1574 sb.append(className);
1577 for (int i = 0; i < bits.size(); i++) {
1578 if (bits.get(i).getName().equals(defaultValue)) {
1583 if (i != bits.size() - 1) {
1590 return sb.toString();
1593 private Module getParentModule(final SchemaNode node) {
1594 QName qname = node.getPath().getPathFromRoot().iterator().next();
1595 URI namespace = qname.getNamespace();
1596 Date revision = qname.getRevision();
1597 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1600 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1601 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1602 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1603 "The Path Statement for Leafref Type Definition cannot be NULL!");
1605 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1606 final String strXPath = xpath.toString();
1608 if (strXPath != null) {
1609 if (strXPath.indexOf('[') == -1) {
1610 final Module module = findParentModule(schemaContext, parentNode);
1611 if (module != null) {
1612 final SchemaNode dataNode;
1613 if (xpath.isAbsolute()) {
1614 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1616 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1618 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1622 return "new java.lang.Object()";
1629 private String unionToDef(final LeafSchemaNode node) {
1630 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1634 if (type.getBaseType() != null) {
1635 QName typeQName = type.getQName();
1636 Module module = null;
1637 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1638 if (modules.size() > 1) {
1639 for (Module m : modules) {
1640 if (m.getRevision().equals(typeQName.getRevision())) {
1645 if (module == null) {
1646 List<Module> modulesList = new ArrayList<>(modules);
1647 Collections.sort(modulesList, (o1, o2) -> o1.getRevision().compareTo(o2.getRevision()));
1648 module = modulesList.get(0);
1651 module = modules.iterator().next();
1654 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1655 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1657 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1658 QName first = path.next();
1659 if (!(path.hasNext())) {
1660 URI namespace = first.getNamespace();
1661 Date revision = first.getRevision();
1662 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1663 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1664 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1665 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1667 URI namespace = first.getNamespace();
1668 Date revision = first.getRevision();
1669 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1670 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1671 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
1672 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1675 return union(className, node.getDefault(), node);
1678 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1679 StringBuilder sb = new StringBuilder();
1681 sb.append(className);
1683 sb.append(defaultValue);
1684 sb.append("\".toCharArray())");
1685 return sb.toString();
1689 public String getConstructorPropertyName(final SchemaNode node) {
1690 if (node instanceof TypeDefinition<?>) {
1698 public String getParamNameFromType(final TypeDefinition<?> type) {
1699 return BindingMapping.getPropertyName(type.getQName().getLocalName());