2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.sal.binding.yang.types;
10 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
11 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
12 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.Sets;
17 import com.google.common.io.BaseEncoding;
18 import java.io.Serializable;
19 import java.math.BigDecimal;
20 import java.math.BigInteger;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
32 import java.util.TreeMap;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35 import org.apache.commons.lang3.StringEscapeUtils;
36 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
37 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
38 import org.opendaylight.yangtools.binding.generator.util.Types;
39 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
40 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
41 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
42 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
43 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
44 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
45 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
46 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty;
47 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
48 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
49 import org.opendaylight.yangtools.sal.binding.model.api.Type;
50 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
51 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
53 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
54 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
55 import org.opendaylight.yangtools.yang.binding.BindingMapping;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.Module;
63 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
67 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
69 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
71 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
79 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
82 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
83 import org.opendaylight.yangtools.yang.model.util.Int16;
84 import org.opendaylight.yangtools.yang.model.util.Int32;
85 import org.opendaylight.yangtools.yang.model.util.Int64;
86 import org.opendaylight.yangtools.yang.model.util.Int8;
87 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
88 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
89 import org.opendaylight.yangtools.yang.model.util.StringType;
90 import org.opendaylight.yangtools.yang.model.util.Uint16;
91 import org.opendaylight.yangtools.yang.model.util.Uint32;
92 import org.opendaylight.yangtools.yang.model.util.Uint64;
93 import org.opendaylight.yangtools.yang.model.util.Uint8;
94 import org.opendaylight.yangtools.yang.model.util.UnionType;
95 import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
99 public final class TypeProviderImpl implements TypeProvider {
100 private static final Logger LOG = LoggerFactory.getLogger(TypeProviderImpl.class);
101 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
104 * Contains the schema data red from YANG files.
106 private final SchemaContext schemaContext;
109 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
111 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
114 * The map which maps schema paths to JAVA <code>Type</code>.
116 private final Map<SchemaPath, Type> referencedTypes;
117 private final Map<Module, Set<Type>> additionalTypes;
120 * Creates new instance of class <code>TypeProviderImpl</code>.
122 * @param schemaContext
123 * contains the schema data red from YANG files
124 * @throws IllegalArgumentException
125 * if <code>schemaContext</code> equal null.
127 public TypeProviderImpl(final SchemaContext schemaContext) {
128 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
130 this.schemaContext = schemaContext;
131 this.genTypeDefsContextMap = new HashMap<>();
132 this.referencedTypes = new HashMap<>();
133 this.additionalTypes = new HashMap<>();
134 resolveTypeDefsFromContext();
138 * Puts <code>refType</code> to map with key <code>refTypePath</code>
141 * schema path used as the map key
143 * type which represents the map value
144 * @throws IllegalArgumentException
146 * <li>if <code>refTypePath</code> equal null</li>
147 * <li>if <code>refType</code> equal null</li>
151 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
152 Preconditions.checkArgument(refTypePath != null,
153 "Path reference of Enumeration Type Definition cannot be NULL!");
154 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
155 referencedTypes.put(refTypePath, refType);
158 public Map<Module, Set<Type>> getAdditionalTypes() {
159 return additionalTypes;
164 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
167 * string with YANG name of type
168 * @return JAVA <code>Type</code> for YANG type <code>type</code>
169 * @see TypeProvider#javaTypeForYangType(String)
173 public Type javaTypeForYangType(final String type) {
174 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
178 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
179 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
183 * Converts schema definition type <code>typeDefinition</code> to JAVA
186 * @param typeDefinition
187 * type definition which is converted to JAVA type
188 * @throws IllegalArgumentException
190 * <li>if <code>typeDefinition</code> equal null</li>
191 * <li>if Qname of <code>typeDefinition</code> equal null</li>
192 * <li>if name of <code>typeDefinition</code> equal null</li>
196 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
197 final Restrictions r) {
198 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
199 Preconditions.checkArgument(typeDefinition.getQName() != null,
200 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
201 String typedefName = typeDefinition.getQName().getLocalName();
202 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
204 // Deal with leafrefs/identityrefs first
205 Type returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
206 if (returnType != null) {
210 if (typeDefinition.getBaseType() == null) {
211 // Now deal with base types
212 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
214 if (returnType == null) {
215 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
218 // FIXME: what about base types with restrictions?
222 returnType = javaTypeForExtendedType(typeDefinition);
223 if (r != null && returnType instanceof GeneratedTransferObject) {
224 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
225 Module module = findParentModule(schemaContext, parentNode);
226 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
227 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
228 typeDefinition.getPath());
229 String genTOName = BindingMapping.getClassName(typedefName);
230 String name = packageName + "." + genTOName;
231 if (!(returnType.getFullyQualifiedName().equals(name))) {
232 returnType = shadedTOWithRestrictions(gto, r);
238 private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
239 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
240 GeneratedTransferObject parent = gto.getSuperType();
241 if (parent != null) {
242 gtob.setExtendsType(parent);
244 gtob.setRestrictions(r);
245 for (GeneratedProperty gp : gto.getProperties()) {
246 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
247 gpb.setValue(gp.getValue());
248 gpb.setReadOnly(gp.isReadOnly());
249 gpb.setAccessModifier(gp.getAccessModifier());
250 gpb.setReturnType(gp.getReturnType());
251 gpb.setFinal(gp.isFinal());
252 gpb.setStatic(gp.isStatic());
254 return gtob.toInstance();
257 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
258 final SchemaNode leafRefValueNode;
259 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
260 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
261 .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute());
263 ///// skip leafrefs in augments - they're checked once augments are resolved
264 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
265 boolean isAugmenting = false;
266 DataNodeContainer current = null;
267 DataSchemaNode dataChildByName;
269 while (iterator.hasNext() && !isAugmenting) {
270 final QName next = iterator.next();
271 if (current == null) {
272 dataChildByName = schemaContext.getDataChildByName(next);
274 dataChildByName = current.getDataChildByName(next);
276 if (dataChildByName != null) {
277 isAugmenting = dataChildByName.isAugmenting();
281 if (dataChildByName instanceof DataNodeContainer) {
282 current = (DataNodeContainer) dataChildByName;
290 Module parentModule = getParentModule(parentNode);
291 if (!leafRefStrippedXPath.isAbsolute()) {
292 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
293 parentNode, leafRefStrippedXPath);
295 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
297 return (leafRefValueNode != null) ? leafRefValueNode.equals(parentNode) : false;
301 * Returns JAVA <code>Type</code> for instances of the type
302 * <code>LeafrefTypeDefinition</code> or
303 * <code>IdentityrefTypeDefinition</code>.
305 * @param typeDefinition
306 * type definition which is converted to JAVA <code>Type</code>
307 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
309 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
310 if (typeDefinition instanceof LeafrefTypeDefinition) {
311 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
312 if (isLeafRefSelfReference(leafref, parentNode)) {
313 throw new YangValidationException("Leafref " + leafref.toString() + " is referencing itself, incoming" +
314 " StackOverFlowError detected.");
316 return provideTypeForLeafref(leafref, parentNode);
317 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
318 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
319 return provideTypeForIdentityref(idref);
326 * Returns JAVA <code>Type</code> for instances of the type
327 * <code>ExtendedType</code>.
329 * @param typeDefinition
330 * type definition which is converted to JAVA <code>Type</code>
331 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
333 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
334 final String typedefName = typeDefinition.getQName().getLocalName();
335 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
336 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
337 if (returnType == null) {
338 if (baseTypeDef instanceof EnumTypeDefinition) {
339 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
340 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
342 final Module module = findParentModule(schemaContext, typeDefinition);
343 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
344 if (module != null) {
345 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
346 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
347 if (genTOs != null) {
348 returnType = genTOs.get(typedefName);
350 if (returnType == null) {
351 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
352 baseTypeDef, typeDefinition, r);
361 * Seeks for identity reference <code>idref</code> the JAVA
362 * <code>type</code>.<br />
366 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
367 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
370 * identityref type definition for which JAVA <code>Type</code>
372 * @return JAVA <code>Type</code> of the identity which is refrenced through
375 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
376 QName baseIdQName = idref.getIdentity().getQName();
377 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
378 baseIdQName.getRevision());
379 IdentitySchemaNode identity = null;
380 for (IdentitySchemaNode id : module.getIdentities()) {
381 if (id.getQName().equals(baseIdQName)) {
385 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
387 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
388 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath());
389 final String genTypeName = BindingMapping.getClassName(identity.getQName());
391 Type baseType = Types.typeForClass(Class.class);
392 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
393 return Types.parameterizedTypeFor(baseType, paramType);
397 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
399 * @param typeDefinition
400 * type definition which should be converted to JAVA
402 * @return JAVA <code>Type</code> which represents
403 * <code>typeDefinition</code>
404 * @throws IllegalArgumentException
406 * <li>if <code>typeDefinition</code> equal null</li>
407 * <li>if Q name of <code>typeDefinition</code></li>
408 * <li>if name of <code>typeDefinition</code></li>
411 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
412 final SchemaNode parentNode) {
413 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
414 if (typeDefinition.getQName() == null) {
415 throw new IllegalArgumentException(
416 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
418 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
419 "Type Definitions Local Name cannot be NULL!");
421 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
422 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
423 final Module module = findParentModule(schemaContext, parentNode);
425 if (module != null) {
426 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
427 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
428 if (genTOs != null) {
429 return genTOs.get(typeDefinition.getQName().getLocalName());
437 * Gets base type definition for <code>extendTypeDef</code>. The method is
438 * recursively called until non <code>ExtendedType</code> type is found.
440 * @param extendTypeDef
441 * type definition for which is the base type definition sought
442 * @return type definition which is base type for <code>extendTypeDef</code>
443 * @throws IllegalArgumentException
444 * if <code>extendTypeDef</code> equal null
446 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
447 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
449 TypeDefinition<?> ret = extendTypeDef;
450 while (ret.getBaseType() != null) {
451 ret = ret.getBaseType();
458 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
460 * The path of <code>leafrefType</code> is followed to find referenced node
461 * and its <code>Type</code> is returned.
464 * leafref type definition for which is the type sought
465 * @return JAVA <code>Type</code> of data schema node which is referenced in
466 * <code>leafrefType</code>
467 * @throws IllegalArgumentException
469 * <li>if <code>leafrefType</code> equal null</li>
470 * <li>if path statement of <code>leafrefType</code> equal null</li>
474 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
475 Type returnType = null;
476 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
478 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
479 "The Path Statement for Leafref Type Definition cannot be NULL!");
481 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
482 final String strXPath = xpath.toString();
484 if (strXPath != null) {
485 if (strXPath.indexOf('[') == -1) {
486 final Module module = findParentModule(schemaContext, parentNode);
487 if (module != null) {
488 final SchemaNode dataNode;
489 if (xpath.isAbsolute()) {
490 dataNode = findDataSchemaNode(schemaContext, module, xpath);
492 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
495 if (leafContainsEnumDefinition(dataNode)) {
496 returnType = referencedTypes.get(dataNode.getPath());
497 } else if (leafListContainsEnumDefinition(dataNode)) {
498 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
500 returnType = resolveTypeFromDataSchemaNode(dataNode);
504 returnType = Types.typeForClass(Object.class);
507 if (returnType == null) {
508 throw new IllegalArgumentException("Failed to find leafref target: " + strXPath);
514 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
515 * so then checks if it is of type <code>EnumTypeDefinition</code>.
518 * data schema node for which is checked if it is leaf and if it
520 * @return boolean value
522 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
523 * <li>false - other cases</li>
526 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
527 if (dataNode instanceof LeafSchemaNode) {
528 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
529 if (leaf.getType() instanceof EnumTypeDefinition) {
537 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
538 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
541 * data schema node for which is checked if it is leaflist and if
543 * @return boolean value
545 * <li>true - if <code>dataNode</code> is leaflist of type
547 * <li>false - other cases</li>
550 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
551 if (dataNode instanceof LeafListSchemaNode) {
552 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
553 if (leafList.getType() instanceof EnumTypeDefinition) {
561 * Converts <code>enumTypeDef</code> to
562 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
566 * enumeration type definition which is converted to enumeration
568 * string with name which is used as the enumeration name
569 * @return enumeration type which is built with data (name, enum values)
570 * from <code>enumTypeDef</code>
571 * @throws IllegalArgumentException
573 * <li>if <code>enumTypeDef</code> equals null</li>
574 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
575 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
576 * <li>if name of <code>enumTypeDef</code> equal null</li>
579 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
580 final SchemaNode parentNode) {
581 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
582 Preconditions.checkArgument(enumTypeDef.getValues() != null,
583 "EnumTypeDefinition MUST contain at least ONE value definition!");
584 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
585 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
586 "Local Name in EnumTypeDefinition QName cannot be NULL!");
588 final String enumerationName = BindingMapping.getClassName(enumName);
590 Module module = findParentModule(schemaContext, parentNode);
591 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
593 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
594 enumBuilder.setDescription(enumTypeDef.getDescription());
595 enumBuilder.setReference(enumTypeDef.getReference());
596 enumBuilder.setModuleName(module.getName());
597 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
598 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
599 return enumBuilder.toInstance(null);
603 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
604 * taken from <code>enumTypeDef</code>.
607 * enumeration type definition is source of enumeration data for
608 * <code>typeBuilder</code>
610 * string with the name of enumeration
612 * generated type builder to which is enumeration added
613 * @return enumeration type which contains enumeration data form
614 * <code>enumTypeDef</code>
615 * @throws IllegalArgumentException
617 * <li>if <code>enumTypeDef</code> equals null</li>
618 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
619 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
620 * <li>if name of <code>enumTypeDef</code> equal null</li>
621 * <li>if name of <code>typeBuilder</code> equal null</li>
625 private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
626 final GeneratedTypeBuilderBase<?> typeBuilder) {
627 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
628 Preconditions.checkArgument(enumTypeDef.getValues() != null,
629 "EnumTypeDefinition MUST contain at least ONE value definition!");
630 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
631 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
632 "Local Name in EnumTypeDefinition QName cannot be NULL!");
633 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
635 final String enumerationName = BindingMapping.getClassName(enumName);
637 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
638 enumBuilder.setDescription(enumTypeDef.getDescription());
639 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
640 return enumBuilder.toInstance(enumBuilder);
644 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
647 * contains information about YANG type
648 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
650 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
651 Type returnType = null;
652 if (dataNode != null) {
653 if (dataNode instanceof LeafSchemaNode) {
654 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
655 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
656 } else if (dataNode instanceof LeafListSchemaNode) {
657 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
658 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
665 * Passes through all modules and through all its type definitions and
666 * convert it to generated types.
668 * The modules are firstly sorted by mutual dependencies. The modules are
669 * sequentially passed. All type definitions of a module are at the
670 * beginning sorted so that type definition with less amount of references
671 * to other type definition are processed first.<br />
672 * For each module is created mapping record in the map
673 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
674 * which map current module name to the map which maps type names to
675 * returned types (generated types).
678 private void resolveTypeDefsFromContext() {
679 final Set<Module> modules = schemaContext.getModules();
680 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
681 final Module[] modulesArray = new Module[modules.size()];
683 for (Module modul : modules) {
684 modulesArray[i++] = modul;
686 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
689 for (final Module module : modulesSortedByDependency) {
690 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
691 if (dateTypeMap == null) {
692 dateTypeMap = new HashMap<>();
694 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
695 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
698 for (final Module module : modulesSortedByDependency) {
699 if (module != null) {
700 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
701 if (basePackageName != null) {
702 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
703 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
704 if (listTypeDefinitions != null) {
705 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
706 typedefToGeneratedType(basePackageName, module, typedef);
716 * @param basePackageName
717 * string with name of package to which the module belongs
719 * string with the name of the module for to which the
720 * <code>typedef</code> belongs
722 * type definition of the node for which should be creted JAVA
723 * <code>Type</code> (usually generated TO)
724 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
725 * <code>null</code> value if <code>basePackageName</code> or
726 * <code>modulName</code> or <code>typedef</code> or Q name of
727 * <code>typedef</code> equals <code>null</code>
729 private Type typedefToGeneratedType(final String basePackageName, final Module module,
730 final TypeDefinition<?> typedef) {
731 final String moduleName = module.getName();
732 final Date moduleRevision = module.getRevision();
733 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
734 final String typedefName = typedef.getQName().getLocalName();
735 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
736 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
737 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
738 Type returnType = null;
739 if (innerTypeDefinition instanceof ExtendedType) {
740 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
741 returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName,
743 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
744 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
745 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
746 genTOBuilder.setTypedef(true);
747 genTOBuilder.setIsUnion(true);
748 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
749 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
750 returnType = genTOBuilder.toInstance();
752 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
753 genTOBuilder.getName() + "Builder");
754 unionBuilder.setIsUnionBuilder(true);
755 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
756 method.setReturnType(returnType);
757 method.addParameter(Types.STRING, "defaultValue");
758 method.setAccessModifier(AccessModifier.PUBLIC);
759 method.setStatic(true);
760 Set<Type> types = additionalTypes.get(module);
762 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
763 additionalTypes.put(module, types);
765 types.add(unionBuilder.toInstance());
767 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
768 // enums are automatically Serializable
769 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
770 // TODO units for typedef enum
771 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
772 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
773 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
774 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
775 basePackageName, bitsTypeDefinition, typedefName, module.getName());
776 genTOBuilder.setTypedef(true);
777 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
778 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
779 returnType = genTOBuilder.toInstance();
781 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
782 innerTypeDefinition, typedef);
783 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
785 if (returnType != null) {
786 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
787 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
788 if (typeMap != null) {
789 if (typeMap.isEmpty()) {
790 typeMap = new HashMap<>(4);
791 modulesByDate.put(moduleRevision, typeMap);
793 typeMap.put(typedefName, returnType);
803 * Wraps base YANG type to generated TO.
805 * @param basePackageName
806 * string with name of package to which the module belongs
808 * type definition which is converted to the TO
810 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
811 * @return generated transfer object which represent<code>javaType</code>
813 private static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
814 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 (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
826 final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
827 addStringRegExAsConstant(genTOBuilder, regExps);
829 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
830 genTOBuilder.setTypedef(true);
831 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
832 return genTOBuilder.toInstance();
836 * Converts output list of generated TO builders to one TO builder (first
837 * from list) which contains the remaining builders as its enclosing TO.
839 * @param basePackageName
840 * string with name of package to which the module belongs
842 * type definition which should be of type
843 * <code>UnionTypeDefinition</code>
845 * string with name for generated TO
846 * @return generated TO builder with the list of enclosed generated TO
849 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
850 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
851 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
852 typedef, typeDefName, parentNode);
853 GeneratedTOBuilder resultTOBuilder = null;
854 if (genTOBuilders.isEmpty()) {
855 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typedef);
858 resultTOBuilder = genTOBuilders.remove(0);
859 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
860 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
863 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
864 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
865 resultTOBuilder.addEqualsIdentity(genPropBuilder);
866 resultTOBuilder.addHashIdentity(genPropBuilder);
867 resultTOBuilder.addToStringProperty(genPropBuilder);
869 return resultTOBuilder;
873 * Converts <code>typedef</code> to generated TO with
874 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
875 * added to generated TO builder as property.
877 * @param basePackageName
878 * string with name of package to which the module belongs
880 * type definition which should be of type
881 * <code>UnionTypeDefinition</code>
883 * string with name for generated TO
884 * @return generated TO builder which represents <code>typedef</code>
885 * @throws NullPointerException
887 * <li>if <code>basePackageName</code> is null</li>
888 * <li>if <code>typedef</code> is null</li>
889 * <li>if Qname of <code>typedef</code> is null</li>
892 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
893 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
894 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
895 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
896 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
898 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
899 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
900 final Module module = findParentModule(schemaContext, parentNode);
902 final GeneratedTOBuilderImpl unionGenTOBuilder;
903 if (typeDefName != null && !typeDefName.isEmpty()) {
904 final String typeName = BindingMapping.getClassName(typeDefName);
905 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
906 unionGenTOBuilder.setDescription(typedef.getDescription());
907 unionGenTOBuilder.setReference(typedef.getReference());
908 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
909 unionGenTOBuilder.setModuleName(module.getName());
911 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
914 generatedTOBuilders.add(unionGenTOBuilder);
915 unionGenTOBuilder.setIsUnion(true);
916 final List<String> regularExpressions = new ArrayList<String>();
917 for (final TypeDefinition<?> unionType : unionTypes) {
918 final String unionTypeName = unionType.getQName().getLocalName();
919 if (unionType instanceof UnionType) {
920 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
921 basePackageName, parentNode));
922 } else if (unionType instanceof ExtendedType) {
923 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, regularExpressions,
925 } else if (unionType instanceof EnumTypeDefinition) {
926 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
927 unionTypeName, unionGenTOBuilder);
928 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
930 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
932 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
935 if (!regularExpressions.isEmpty()) {
936 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
939 storeGenTO(typedef, unionGenTOBuilder, parentNode);
941 return generatedTOBuilders;
945 * Wraps code which handle case when union subtype is also of the type
946 * <code>UnionType</code>.
948 * In this case the new generated TO is created for union subtype (recursive
950 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
951 * String, SchemaNode)}
952 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
953 * <code>parentUnionGenTOBuilder</code> is created property which type is
954 * equal to new generated TO.
956 * @param parentUnionGenTOBuilder
957 * generated TO builder to which is the property with the child
958 * union subtype added
959 * @param basePackageName
960 * string with the name of the module package
961 * @param unionSubtype
962 * type definition which represents union subtype
963 * @return list of generated TO builders. The number of the builders can be
964 * bigger one due to recursive call of
965 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
967 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
968 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
969 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
970 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
971 basePackageName, unionSubtype, newTOBuilderName, parentNode);
973 final GeneratedPropertyBuilder propertyBuilder;
974 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
975 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
976 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
977 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
979 return subUnionGenTOBUilders;
983 * Wraps code which handle case when union subtype is of the type
984 * <code>ExtendedType</code>.
986 * If TO for this type already exists it is used for the creation of the
987 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
988 * type is used for the property creation.
990 * @param parentUnionGenTOBuilder
991 * generated TO builder in which new property is created
992 * @param unionSubtype
993 * type definition of the <code>ExtendedType</code> type which
994 * represents union subtype
995 * @param regularExpressions
996 * list of strings with the regular expressions
998 * parent Schema Node for Extended Subtype
1001 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1002 final ExtendedType unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
1003 final String unionTypeName = unionSubtype.getQName().getLocalName();
1004 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1005 if (genTO != null) {
1006 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1008 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1009 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1010 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1012 if (javaType != null) {
1013 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1016 if (baseType instanceof StringType) {
1017 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
1023 * Searches for generated TO for <code>searchedTypeDef</code> type
1024 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1026 * @param searchedTypeName
1027 * string with name of <code>searchedTypeDef</code>
1028 * @return generated TO for <code>searchedTypeDef</code> or
1029 * <code>null</code> it it doesn't exist
1031 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1032 final Module typeModule = findParentModule(schemaContext, parentNode);
1033 if (typeModule != null && typeModule.getName() != null) {
1034 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1035 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1036 if (genTOs != null) {
1037 return genTOs.get(searchedTypeName);
1044 * Stores generated TO created from <code>genTOBuilder</code> for
1045 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1046 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1049 * type definition for which is <code>genTOBuilder</code> created
1050 * @param genTOBuilder
1051 * generated TO builder which is converted to generated TO and
1054 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1055 final SchemaNode parentNode) {
1056 if (!(newTypeDef instanceof UnionType)) {
1058 final Module parentModule = findParentModule(schemaContext, parentNode);
1059 if (parentModule != null && parentModule.getName() != null) {
1060 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1061 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1062 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1068 * Adds a new property with the name <code>propertyName</code> and with type
1069 * <code>type</code> to <code>unonGenTransObject</code>.
1071 * @param unionGenTransObject
1072 * generated TO to which should be property added
1074 * JAVA <code>type</code> of the property which should be added
1075 * to <code>unionGentransObject</code>
1076 * @param propertyName
1077 * string with name of property which should be added to
1078 * <code>unionGentransObject</code>
1080 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1081 final String propertyName) {
1082 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1083 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1084 .addProperty(BindingMapping.getPropertyName(propertyName));
1085 propBuilder.setReturnType(type);
1087 unionGenTransObject.addEqualsIdentity(propBuilder);
1088 unionGenTransObject.addHashIdentity(propBuilder);
1089 unionGenTransObject.addToStringProperty(propBuilder);
1094 * Converts <code>typedef</code> to the generated TO builder.
1096 * @param basePackageName
1097 * string with name of package to which the module belongs
1099 * type definition from which is the generated TO builder created
1100 * @return generated TO builder which contains data from
1101 * <code>typedef</code> and <code>basePackageName</code>
1103 private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName,
1104 final TypeDefinition<?> typedef, final String moduleName) {
1106 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1107 final String typeDefTOName = typedef.getQName().getLocalName();
1109 if ((packageName != null) && (typeDefTOName != null)) {
1110 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1111 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1113 newType.setDescription(typedef.getDescription());
1114 newType.setReference(typedef.getReference());
1115 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1116 newType.setModuleName(moduleName);
1124 * Converts <code>typeDef</code> which should be of the type
1125 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1127 * All the bits of the typeDef are added to returning generated TO as
1130 * @param basePackageName
1131 * string with name of package to which the module belongs
1133 * type definition from which is the generated TO builder created
1134 * @param typeDefName
1135 * string with the name for generated TO builder
1136 * @return generated TO builder which represents <code>typeDef</code>
1137 * @throws IllegalArgumentException
1139 * <li>if <code>typeDef</code> equals null</li>
1140 * <li>if <code>basePackageName</code> equals null</li>
1143 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1144 final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1146 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1147 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1149 if (typeDef instanceof BitsTypeDefinition) {
1150 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1152 final String typeName = BindingMapping.getClassName(typeDefName);
1153 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1155 genTOBuilder.setDescription(typeDef.getDescription());
1156 genTOBuilder.setReference(typeDef.getReference());
1157 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1158 genTOBuilder.setModuleName(moduleName);
1159 genTOBuilder.setBaseType(typeDef);
1161 final List<Bit> bitList = bitsTypeDefinition.getBits();
1162 GeneratedPropertyBuilder genPropertyBuilder;
1163 for (final Bit bit : bitList) {
1164 String name = bit.getName();
1165 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1166 genPropertyBuilder.setReadOnly(true);
1167 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1169 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1170 genTOBuilder.addHashIdentity(genPropertyBuilder);
1171 genTOBuilder.addToStringProperty(genPropertyBuilder);
1174 return genTOBuilder;
1180 * Converts the pattern constraints from <code>typedef</code> to the list of
1181 * the strings which represents these constraints.
1184 * extended type in which are the pattern constraints sought
1185 * @return list of strings which represents the constraint patterns
1186 * @throws IllegalArgumentException
1187 * if <code>typedef</code> equals null
1190 private static List<String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
1191 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1193 final List<PatternConstraint> patternConstraints;
1194 if (typedef instanceof ExtendedType) {
1195 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1196 if (strTypeDef instanceof StringType) {
1197 patternConstraints = ((ExtendedType)typedef).getPatternConstraints();
1199 patternConstraints = ImmutableList.of();
1201 } else if (typedef instanceof StringTypeDefinition) {
1202 // FIXME: run diff against base
1203 patternConstraints = ((StringTypeDefinition) typedef).getPatternConstraints();
1205 patternConstraints = ImmutableList.of();
1208 final List<String> regExps = new ArrayList<>(patternConstraints.size());
1209 for (PatternConstraint patternConstraint : patternConstraints) {
1210 final String regEx = patternConstraint.getRegularExpression();
1211 final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1212 regExps.add(modifiedRegEx);
1220 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1221 * expressions from the <code>regularExpressions</code>
1223 * @param genTOBuilder
1224 * generated TO builder to which are
1225 * <code>regular expressions</code> added
1226 * @param regularExpressions
1227 * list of string which represent regular expressions
1228 * @throws IllegalArgumentException
1230 * <li>if <code>genTOBuilder</code> equals null</li>
1231 * <li>if <code>regularExpressions</code> equals null</li>
1234 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1235 if (genTOBuilder == null) {
1236 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1238 if (regularExpressions == null) {
1239 throw new IllegalArgumentException("List of regular expressions can't be null");
1241 if (!regularExpressions.isEmpty()) {
1242 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1243 regularExpressions);
1248 * Creates generated TO with data about inner extended type
1249 * <code>innerExtendedType</code>, about the package name
1250 * <code>typedefName</code> and about the generated TO name
1251 * <code>typedefName</code>.
1253 * It is supposed that <code>innerExtendedType</code> is already present in
1254 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1255 * be possible set it as extended type for the returning generated TO.
1259 * @param innerExtendedType
1260 * extended type which is part of some other extended type
1261 * @param basePackageName
1262 * string with the package name of the module
1265 * @return generated TO which extends generated TO for
1266 * <code>innerExtendedType</code>
1267 * @throws IllegalArgumentException
1269 * <li>if <code>extendedType</code> equals null</li>
1270 * <li>if <code>basePackageName</code> equals null</li>
1271 * <li>if <code>typedefName</code> equals null</li>
1274 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1275 final ExtendedType innerExtendedType, final String basePackageName, final String moduleName) {
1276 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1277 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1279 final String typedefName = typedef.getQName().getLocalName();
1280 final String classTypedefName = BindingMapping.getClassName(typedefName);
1281 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1282 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1284 genTOBuilder.setDescription(typedef.getDescription());
1285 genTOBuilder.setReference(typedef.getReference());
1286 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1287 genTOBuilder.setModuleName(moduleName);
1288 genTOBuilder.setTypedef(true);
1289 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1290 genTOBuilder.setRestrictions(r);
1292 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1293 genTOBuilder.setIsUnion(true);
1296 Map<Date, Map<String, Type>> modulesByDate = null;
1297 Map<String, Type> typeMap = null;
1298 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1299 if (parentModule != null) {
1300 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1301 typeMap = modulesByDate.get(parentModule.getRevision());
1304 if (typeMap != null) {
1305 Type type = typeMap.get(innerTypeDef);
1306 if (type instanceof GeneratedTransferObject) {
1307 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1310 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1311 makeSerializable(genTOBuilder);
1313 return genTOBuilder.toInstance();
1317 * Add {@link Serializable} to implemented interfaces of this TO. Also
1318 * compute and add serialVersionUID property.
1321 * transfer object which needs to be serializable
1323 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1324 gto.addImplementsType(Types.typeForClass(Serializable.class));
1325 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1326 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1331 * Finds out for each type definition how many immersion (depth) is
1332 * necessary to get to the base type. Every type definition is inserted to
1333 * the map which key is depth and value is list of type definitions with
1334 * equal depth. In next step are lists from this map concatenated to one
1335 * list in ascending order according to their depth. All type definitions
1336 * are in the list behind all type definitions on which depends.
1338 * @param unsortedTypeDefinitions
1339 * list of type definitions which should be sorted by depth
1340 * @return list of type definitions sorted according their each other
1341 * dependencies (type definitions which are depend on other type
1342 * definitions are in list behind them).
1344 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1345 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1346 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1348 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1349 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1350 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1351 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1352 if (typeDefinitionsConcreteDepth == null) {
1353 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1354 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1356 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1359 // SortedMap guarantees order corresponding to keys in ascending order
1360 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1361 sortedTypeDefinition.addAll(v);
1364 return sortedTypeDefinition;
1368 * Returns how many immersion is necessary to get from the type definition
1371 * @param typeDefinition
1372 * type definition for which is depth sought.
1373 * @return number of immersions which are necessary to get from the type
1374 * definition to the base type
1376 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1377 // FIXME: rewrite this in a non-recursive manner, without ExtendedType and UnionType
1378 if (typeDefinition == null) {
1382 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1384 if (baseType instanceof ExtendedType) {
1385 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1386 } else if (baseType instanceof UnionType) {
1387 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1388 int maxChildDepth = 0;
1390 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1391 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1392 if (childDepth > maxChildDepth) {
1393 maxChildDepth = childDepth;
1396 return maxChildDepth;
1402 * Returns string which contains the same value as <code>name</code> but
1403 * integer suffix is incremented by one. If <code>name</code> contains no
1404 * number suffix then number 1 is added.
1407 * string with name of augmented node
1408 * @return string with the number suffix incremented by one (or 1 is added)
1410 private static String provideAvailableNameForGenTOBuilder(final String name) {
1411 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1413 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1414 return name.substring(0, mtch.start()) + newSuffix;
1420 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1421 if (!Strings.isNullOrEmpty(units)) {
1422 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1423 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1424 prop.setReturnType(Types.STRING);
1425 to.addToStringProperty(prop);
1430 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1431 return getTypeDefaultConstruction(node, node.getDefault());
1434 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1435 TypeDefinition<?> type = node.getType();
1436 QName typeQName = type.getQName();
1437 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1438 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1439 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1442 StringBuilder sb = new StringBuilder();
1443 String result = null;
1444 if (base instanceof BinaryTypeDefinition) {
1445 result = binaryToDef(defaultValue);
1446 } else if (base instanceof BitsTypeDefinition) {
1449 Module parent = getParentModule(node);
1450 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1452 if (!(path.hasNext())) {
1453 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1454 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1455 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1457 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1458 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1459 parentName = BindingMapping.getClassName(parent.getName());
1460 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1462 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1463 } else if (base instanceof BooleanTypeDefinition) {
1464 result = typeToDef(Boolean.class, defaultValue);
1465 } else if (base instanceof DecimalTypeDefinition) {
1466 result = typeToDef(BigDecimal.class, defaultValue);
1467 } else if (base instanceof EmptyTypeDefinition) {
1468 result = typeToDef(Boolean.class, defaultValue);
1469 } else if (base instanceof EnumTypeDefinition) {
1470 char[] defValArray = defaultValue.toCharArray();
1471 char first = Character.toUpperCase(defaultValue.charAt(0));
1472 defValArray[0] = first;
1473 String newDefVal = new String(defValArray);
1475 if (type instanceof ExtendedType) {
1476 Module m = getParentModule(type);
1477 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1478 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1479 className = packageName + "." + BindingMapping.getClassName(typeQName);
1481 Module parentModule = getParentModule(node);
1482 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1483 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1484 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1486 result = className + "." + newDefVal;
1487 } else if (base instanceof IdentityrefTypeDefinition) {
1488 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1489 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1490 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1491 } else if (base instanceof Int8) {
1492 result = typeToDef(Byte.class, defaultValue);
1493 } else if (base instanceof Int16) {
1494 result = typeToDef(Short.class, defaultValue);
1495 } else if (base instanceof Int32) {
1496 result = typeToDef(Integer.class, defaultValue);
1497 } else if (base instanceof Int64) {
1498 result = typeToDef(Long.class, defaultValue);
1499 } else if (base instanceof LeafrefTypeDefinition) {
1500 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1501 } else if (base instanceof StringTypeDefinition) {
1502 result = "\"" + defaultValue + "\"";
1503 } else if (base instanceof Uint8) {
1504 result = typeToDef(Short.class, defaultValue);
1505 } else if (base instanceof Uint16) {
1506 result = typeToDef(Integer.class, defaultValue);
1507 } else if (base instanceof Uint32) {
1508 result = typeToDef(Long.class, defaultValue);
1509 } else if (base instanceof Uint64) {
1510 result = typeToDef(BigInteger.class, defaultValue);
1511 } else if (base instanceof UnionTypeDefinition) {
1512 result = unionToDef(node);
1518 if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
1519 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
1520 Module m = getParentModule(type);
1521 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1522 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1523 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1524 sb.insert(0, "new " + className + "(");
1525 sb.insert(sb.length(), ')');
1528 return sb.toString();
1531 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1532 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1535 private static String binaryToDef(final String defaultValue) {
1536 StringBuilder sb = new StringBuilder();
1537 BaseEncoding en = BaseEncoding.base64();
1538 byte[] encoded = en.decode(defaultValue);
1539 sb.append("new byte[] {");
1540 for (int i = 0; i < encoded.length; i++) {
1541 sb.append(encoded[i]);
1542 if (i != encoded.length - 1) {
1547 return sb.toString();
1550 private static final Comparator<Bit> BIT_NAME_COMPARATOR = new Comparator<Bit>() {
1552 public int compare(final Bit o1, final Bit o2) {
1553 return o1.getName().compareTo(o2.getName());
1557 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1558 final boolean isExt) {
1559 List<Bit> bits = new ArrayList<>(type.getBits());
1560 Collections.sort(bits, BIT_NAME_COMPARATOR);
1561 StringBuilder sb = new StringBuilder();
1564 sb.append(className);
1567 for (int i = 0; i < bits.size(); i++) {
1568 if (bits.get(i).getName().equals(defaultValue)) {
1573 if (i != bits.size() - 1) {
1580 return sb.toString();
1583 private Module getParentModule(final SchemaNode node) {
1584 QName qname = node.getPath().getPathFromRoot().iterator().next();
1585 URI namespace = qname.getNamespace();
1586 Date revision = qname.getRevision();
1587 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1590 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1591 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1592 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1593 "The Path Statement for Leafref Type Definition cannot be NULL!");
1595 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1596 final String strXPath = xpath.toString();
1598 if (strXPath != null) {
1599 if (strXPath.indexOf('[') == -1) {
1600 final Module module = findParentModule(schemaContext, parentNode);
1601 if (module != null) {
1602 final SchemaNode dataNode;
1603 if (xpath.isAbsolute()) {
1604 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1606 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1608 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1612 return "new java.lang.Object()";
1619 private String unionToDef(final LeafSchemaNode node) {
1623 if (node.getType() instanceof ExtendedType) {
1624 ExtendedType type = (ExtendedType) node.getType();
1625 QName typeQName = type.getQName();
1626 Module module = null;
1627 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1628 if (modules.size() > 1) {
1629 for (Module m : modules) {
1630 if (m.getRevision().equals(typeQName.getRevision())) {
1635 if (module == null) {
1636 List<Module> modulesList = new ArrayList<>(modules);
1637 Collections.sort(modulesList, new Comparator<Module>() {
1639 public int compare(final Module o1, final Module o2) {
1640 return o1.getRevision().compareTo(o2.getRevision());
1643 module = modulesList.get(0);
1646 module = modules.iterator().next();
1649 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1650 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1652 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1653 QName first = path.next();
1654 if (!(path.hasNext())) {
1655 URI namespace = first.getNamespace();
1656 Date revision = first.getRevision();
1657 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1658 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1659 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1660 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1662 URI namespace = first.getNamespace();
1663 Date revision = first.getRevision();
1664 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1665 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1666 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1667 node.getType().getPath());
1668 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1671 return union(className, node.getDefault(), node);
1674 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1675 StringBuilder sb = new StringBuilder();
1677 sb.append(className);
1679 sb.append(defaultValue);
1680 sb.append("\".toCharArray())");
1681 return sb.toString();
1685 public String getConstructorPropertyName(final SchemaNode node) {
1686 if (node instanceof TypeDefinition<?>) {
1694 public String getParamNameFromType(final TypeDefinition<?> type) {
1695 return BindingMapping.getPropertyName(type.getQName().getLocalName());