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.getBaseType() != null) {
740 returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName,
742 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
743 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
744 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
745 genTOBuilder.setTypedef(true);
746 genTOBuilder.setIsUnion(true);
747 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
748 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
749 returnType = genTOBuilder.toInstance();
751 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
752 genTOBuilder.getName() + "Builder");
753 unionBuilder.setIsUnionBuilder(true);
754 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
755 method.setReturnType(returnType);
756 method.addParameter(Types.STRING, "defaultValue");
757 method.setAccessModifier(AccessModifier.PUBLIC);
758 method.setStatic(true);
759 Set<Type> types = additionalTypes.get(module);
761 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
762 additionalTypes.put(module, types);
764 types.add(unionBuilder.toInstance());
766 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
767 // enums are automatically Serializable
768 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
769 // TODO units for typedef enum
770 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
771 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
772 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
773 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
774 basePackageName, bitsTypeDefinition, typedefName, module.getName());
775 genTOBuilder.setTypedef(true);
776 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
777 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
778 returnType = genTOBuilder.toInstance();
780 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
781 innerTypeDefinition, typedef);
782 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
784 if (returnType != null) {
785 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
786 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
787 if (typeMap != null) {
788 if (typeMap.isEmpty()) {
789 typeMap = new HashMap<>(4);
790 modulesByDate.put(moduleRevision, typeMap);
792 typeMap.put(typedefName, returnType);
802 * Wraps base YANG type to generated TO.
804 * @param basePackageName
805 * string with name of package to which the module belongs
807 * type definition which is converted to the TO
809 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
810 * @return generated transfer object which represent<code>javaType</code>
812 private static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
813 final Type javaType, final String moduleName) {
814 Preconditions.checkNotNull(javaType, "javaType cannot be null");
815 final String propertyName = "value";
817 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
818 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
819 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
820 genPropBuilder.setReturnType(javaType);
821 genTOBuilder.addEqualsIdentity(genPropBuilder);
822 genTOBuilder.addHashIdentity(genPropBuilder);
823 genTOBuilder.addToStringProperty(genPropBuilder);
824 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
825 final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
826 addStringRegExAsConstant(genTOBuilder, regExps);
828 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
829 genTOBuilder.setTypedef(true);
830 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
831 return genTOBuilder.toInstance();
835 * Converts output list of generated TO builders to one TO builder (first
836 * from list) which contains the remaining builders as its enclosing TO.
838 * @param basePackageName
839 * string with name of package to which the module belongs
841 * type definition which should be of type
842 * <code>UnionTypeDefinition</code>
844 * string with name for generated TO
845 * @return generated TO builder with the list of enclosed generated TO
848 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
849 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
850 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
851 typedef, typeDefName, parentNode);
852 GeneratedTOBuilder resultTOBuilder = null;
853 if (genTOBuilders.isEmpty()) {
854 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typedef);
857 resultTOBuilder = genTOBuilders.remove(0);
858 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
859 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
862 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
863 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
864 resultTOBuilder.addEqualsIdentity(genPropBuilder);
865 resultTOBuilder.addHashIdentity(genPropBuilder);
866 resultTOBuilder.addToStringProperty(genPropBuilder);
868 return resultTOBuilder;
872 * Converts <code>typedef</code> to generated TO with
873 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
874 * added to generated TO builder as property.
876 * @param basePackageName
877 * string with name of package to which the module belongs
879 * type definition which should be of type
880 * <code>UnionTypeDefinition</code>
882 * string with name for generated TO
883 * @return generated TO builder which represents <code>typedef</code>
884 * @throws NullPointerException
886 * <li>if <code>basePackageName</code> is null</li>
887 * <li>if <code>typedef</code> is null</li>
888 * <li>if Qname of <code>typedef</code> is null</li>
891 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
892 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
893 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
894 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
895 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
897 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
898 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
899 final Module module = findParentModule(schemaContext, parentNode);
901 final GeneratedTOBuilderImpl unionGenTOBuilder;
902 if (typeDefName != null && !typeDefName.isEmpty()) {
903 final String typeName = BindingMapping.getClassName(typeDefName);
904 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
905 unionGenTOBuilder.setDescription(typedef.getDescription());
906 unionGenTOBuilder.setReference(typedef.getReference());
907 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
908 unionGenTOBuilder.setModuleName(module.getName());
910 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
913 generatedTOBuilders.add(unionGenTOBuilder);
914 unionGenTOBuilder.setIsUnion(true);
915 final List<String> regularExpressions = new ArrayList<String>();
916 for (final TypeDefinition<?> unionType : unionTypes) {
917 final String unionTypeName = unionType.getQName().getLocalName();
918 if (unionType instanceof UnionType) {
919 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
920 basePackageName, parentNode));
921 } else if (unionType instanceof ExtendedType) {
922 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, regularExpressions,
924 } else if (unionType instanceof EnumTypeDefinition) {
925 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
926 unionTypeName, unionGenTOBuilder);
927 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
929 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
931 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
934 if (!regularExpressions.isEmpty()) {
935 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
938 storeGenTO(typedef, unionGenTOBuilder, parentNode);
940 return generatedTOBuilders;
944 * Wraps code which handle case when union subtype is also of the type
945 * <code>UnionType</code>.
947 * In this case the new generated TO is created for union subtype (recursive
949 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
950 * String, SchemaNode)}
951 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
952 * <code>parentUnionGenTOBuilder</code> is created property which type is
953 * equal to new generated TO.
955 * @param parentUnionGenTOBuilder
956 * generated TO builder to which is the property with the child
957 * union subtype added
958 * @param basePackageName
959 * string with the name of the module package
960 * @param unionSubtype
961 * type definition which represents union subtype
962 * @return list of generated TO builders. The number of the builders can be
963 * bigger one due to recursive call of
964 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
966 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
967 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
968 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
969 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
970 basePackageName, unionSubtype, newTOBuilderName, parentNode);
972 final GeneratedPropertyBuilder propertyBuilder;
973 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
974 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
975 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
976 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
978 return subUnionGenTOBUilders;
982 * Wraps code which handle case when union subtype is of the type
983 * <code>ExtendedType</code>.
985 * If TO for this type already exists it is used for the creation of the
986 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
987 * type is used for the property creation.
989 * @param parentUnionGenTOBuilder
990 * generated TO builder in which new property is created
991 * @param unionSubtype
992 * type definition of the <code>ExtendedType</code> type which
993 * represents union subtype
994 * @param regularExpressions
995 * list of strings with the regular expressions
997 * parent Schema Node for Extended Subtype
1000 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1001 final ExtendedType unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
1002 final String unionTypeName = unionSubtype.getQName().getLocalName();
1003 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1004 if (genTO != null) {
1005 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1007 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1008 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1009 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1011 if (javaType != null) {
1012 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1015 if (baseType instanceof StringType) {
1016 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
1022 * Searches for generated TO for <code>searchedTypeDef</code> type
1023 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1025 * @param searchedTypeName
1026 * string with name of <code>searchedTypeDef</code>
1027 * @return generated TO for <code>searchedTypeDef</code> or
1028 * <code>null</code> it it doesn't exist
1030 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1031 final Module typeModule = findParentModule(schemaContext, parentNode);
1032 if (typeModule != null && typeModule.getName() != null) {
1033 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1034 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1035 if (genTOs != null) {
1036 return genTOs.get(searchedTypeName);
1043 * Stores generated TO created from <code>genTOBuilder</code> for
1044 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1045 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1048 * type definition for which is <code>genTOBuilder</code> created
1049 * @param genTOBuilder
1050 * generated TO builder which is converted to generated TO and
1053 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1054 final SchemaNode parentNode) {
1055 if (!(newTypeDef instanceof UnionType)) {
1057 final Module parentModule = findParentModule(schemaContext, parentNode);
1058 if (parentModule != null && parentModule.getName() != null) {
1059 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1060 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1061 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1067 * Adds a new property with the name <code>propertyName</code> and with type
1068 * <code>type</code> to <code>unonGenTransObject</code>.
1070 * @param unionGenTransObject
1071 * generated TO to which should be property added
1073 * JAVA <code>type</code> of the property which should be added
1074 * to <code>unionGentransObject</code>
1075 * @param propertyName
1076 * string with name of property which should be added to
1077 * <code>unionGentransObject</code>
1079 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1080 final String propertyName) {
1081 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1082 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1083 .addProperty(BindingMapping.getPropertyName(propertyName));
1084 propBuilder.setReturnType(type);
1086 unionGenTransObject.addEqualsIdentity(propBuilder);
1087 unionGenTransObject.addHashIdentity(propBuilder);
1088 unionGenTransObject.addToStringProperty(propBuilder);
1093 * Converts <code>typedef</code> to the generated TO builder.
1095 * @param basePackageName
1096 * string with name of package to which the module belongs
1098 * type definition from which is the generated TO builder created
1099 * @return generated TO builder which contains data from
1100 * <code>typedef</code> and <code>basePackageName</code>
1102 private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName,
1103 final TypeDefinition<?> typedef, final String moduleName) {
1105 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1106 final String typeDefTOName = typedef.getQName().getLocalName();
1108 if ((packageName != null) && (typeDefTOName != null)) {
1109 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1110 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1112 newType.setDescription(typedef.getDescription());
1113 newType.setReference(typedef.getReference());
1114 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1115 newType.setModuleName(moduleName);
1123 * Converts <code>typeDef</code> which should be of the type
1124 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1126 * All the bits of the typeDef are added to returning generated TO as
1129 * @param basePackageName
1130 * string with name of package to which the module belongs
1132 * type definition from which is the generated TO builder created
1133 * @param typeDefName
1134 * string with the name for generated TO builder
1135 * @return generated TO builder which represents <code>typeDef</code>
1136 * @throws IllegalArgumentException
1138 * <li>if <code>typeDef</code> equals null</li>
1139 * <li>if <code>basePackageName</code> equals null</li>
1142 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1143 final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1145 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1146 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1148 if (typeDef instanceof BitsTypeDefinition) {
1149 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1151 final String typeName = BindingMapping.getClassName(typeDefName);
1152 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1154 genTOBuilder.setDescription(typeDef.getDescription());
1155 genTOBuilder.setReference(typeDef.getReference());
1156 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1157 genTOBuilder.setModuleName(moduleName);
1158 genTOBuilder.setBaseType(typeDef);
1160 final List<Bit> bitList = bitsTypeDefinition.getBits();
1161 GeneratedPropertyBuilder genPropertyBuilder;
1162 for (final Bit bit : bitList) {
1163 String name = bit.getName();
1164 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1165 genPropertyBuilder.setReadOnly(true);
1166 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1168 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1169 genTOBuilder.addHashIdentity(genPropertyBuilder);
1170 genTOBuilder.addToStringProperty(genPropertyBuilder);
1173 return genTOBuilder;
1179 * Converts the pattern constraints from <code>typedef</code> to the list of
1180 * the strings which represents these constraints.
1183 * extended type in which are the pattern constraints sought
1184 * @return list of strings which represents the constraint patterns
1185 * @throws IllegalArgumentException
1186 * if <code>typedef</code> equals null
1189 private static List<String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
1190 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1192 final List<PatternConstraint> patternConstraints;
1193 if (typedef instanceof ExtendedType) {
1194 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1195 if (strTypeDef instanceof StringType) {
1196 patternConstraints = ((ExtendedType)typedef).getPatternConstraints();
1198 patternConstraints = ImmutableList.of();
1200 } else if (typedef instanceof StringTypeDefinition) {
1201 // FIXME: run diff against base
1202 patternConstraints = ((StringTypeDefinition) typedef).getPatternConstraints();
1204 patternConstraints = ImmutableList.of();
1207 final List<String> regExps = new ArrayList<>(patternConstraints.size());
1208 for (PatternConstraint patternConstraint : patternConstraints) {
1209 final String regEx = patternConstraint.getRegularExpression();
1210 final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1211 regExps.add(modifiedRegEx);
1219 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1220 * expressions from the <code>regularExpressions</code>
1222 * @param genTOBuilder
1223 * generated TO builder to which are
1224 * <code>regular expressions</code> added
1225 * @param regularExpressions
1226 * list of string which represent regular expressions
1227 * @throws IllegalArgumentException
1229 * <li>if <code>genTOBuilder</code> equals null</li>
1230 * <li>if <code>regularExpressions</code> equals null</li>
1233 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1234 if (genTOBuilder == null) {
1235 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1237 if (regularExpressions == null) {
1238 throw new IllegalArgumentException("List of regular expressions can't be null");
1240 if (!regularExpressions.isEmpty()) {
1241 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1242 regularExpressions);
1247 * Creates generated TO with data about inner extended type
1248 * <code>innerExtendedType</code>, about the package name
1249 * <code>typedefName</code> and about the generated TO name
1250 * <code>typedefName</code>.
1252 * It is supposed that <code>innerExtendedType</code> is already present in
1253 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1254 * be possible set it as extended type for the returning generated TO.
1258 * @param innerExtendedType
1259 * extended type which is part of some other extended type
1260 * @param basePackageName
1261 * string with the package name of the module
1264 * @return generated TO which extends generated TO for
1265 * <code>innerExtendedType</code>
1266 * @throws IllegalArgumentException
1268 * <li>if <code>extendedType</code> equals null</li>
1269 * <li>if <code>basePackageName</code> equals null</li>
1270 * <li>if <code>typedefName</code> equals null</li>
1273 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1274 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1275 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1276 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1278 final String typedefName = typedef.getQName().getLocalName();
1279 final String classTypedefName = BindingMapping.getClassName(typedefName);
1280 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1281 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1283 genTOBuilder.setDescription(typedef.getDescription());
1284 genTOBuilder.setReference(typedef.getReference());
1285 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1286 genTOBuilder.setModuleName(moduleName);
1287 genTOBuilder.setTypedef(true);
1288 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1289 genTOBuilder.setRestrictions(r);
1291 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1292 genTOBuilder.setIsUnion(true);
1295 Map<Date, Map<String, Type>> modulesByDate = null;
1296 Map<String, Type> typeMap = null;
1297 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1298 if (parentModule != null) {
1299 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1300 typeMap = modulesByDate.get(parentModule.getRevision());
1303 if (typeMap != null) {
1304 Type type = typeMap.get(innerTypeDef);
1305 if (type instanceof GeneratedTransferObject) {
1306 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1309 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1310 makeSerializable(genTOBuilder);
1312 return genTOBuilder.toInstance();
1316 * Add {@link Serializable} to implemented interfaces of this TO. Also
1317 * compute and add serialVersionUID property.
1320 * transfer object which needs to be serializable
1322 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1323 gto.addImplementsType(Types.typeForClass(Serializable.class));
1324 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1325 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1330 * Finds out for each type definition how many immersion (depth) is
1331 * necessary to get to the base type. Every type definition is inserted to
1332 * the map which key is depth and value is list of type definitions with
1333 * equal depth. In next step are lists from this map concatenated to one
1334 * list in ascending order according to their depth. All type definitions
1335 * are in the list behind all type definitions on which depends.
1337 * @param unsortedTypeDefinitions
1338 * list of type definitions which should be sorted by depth
1339 * @return list of type definitions sorted according their each other
1340 * dependencies (type definitions which are depend on other type
1341 * definitions are in list behind them).
1343 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1344 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1345 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1347 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1348 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1349 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1350 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1351 if (typeDefinitionsConcreteDepth == null) {
1352 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1353 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1355 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1358 // SortedMap guarantees order corresponding to keys in ascending order
1359 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1360 sortedTypeDefinition.addAll(v);
1363 return sortedTypeDefinition;
1367 * Returns how many immersion is necessary to get from the type definition
1370 * @param typeDefinition
1371 * type definition for which is depth sought.
1372 * @return number of immersions which are necessary to get from the type
1373 * definition to the base type
1375 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1376 // FIXME: rewrite this in a non-recursive manner, without ExtendedType and UnionType
1377 if (typeDefinition == null) {
1381 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1383 if (baseType instanceof ExtendedType) {
1384 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1385 } else if (baseType instanceof UnionType) {
1386 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1387 int maxChildDepth = 0;
1389 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1390 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1391 if (childDepth > maxChildDepth) {
1392 maxChildDepth = childDepth;
1395 return maxChildDepth;
1401 * Returns string which contains the same value as <code>name</code> but
1402 * integer suffix is incremented by one. If <code>name</code> contains no
1403 * number suffix then number 1 is added.
1406 * string with name of augmented node
1407 * @return string with the number suffix incremented by one (or 1 is added)
1409 private static String provideAvailableNameForGenTOBuilder(final String name) {
1410 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1412 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1413 return name.substring(0, mtch.start()) + newSuffix;
1419 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1420 if (!Strings.isNullOrEmpty(units)) {
1421 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1422 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1423 prop.setReturnType(Types.STRING);
1424 to.addToStringProperty(prop);
1429 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1430 return getTypeDefaultConstruction(node, node.getDefault());
1433 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1434 TypeDefinition<?> type = node.getType();
1435 QName typeQName = type.getQName();
1436 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1437 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1438 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1441 StringBuilder sb = new StringBuilder();
1442 String result = null;
1443 if (base instanceof BinaryTypeDefinition) {
1444 result = binaryToDef(defaultValue);
1445 } else if (base instanceof BitsTypeDefinition) {
1448 Module parent = getParentModule(node);
1449 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1451 if (!(path.hasNext())) {
1452 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1453 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1454 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1456 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1457 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1458 parentName = BindingMapping.getClassName(parent.getName());
1459 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1461 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1462 } else if (base instanceof BooleanTypeDefinition) {
1463 result = typeToDef(Boolean.class, defaultValue);
1464 } else if (base instanceof DecimalTypeDefinition) {
1465 result = typeToDef(BigDecimal.class, defaultValue);
1466 } else if (base instanceof EmptyTypeDefinition) {
1467 result = typeToDef(Boolean.class, defaultValue);
1468 } else if (base instanceof EnumTypeDefinition) {
1469 char[] defValArray = defaultValue.toCharArray();
1470 char first = Character.toUpperCase(defaultValue.charAt(0));
1471 defValArray[0] = first;
1472 String newDefVal = new String(defValArray);
1474 if (type instanceof ExtendedType) {
1475 Module m = getParentModule(type);
1476 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1477 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1478 className = packageName + "." + BindingMapping.getClassName(typeQName);
1480 Module parentModule = getParentModule(node);
1481 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1482 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1483 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1485 result = className + "." + newDefVal;
1486 } else if (base instanceof IdentityrefTypeDefinition) {
1487 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1488 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1489 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1490 } else if (base instanceof Int8) {
1491 result = typeToDef(Byte.class, defaultValue);
1492 } else if (base instanceof Int16) {
1493 result = typeToDef(Short.class, defaultValue);
1494 } else if (base instanceof Int32) {
1495 result = typeToDef(Integer.class, defaultValue);
1496 } else if (base instanceof Int64) {
1497 result = typeToDef(Long.class, defaultValue);
1498 } else if (base instanceof LeafrefTypeDefinition) {
1499 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1500 } else if (base instanceof StringTypeDefinition) {
1501 result = "\"" + defaultValue + "\"";
1502 } else if (base instanceof Uint8) {
1503 result = typeToDef(Short.class, defaultValue);
1504 } else if (base instanceof Uint16) {
1505 result = typeToDef(Integer.class, defaultValue);
1506 } else if (base instanceof Uint32) {
1507 result = typeToDef(Long.class, defaultValue);
1508 } else if (base instanceof Uint64) {
1509 result = typeToDef(BigInteger.class, defaultValue);
1510 } else if (base instanceof UnionTypeDefinition) {
1511 result = unionToDef(node);
1517 if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
1518 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
1519 Module m = getParentModule(type);
1520 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1521 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1522 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1523 sb.insert(0, "new " + className + "(");
1524 sb.insert(sb.length(), ')');
1527 return sb.toString();
1530 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1531 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1534 private static String binaryToDef(final String defaultValue) {
1535 StringBuilder sb = new StringBuilder();
1536 BaseEncoding en = BaseEncoding.base64();
1537 byte[] encoded = en.decode(defaultValue);
1538 sb.append("new byte[] {");
1539 for (int i = 0; i < encoded.length; i++) {
1540 sb.append(encoded[i]);
1541 if (i != encoded.length - 1) {
1546 return sb.toString();
1549 private static final Comparator<Bit> BIT_NAME_COMPARATOR = new Comparator<Bit>() {
1551 public int compare(final Bit o1, final Bit o2) {
1552 return o1.getName().compareTo(o2.getName());
1556 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1557 final boolean isExt) {
1558 List<Bit> bits = new ArrayList<>(type.getBits());
1559 Collections.sort(bits, BIT_NAME_COMPARATOR);
1560 StringBuilder sb = new StringBuilder();
1563 sb.append(className);
1566 for (int i = 0; i < bits.size(); i++) {
1567 if (bits.get(i).getName().equals(defaultValue)) {
1572 if (i != bits.size() - 1) {
1579 return sb.toString();
1582 private Module getParentModule(final SchemaNode node) {
1583 QName qname = node.getPath().getPathFromRoot().iterator().next();
1584 URI namespace = qname.getNamespace();
1585 Date revision = qname.getRevision();
1586 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1589 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1590 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1591 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1592 "The Path Statement for Leafref Type Definition cannot be NULL!");
1594 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1595 final String strXPath = xpath.toString();
1597 if (strXPath != null) {
1598 if (strXPath.indexOf('[') == -1) {
1599 final Module module = findParentModule(schemaContext, parentNode);
1600 if (module != null) {
1601 final SchemaNode dataNode;
1602 if (xpath.isAbsolute()) {
1603 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1605 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1607 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1611 return "new java.lang.Object()";
1618 private String unionToDef(final LeafSchemaNode node) {
1622 if (node.getType() instanceof ExtendedType) {
1623 ExtendedType type = (ExtendedType) node.getType();
1624 QName typeQName = type.getQName();
1625 Module module = null;
1626 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1627 if (modules.size() > 1) {
1628 for (Module m : modules) {
1629 if (m.getRevision().equals(typeQName.getRevision())) {
1634 if (module == null) {
1635 List<Module> modulesList = new ArrayList<>(modules);
1636 Collections.sort(modulesList, new Comparator<Module>() {
1638 public int compare(final Module o1, final Module o2) {
1639 return o1.getRevision().compareTo(o2.getRevision());
1642 module = modulesList.get(0);
1645 module = modules.iterator().next();
1648 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1649 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1651 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1652 QName first = path.next();
1653 if (!(path.hasNext())) {
1654 URI namespace = first.getNamespace();
1655 Date revision = first.getRevision();
1656 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1657 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1658 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1659 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1661 URI namespace = first.getNamespace();
1662 Date revision = first.getRevision();
1663 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1664 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1665 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1666 node.getType().getPath());
1667 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1670 return union(className, node.getDefault(), node);
1673 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1674 StringBuilder sb = new StringBuilder();
1676 sb.append(className);
1678 sb.append(defaultValue);
1679 sb.append("\".toCharArray())");
1680 return sb.toString();
1684 public String getConstructorPropertyName(final SchemaNode node) {
1685 if (node instanceof TypeDefinition<?>) {
1693 public String getParamNameFromType(final TypeDefinition<?> type) {
1694 return BindingMapping.getPropertyName(type.getQName().getLocalName());