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;
97 public final class TypeProviderImpl implements TypeProvider {
98 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
101 * Contains the schema data red from YANG files.
103 private final SchemaContext schemaContext;
106 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
108 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
111 * The map which maps schema paths to JAVA <code>Type</code>.
113 private final Map<SchemaPath, Type> referencedTypes;
114 private final Map<Module, Set<Type>> additionalTypes;
117 * Creates new instance of class <code>TypeProviderImpl</code>.
119 * @param schemaContext
120 * contains the schema data red from YANG files
121 * @throws IllegalArgumentException
122 * if <code>schemaContext</code> equal null.
124 public TypeProviderImpl(final SchemaContext schemaContext) {
125 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
127 this.schemaContext = schemaContext;
128 this.genTypeDefsContextMap = new HashMap<>();
129 this.referencedTypes = new HashMap<>();
130 this.additionalTypes = new HashMap<>();
131 resolveTypeDefsFromContext();
135 * Puts <code>refType</code> to map with key <code>refTypePath</code>
138 * schema path used as the map key
140 * type which represents the map value
141 * @throws IllegalArgumentException
143 * <li>if <code>refTypePath</code> equal null</li>
144 * <li>if <code>refType</code> equal null</li>
148 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
149 Preconditions.checkArgument(refTypePath != null,
150 "Path reference of Enumeration Type Definition cannot be NULL!");
151 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
152 referencedTypes.put(refTypePath, refType);
155 public Map<Module, Set<Type>> getAdditionalTypes() {
156 return additionalTypes;
161 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
164 * string with YANG name of type
165 * @return JAVA <code>Type</code> for YANG type <code>type</code>
166 * @see TypeProvider#javaTypeForYangType(String)
170 public Type javaTypeForYangType(final String type) {
171 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
175 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
176 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
180 * Converts schema definition type <code>typeDefinition</code> to JAVA
183 * @param typeDefinition
184 * type definition which is converted to JAVA type
185 * @throws IllegalArgumentException
187 * <li>if <code>typeDefinition</code> equal null</li>
188 * <li>if Qname of <code>typeDefinition</code> equal null</li>
189 * <li>if name of <code>typeDefinition</code> equal null</li>
193 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
194 final Restrictions r) {
196 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
197 Preconditions.checkArgument(typeDefinition.getQName() != null,
198 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
199 String typedefName = typeDefinition.getQName().getLocalName();
200 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
202 if (typeDefinition instanceof ExtendedType) {
203 returnType = javaTypeForExtendedType(typeDefinition);
204 if (r != null && returnType instanceof GeneratedTransferObject) {
205 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
206 Module module = findParentModule(schemaContext, parentNode);
207 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
208 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
209 typeDefinition.getPath());
210 String genTOName = BindingMapping.getClassName(typedefName);
211 String name = packageName + "." + genTOName;
212 if (!(returnType.getFullyQualifiedName().equals(name))) {
213 returnType = shadedTOWithRestrictions(gto, r);
217 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
218 if (returnType == null) {
219 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
226 private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
227 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
228 GeneratedTransferObject parent = gto.getSuperType();
229 if (parent != null) {
230 gtob.setExtendsType(parent);
232 gtob.setRestrictions(r);
233 for (GeneratedProperty gp : gto.getProperties()) {
234 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
235 gpb.setValue(gp.getValue());
236 gpb.setReadOnly(gp.isReadOnly());
237 gpb.setAccessModifier(gp.getAccessModifier());
238 gpb.setReturnType(gp.getReturnType());
239 gpb.setFinal(gp.isFinal());
240 gpb.setStatic(gp.isStatic());
242 return gtob.toInstance();
245 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
246 final SchemaNode leafRefValueNode;
247 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
248 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
249 .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute());
251 ///// skip leafrefs in augments - they're checked once augments are resolved
252 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
253 boolean isAugmenting = false;
254 DataNodeContainer current = null;
255 DataSchemaNode dataChildByName;
257 while (iterator.hasNext() && !isAugmenting) {
258 final QName next = iterator.next();
259 if (current == null) {
260 dataChildByName = schemaContext.getDataChildByName(next);
262 dataChildByName = current.getDataChildByName(next);
264 if (dataChildByName != null) {
265 isAugmenting = dataChildByName.isAugmenting();
269 if (dataChildByName instanceof DataNodeContainer) {
270 current = (DataNodeContainer) dataChildByName;
278 Module parentModule = getParentModule(parentNode);
279 if (!leafRefStrippedXPath.isAbsolute()) {
280 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
281 parentNode, leafRefStrippedXPath);
283 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
285 return (leafRefValueNode != null) ? leafRefValueNode.equals(parentNode) : false;
289 * Returns JAVA <code>Type</code> for instances of the type
290 * <code>LeafrefTypeDefinition</code> or
291 * <code>IdentityrefTypeDefinition</code>.
293 * @param typeDefinition
294 * type definition which is converted to JAVA <code>Type</code>
295 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
297 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
298 if (typeDefinition instanceof LeafrefTypeDefinition) {
299 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
300 if (isLeafRefSelfReference(leafref, parentNode)) {
301 throw new YangValidationException("Leafref " + leafref.toString() + " is referencing itself, incoming" +
302 " StackOverFlowError detected.");
304 return provideTypeForLeafref(leafref, parentNode);
305 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
306 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
307 return provideTypeForIdentityref(idref);
314 * Returns JAVA <code>Type</code> for instances of the type
315 * <code>ExtendedType</code>.
317 * @param typeDefinition
318 * type definition which is converted to JAVA <code>Type</code>
319 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
321 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
322 final String typedefName = typeDefinition.getQName().getLocalName();
323 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
324 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
325 if (returnType == null) {
326 if (baseTypeDef instanceof EnumTypeDefinition) {
327 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
328 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
330 final Module module = findParentModule(schemaContext, typeDefinition);
331 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
332 if (module != null) {
333 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
334 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
335 if (genTOs != null) {
336 returnType = genTOs.get(typedefName);
338 if (returnType == null) {
339 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
340 baseTypeDef, typeDefinition, r);
349 * Seeks for identity reference <code>idref</code> the JAVA
350 * <code>type</code>.<br />
354 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
355 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
358 * identityref type definition for which JAVA <code>Type</code>
360 * @return JAVA <code>Type</code> of the identity which is refrenced through
363 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
364 QName baseIdQName = idref.getIdentity().getQName();
365 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
366 baseIdQName.getRevision());
367 IdentitySchemaNode identity = null;
368 for (IdentitySchemaNode id : module.getIdentities()) {
369 if (id.getQName().equals(baseIdQName)) {
373 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
375 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
376 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath());
377 final String genTypeName = BindingMapping.getClassName(identity.getQName());
379 Type baseType = Types.typeForClass(Class.class);
380 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
381 return Types.parameterizedTypeFor(baseType, paramType);
385 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
387 * @param typeDefinition
388 * type definition which should be converted to JAVA
390 * @return JAVA <code>Type</code> which represents
391 * <code>typeDefinition</code>
392 * @throws IllegalArgumentException
394 * <li>if <code>typeDefinition</code> equal null</li>
395 * <li>if Q name of <code>typeDefinition</code></li>
396 * <li>if name of <code>typeDefinition</code></li>
399 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
400 final SchemaNode parentNode) {
401 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
402 if (typeDefinition.getQName() == null) {
403 throw new IllegalArgumentException(
404 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
406 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
407 "Type Definitions Local Name cannot be NULL!");
409 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
410 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
411 final Module module = findParentModule(schemaContext, parentNode);
413 if (module != null) {
414 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
415 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
416 if (genTOs != null) {
417 return genTOs.get(typeDefinition.getQName().getLocalName());
425 * Gets base type definition for <code>extendTypeDef</code>. The method is
426 * recursively called until non <code>ExtendedType</code> type is found.
428 * @param extendTypeDef
429 * type definition for which is the base type definition sought
430 * @return type definition which is base type for <code>extendTypeDef</code>
431 * @throws IllegalArgumentException
432 * if <code>extendTypeDef</code> equal null
434 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
435 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
437 TypeDefinition<?> ret = extendTypeDef;
438 while (ret.getBaseType() != null) {
439 ret = ret.getBaseType();
446 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
448 * The path of <code>leafrefType</code> is followed to find referenced node
449 * and its <code>Type</code> is returned.
452 * leafref type definition for which is the type sought
453 * @return JAVA <code>Type</code> of data schema node which is referenced in
454 * <code>leafrefType</code>
455 * @throws IllegalArgumentException
457 * <li>if <code>leafrefType</code> equal null</li>
458 * <li>if path statement of <code>leafrefType</code> equal null</li>
462 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
463 Type returnType = null;
464 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
466 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
467 "The Path Statement for Leafref Type Definition cannot be NULL!");
469 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
470 final String strXPath = xpath.toString();
472 if (strXPath != null) {
473 if (strXPath.indexOf('[') == -1) {
474 final Module module = findParentModule(schemaContext, parentNode);
475 if (module != null) {
476 final SchemaNode dataNode;
477 if (xpath.isAbsolute()) {
478 dataNode = findDataSchemaNode(schemaContext, module, xpath);
480 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
483 if (leafContainsEnumDefinition(dataNode)) {
484 returnType = referencedTypes.get(dataNode.getPath());
485 } else if (leafListContainsEnumDefinition(dataNode)) {
486 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
488 returnType = resolveTypeFromDataSchemaNode(dataNode);
492 returnType = Types.typeForClass(Object.class);
495 if (returnType == null) {
496 throw new IllegalArgumentException("Failed to find leafref target: " + strXPath);
502 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
503 * so then checks if it is of type <code>EnumTypeDefinition</code>.
506 * data schema node for which is checked if it is leaf and if it
508 * @return boolean value
510 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
511 * <li>false - other cases</li>
514 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
515 if (dataNode instanceof LeafSchemaNode) {
516 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
517 if (leaf.getType() instanceof EnumTypeDefinition) {
525 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
526 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
529 * data schema node for which is checked if it is leaflist and if
531 * @return boolean value
533 * <li>true - if <code>dataNode</code> is leaflist of type
535 * <li>false - other cases</li>
538 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
539 if (dataNode instanceof LeafListSchemaNode) {
540 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
541 if (leafList.getType() instanceof EnumTypeDefinition) {
549 * Converts <code>enumTypeDef</code> to
550 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
554 * enumeration type definition which is converted to enumeration
556 * string with name which is used as the enumeration name
557 * @return enumeration type which is built with data (name, enum values)
558 * from <code>enumTypeDef</code>
559 * @throws IllegalArgumentException
561 * <li>if <code>enumTypeDef</code> equals null</li>
562 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
563 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
564 * <li>if name of <code>enumTypeDef</code> equal null</li>
567 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
568 final SchemaNode parentNode) {
569 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
570 Preconditions.checkArgument(enumTypeDef.getValues() != null,
571 "EnumTypeDefinition MUST contain at least ONE value definition!");
572 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
573 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
574 "Local Name in EnumTypeDefinition QName cannot be NULL!");
576 final String enumerationName = BindingMapping.getClassName(enumName);
578 Module module = findParentModule(schemaContext, parentNode);
579 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
581 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
582 enumBuilder.setDescription(enumTypeDef.getDescription());
583 enumBuilder.setReference(enumTypeDef.getReference());
584 enumBuilder.setModuleName(module.getName());
585 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
586 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
587 return enumBuilder.toInstance(null);
591 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
592 * taken from <code>enumTypeDef</code>.
595 * enumeration type definition is source of enumeration data for
596 * <code>typeBuilder</code>
598 * string with the name of enumeration
600 * generated type builder to which is enumeration added
601 * @return enumeration type which contains enumeration data form
602 * <code>enumTypeDef</code>
603 * @throws IllegalArgumentException
605 * <li>if <code>enumTypeDef</code> equals null</li>
606 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
607 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
608 * <li>if name of <code>enumTypeDef</code> equal null</li>
609 * <li>if name of <code>typeBuilder</code> equal null</li>
613 private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
614 final GeneratedTypeBuilderBase<?> typeBuilder) {
615 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
616 Preconditions.checkArgument(enumTypeDef.getValues() != null,
617 "EnumTypeDefinition MUST contain at least ONE value definition!");
618 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
619 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
620 "Local Name in EnumTypeDefinition QName cannot be NULL!");
621 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
623 final String enumerationName = BindingMapping.getClassName(enumName);
625 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
626 enumBuilder.setDescription(enumTypeDef.getDescription());
627 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
628 return enumBuilder.toInstance(enumBuilder);
632 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
635 * contains information about YANG type
636 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
638 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
639 Type returnType = null;
640 if (dataNode != null) {
641 if (dataNode instanceof LeafSchemaNode) {
642 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
643 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
644 } else if (dataNode instanceof LeafListSchemaNode) {
645 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
646 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
653 * Passes through all modules and through all its type definitions and
654 * convert it to generated types.
656 * The modules are firstly sorted by mutual dependencies. The modules are
657 * sequentially passed. All type definitions of a module are at the
658 * beginning sorted so that type definition with less amount of references
659 * to other type definition are processed first.<br />
660 * For each module is created mapping record in the map
661 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
662 * which map current module name to the map which maps type names to
663 * returned types (generated types).
666 private void resolveTypeDefsFromContext() {
667 final Set<Module> modules = schemaContext.getModules();
668 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
669 final Module[] modulesArray = new Module[modules.size()];
671 for (Module modul : modules) {
672 modulesArray[i++] = modul;
674 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
677 for (final Module module : modulesSortedByDependency) {
678 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
679 if (dateTypeMap == null) {
680 dateTypeMap = new HashMap<>();
682 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
683 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
686 for (final Module module : modulesSortedByDependency) {
687 if (module != null) {
688 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
689 if (basePackageName != null) {
690 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
691 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
692 if (listTypeDefinitions != null) {
693 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
694 typedefToGeneratedType(basePackageName, module, typedef);
704 * @param basePackageName
705 * string with name of package to which the module belongs
707 * string with the name of the module for to which the
708 * <code>typedef</code> belongs
710 * type definition of the node for which should be creted JAVA
711 * <code>Type</code> (usually generated TO)
712 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
713 * <code>null</code> value if <code>basePackageName</code> or
714 * <code>modulName</code> or <code>typedef</code> or Q name of
715 * <code>typedef</code> equals <code>null</code>
717 private Type typedefToGeneratedType(final String basePackageName, final Module module,
718 final TypeDefinition<?> typedef) {
719 final String moduleName = module.getName();
720 final Date moduleRevision = module.getRevision();
721 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
722 final String typedefName = typedef.getQName().getLocalName();
723 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
724 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
725 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
726 Type returnType = null;
727 if (innerTypeDefinition instanceof ExtendedType) {
728 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
729 returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName,
731 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
732 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
733 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
734 genTOBuilder.setTypedef(true);
735 genTOBuilder.setIsUnion(true);
736 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
737 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
738 returnType = genTOBuilder.toInstance();
740 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
741 genTOBuilder.getName() + "Builder");
742 unionBuilder.setIsUnionBuilder(true);
743 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
744 method.setReturnType(returnType);
745 method.addParameter(Types.STRING, "defaultValue");
746 method.setAccessModifier(AccessModifier.PUBLIC);
747 method.setStatic(true);
748 Set<Type> types = additionalTypes.get(module);
750 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
751 additionalTypes.put(module, types);
753 types.add(unionBuilder.toInstance());
755 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
756 // enums are automatically Serializable
757 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
758 // TODO units for typedef enum
759 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
760 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
761 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
762 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
763 basePackageName, bitsTypeDefinition, typedefName, module.getName());
764 genTOBuilder.setTypedef(true);
765 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
766 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
767 returnType = genTOBuilder.toInstance();
769 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
770 innerTypeDefinition, typedef);
771 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
773 if (returnType != null) {
774 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
775 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
776 if (typeMap != null) {
777 if (typeMap.isEmpty()) {
778 typeMap = new HashMap<>(4);
779 modulesByDate.put(moduleRevision, typeMap);
781 typeMap.put(typedefName, returnType);
791 * Wraps base YANG type to generated TO.
793 * @param basePackageName
794 * string with name of package to which the module belongs
796 * type definition which is converted to the TO
798 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
799 * @return generated transfer object which represent<code>javaType</code>
801 private static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
802 final Type javaType, final String moduleName) {
803 Preconditions.checkNotNull(javaType, "javaType cannot be null");
804 final String propertyName = "value";
806 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
807 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
808 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
809 genPropBuilder.setReturnType(javaType);
810 genTOBuilder.addEqualsIdentity(genPropBuilder);
811 genTOBuilder.addHashIdentity(genPropBuilder);
812 genTOBuilder.addToStringProperty(genPropBuilder);
813 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
814 final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
815 addStringRegExAsConstant(genTOBuilder, regExps);
817 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
818 genTOBuilder.setTypedef(true);
819 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
820 return genTOBuilder.toInstance();
824 * Converts output list of generated TO builders to one TO builder (first
825 * from list) which contains the remaining builders as its enclosing TO.
827 * @param basePackageName
828 * string with name of package to which the module belongs
830 * type definition which should be of type
831 * <code>UnionTypeDefinition</code>
833 * string with name for generated TO
834 * @return generated TO builder with the list of enclosed generated TO
837 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
838 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
839 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
840 typedef, typeDefName, parentNode);
841 GeneratedTOBuilder resultTOBuilder = null;
842 if (genTOBuilders.isEmpty()) {
843 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typedef);
846 resultTOBuilder = genTOBuilders.remove(0);
847 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
848 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
851 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
852 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
853 resultTOBuilder.addEqualsIdentity(genPropBuilder);
854 resultTOBuilder.addHashIdentity(genPropBuilder);
855 resultTOBuilder.addToStringProperty(genPropBuilder);
857 return resultTOBuilder;
861 * Converts <code>typedef</code> to generated TO with
862 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
863 * added to generated TO builder as property.
865 * @param basePackageName
866 * string with name of package to which the module belongs
868 * type definition which should be of type
869 * <code>UnionTypeDefinition</code>
871 * string with name for generated TO
872 * @return generated TO builder which represents <code>typedef</code>
873 * @throws NullPointerException
875 * <li>if <code>basePackageName</code> is null</li>
876 * <li>if <code>typedef</code> is null</li>
877 * <li>if Qname of <code>typedef</code> is null</li>
880 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
881 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
882 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
883 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
884 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
886 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
887 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
888 final Module module = findParentModule(schemaContext, parentNode);
890 final GeneratedTOBuilderImpl unionGenTOBuilder;
891 if (typeDefName != null && !typeDefName.isEmpty()) {
892 final String typeName = BindingMapping.getClassName(typeDefName);
893 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
894 unionGenTOBuilder.setDescription(typedef.getDescription());
895 unionGenTOBuilder.setReference(typedef.getReference());
896 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
897 unionGenTOBuilder.setModuleName(module.getName());
899 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
902 generatedTOBuilders.add(unionGenTOBuilder);
903 unionGenTOBuilder.setIsUnion(true);
904 final List<String> regularExpressions = new ArrayList<String>();
905 for (final TypeDefinition<?> unionType : unionTypes) {
906 final String unionTypeName = unionType.getQName().getLocalName();
907 if (unionType instanceof UnionType) {
908 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
909 basePackageName, parentNode));
910 } else if (unionType instanceof ExtendedType) {
911 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, regularExpressions,
913 } else if (unionType instanceof EnumTypeDefinition) {
914 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
915 unionTypeName, unionGenTOBuilder);
916 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
918 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
920 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
923 if (!regularExpressions.isEmpty()) {
924 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
927 storeGenTO(typedef, unionGenTOBuilder, parentNode);
929 return generatedTOBuilders;
933 * Wraps code which handle case when union subtype is also of the type
934 * <code>UnionType</code>.
936 * In this case the new generated TO is created for union subtype (recursive
938 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
939 * String, SchemaNode)}
940 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
941 * <code>parentUnionGenTOBuilder</code> is created property which type is
942 * equal to new generated TO.
944 * @param parentUnionGenTOBuilder
945 * generated TO builder to which is the property with the child
946 * union subtype added
947 * @param basePackageName
948 * string with the name of the module package
949 * @param unionSubtype
950 * type definition which represents union subtype
951 * @return list of generated TO builders. The number of the builders can be
952 * bigger one due to recursive call of
953 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
955 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
956 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
957 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
958 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
959 basePackageName, unionSubtype, newTOBuilderName, parentNode);
961 final GeneratedPropertyBuilder propertyBuilder;
962 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
963 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
964 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
965 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
967 return subUnionGenTOBUilders;
971 * Wraps code which handle case when union subtype is of the type
972 * <code>ExtendedType</code>.
974 * If TO for this type already exists it is used for the creation of the
975 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
976 * type is used for the property creation.
978 * @param parentUnionGenTOBuilder
979 * generated TO builder in which new property is created
980 * @param unionSubtype
981 * type definition of the <code>ExtendedType</code> type which
982 * represents union subtype
983 * @param regularExpressions
984 * list of strings with the regular expressions
986 * parent Schema Node for Extended Subtype
989 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
990 final ExtendedType unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
991 final String unionTypeName = unionSubtype.getQName().getLocalName();
992 final Type genTO = findGenTO(unionTypeName, unionSubtype);
994 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
996 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
997 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
998 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1000 if (javaType != null) {
1001 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1004 if (baseType instanceof StringType) {
1005 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
1011 * Searches for generated TO for <code>searchedTypeDef</code> type
1012 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1014 * @param searchedTypeName
1015 * string with name of <code>searchedTypeDef</code>
1016 * @return generated TO for <code>searchedTypeDef</code> or
1017 * <code>null</code> it it doesn't exist
1019 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1020 final Module typeModule = findParentModule(schemaContext, parentNode);
1021 if (typeModule != null && typeModule.getName() != null) {
1022 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1023 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1024 if (genTOs != null) {
1025 return genTOs.get(searchedTypeName);
1032 * Stores generated TO created from <code>genTOBuilder</code> for
1033 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1034 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1037 * type definition for which is <code>genTOBuilder</code> created
1038 * @param genTOBuilder
1039 * generated TO builder which is converted to generated TO and
1042 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1043 final SchemaNode parentNode) {
1044 if (!(newTypeDef instanceof UnionType)) {
1046 final Module parentModule = findParentModule(schemaContext, parentNode);
1047 if (parentModule != null && parentModule.getName() != null) {
1048 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1049 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1050 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1056 * Adds a new property with the name <code>propertyName</code> and with type
1057 * <code>type</code> to <code>unonGenTransObject</code>.
1059 * @param unionGenTransObject
1060 * generated TO to which should be property added
1062 * JAVA <code>type</code> of the property which should be added
1063 * to <code>unionGentransObject</code>
1064 * @param propertyName
1065 * string with name of property which should be added to
1066 * <code>unionGentransObject</code>
1068 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1069 final String propertyName) {
1070 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1071 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1072 .addProperty(BindingMapping.getPropertyName(propertyName));
1073 propBuilder.setReturnType(type);
1075 unionGenTransObject.addEqualsIdentity(propBuilder);
1076 unionGenTransObject.addHashIdentity(propBuilder);
1077 unionGenTransObject.addToStringProperty(propBuilder);
1082 * Converts <code>typedef</code> to the generated TO builder.
1084 * @param basePackageName
1085 * string with name of package to which the module belongs
1087 * type definition from which is the generated TO builder created
1088 * @return generated TO builder which contains data from
1089 * <code>typedef</code> and <code>basePackageName</code>
1091 private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName,
1092 final TypeDefinition<?> typedef, final String moduleName) {
1094 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1095 final String typeDefTOName = typedef.getQName().getLocalName();
1097 if ((packageName != null) && (typeDefTOName != null)) {
1098 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1099 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1101 newType.setDescription(typedef.getDescription());
1102 newType.setReference(typedef.getReference());
1103 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1104 newType.setModuleName(moduleName);
1112 * Converts <code>typeDef</code> which should be of the type
1113 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1115 * All the bits of the typeDef are added to returning generated TO as
1118 * @param basePackageName
1119 * string with name of package to which the module belongs
1121 * type definition from which is the generated TO builder created
1122 * @param typeDefName
1123 * string with the name for generated TO builder
1124 * @return generated TO builder which represents <code>typeDef</code>
1125 * @throws IllegalArgumentException
1127 * <li>if <code>typeDef</code> equals null</li>
1128 * <li>if <code>basePackageName</code> equals null</li>
1131 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1132 final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1134 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1135 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1137 if (typeDef instanceof BitsTypeDefinition) {
1138 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1140 final String typeName = BindingMapping.getClassName(typeDefName);
1141 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1143 genTOBuilder.setDescription(typeDef.getDescription());
1144 genTOBuilder.setReference(typeDef.getReference());
1145 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1146 genTOBuilder.setModuleName(moduleName);
1147 genTOBuilder.setBaseType(typeDef);
1149 final List<Bit> bitList = bitsTypeDefinition.getBits();
1150 GeneratedPropertyBuilder genPropertyBuilder;
1151 for (final Bit bit : bitList) {
1152 String name = bit.getName();
1153 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1154 genPropertyBuilder.setReadOnly(true);
1155 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1157 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1158 genTOBuilder.addHashIdentity(genPropertyBuilder);
1159 genTOBuilder.addToStringProperty(genPropertyBuilder);
1162 return genTOBuilder;
1168 * Converts the pattern constraints from <code>typedef</code> to the list of
1169 * the strings which represents these constraints.
1172 * extended type in which are the pattern constraints sought
1173 * @return list of strings which represents the constraint patterns
1174 * @throws IllegalArgumentException
1175 * if <code>typedef</code> equals null
1178 private static List<String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
1179 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1181 final List<PatternConstraint> patternConstraints;
1182 if (typedef instanceof ExtendedType) {
1183 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1184 if (strTypeDef instanceof StringType) {
1185 patternConstraints = ((ExtendedType)typedef).getPatternConstraints();
1187 patternConstraints = ImmutableList.of();
1189 } else if (typedef instanceof StringTypeDefinition) {
1190 // FIXME: run diff against base
1191 patternConstraints = ((StringTypeDefinition) typedef).getPatternConstraints();
1193 patternConstraints = ImmutableList.of();
1196 final List<String> regExps = new ArrayList<>(patternConstraints.size());
1197 for (PatternConstraint patternConstraint : patternConstraints) {
1198 final String regEx = patternConstraint.getRegularExpression();
1199 final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1200 regExps.add(modifiedRegEx);
1208 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1209 * expressions from the <code>regularExpressions</code>
1211 * @param genTOBuilder
1212 * generated TO builder to which are
1213 * <code>regular expressions</code> added
1214 * @param regularExpressions
1215 * list of string which represent regular expressions
1216 * @throws IllegalArgumentException
1218 * <li>if <code>genTOBuilder</code> equals null</li>
1219 * <li>if <code>regularExpressions</code> equals null</li>
1222 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1223 if (genTOBuilder == null) {
1224 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1226 if (regularExpressions == null) {
1227 throw new IllegalArgumentException("List of regular expressions can't be null");
1229 if (!regularExpressions.isEmpty()) {
1230 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1231 regularExpressions);
1236 * Creates generated TO with data about inner extended type
1237 * <code>innerExtendedType</code>, about the package name
1238 * <code>typedefName</code> and about the generated TO name
1239 * <code>typedefName</code>.
1241 * It is supposed that <code>innerExtendedType</code> is already present in
1242 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1243 * be possible set it as extended type for the returning generated TO.
1247 * @param innerExtendedType
1248 * extended type which is part of some other extended type
1249 * @param basePackageName
1250 * string with the package name of the module
1253 * @return generated TO which extends generated TO for
1254 * <code>innerExtendedType</code>
1255 * @throws IllegalArgumentException
1257 * <li>if <code>extendedType</code> equals null</li>
1258 * <li>if <code>basePackageName</code> equals null</li>
1259 * <li>if <code>typedefName</code> equals null</li>
1262 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1263 final ExtendedType innerExtendedType, final String basePackageName, final String moduleName) {
1264 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1265 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1267 final String typedefName = typedef.getQName().getLocalName();
1268 final String classTypedefName = BindingMapping.getClassName(typedefName);
1269 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1270 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1272 genTOBuilder.setDescription(typedef.getDescription());
1273 genTOBuilder.setReference(typedef.getReference());
1274 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1275 genTOBuilder.setModuleName(moduleName);
1276 genTOBuilder.setTypedef(true);
1277 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1278 genTOBuilder.setRestrictions(r);
1280 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1281 genTOBuilder.setIsUnion(true);
1284 Map<Date, Map<String, Type>> modulesByDate = null;
1285 Map<String, Type> typeMap = null;
1286 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1287 if (parentModule != null) {
1288 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1289 typeMap = modulesByDate.get(parentModule.getRevision());
1292 if (typeMap != null) {
1293 Type type = typeMap.get(innerTypeDef);
1294 if (type instanceof GeneratedTransferObject) {
1295 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1298 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1299 makeSerializable(genTOBuilder);
1301 return genTOBuilder.toInstance();
1305 * Add {@link Serializable} to implemented interfaces of this TO. Also
1306 * compute and add serialVersionUID property.
1309 * transfer object which needs to be serializable
1311 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1312 gto.addImplementsType(Types.typeForClass(Serializable.class));
1313 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1314 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1319 * Finds out for each type definition how many immersion (depth) is
1320 * necessary to get to the base type. Every type definition is inserted to
1321 * the map which key is depth and value is list of type definitions with
1322 * equal depth. In next step are lists from this map concatenated to one
1323 * list in ascending order according to their depth. All type definitions
1324 * are in the list behind all type definitions on which depends.
1326 * @param unsortedTypeDefinitions
1327 * list of type definitions which should be sorted by depth
1328 * @return list of type definitions sorted according their each other
1329 * dependencies (type definitions which are depend on other type
1330 * definitions are in list behind them).
1332 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1333 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1334 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1336 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1337 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1338 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1339 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1340 if (typeDefinitionsConcreteDepth == null) {
1341 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1342 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1344 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1347 // SortedMap guarantees order corresponding to keys in ascending order
1348 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1349 sortedTypeDefinition.addAll(v);
1352 return sortedTypeDefinition;
1356 * Returns how many immersion is necessary to get from the type definition
1359 * @param typeDefinition
1360 * type definition for which is depth sought.
1361 * @return number of immersions which are necessary to get from the type
1362 * definition to the base type
1364 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1365 // FIXME: rewrite this in a non-recursive manner, without ExtendedType and UnionType
1366 if (typeDefinition == null) {
1370 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1372 if (baseType instanceof ExtendedType) {
1373 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1374 } else if (baseType instanceof UnionType) {
1375 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1376 int maxChildDepth = 0;
1378 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1379 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1380 if (childDepth > maxChildDepth) {
1381 maxChildDepth = childDepth;
1384 return maxChildDepth;
1390 * Returns string which contains the same value as <code>name</code> but
1391 * integer suffix is incremented by one. If <code>name</code> contains no
1392 * number suffix then number 1 is added.
1395 * string with name of augmented node
1396 * @return string with the number suffix incremented by one (or 1 is added)
1398 private static String provideAvailableNameForGenTOBuilder(final String name) {
1399 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1401 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1402 return name.substring(0, mtch.start()) + newSuffix;
1408 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1409 if (!Strings.isNullOrEmpty(units)) {
1410 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1411 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1412 prop.setReturnType(Types.STRING);
1413 to.addToStringProperty(prop);
1418 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1419 return getTypeDefaultConstruction(node, node.getDefault());
1422 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1423 TypeDefinition<?> type = node.getType();
1424 QName typeQName = type.getQName();
1425 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1426 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1427 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1430 StringBuilder sb = new StringBuilder();
1431 String result = null;
1432 if (base instanceof BinaryTypeDefinition) {
1433 result = binaryToDef(defaultValue);
1434 } else if (base instanceof BitsTypeDefinition) {
1437 Module parent = getParentModule(node);
1438 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1440 if (!(path.hasNext())) {
1441 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1442 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1443 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1445 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1446 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1447 parentName = BindingMapping.getClassName(parent.getName());
1448 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1450 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1451 } else if (base instanceof BooleanTypeDefinition) {
1452 result = typeToDef(Boolean.class, defaultValue);
1453 } else if (base instanceof DecimalTypeDefinition) {
1454 result = typeToDef(BigDecimal.class, defaultValue);
1455 } else if (base instanceof EmptyTypeDefinition) {
1456 result = typeToDef(Boolean.class, defaultValue);
1457 } else if (base instanceof EnumTypeDefinition) {
1458 char[] defValArray = defaultValue.toCharArray();
1459 char first = Character.toUpperCase(defaultValue.charAt(0));
1460 defValArray[0] = first;
1461 String newDefVal = new String(defValArray);
1463 if (type instanceof ExtendedType) {
1464 Module m = getParentModule(type);
1465 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1466 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1467 className = packageName + "." + BindingMapping.getClassName(typeQName);
1469 Module parentModule = getParentModule(node);
1470 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1471 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1472 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1474 result = className + "." + newDefVal;
1475 } else if (base instanceof IdentityrefTypeDefinition) {
1476 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1477 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1478 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1479 } else if (base instanceof Int8) {
1480 result = typeToDef(Byte.class, defaultValue);
1481 } else if (base instanceof Int16) {
1482 result = typeToDef(Short.class, defaultValue);
1483 } else if (base instanceof Int32) {
1484 result = typeToDef(Integer.class, defaultValue);
1485 } else if (base instanceof Int64) {
1486 result = typeToDef(Long.class, defaultValue);
1487 } else if (base instanceof LeafrefTypeDefinition) {
1488 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1489 } else if (base instanceof StringTypeDefinition) {
1490 result = "\"" + defaultValue + "\"";
1491 } else if (base instanceof Uint8) {
1492 result = typeToDef(Short.class, defaultValue);
1493 } else if (base instanceof Uint16) {
1494 result = typeToDef(Integer.class, defaultValue);
1495 } else if (base instanceof Uint32) {
1496 result = typeToDef(Long.class, defaultValue);
1497 } else if (base instanceof Uint64) {
1498 result = typeToDef(BigInteger.class, defaultValue);
1499 } else if (base instanceof UnionTypeDefinition) {
1500 result = unionToDef(node);
1506 if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
1507 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
1508 Module m = getParentModule(type);
1509 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1510 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1511 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1512 sb.insert(0, "new " + className + "(");
1513 sb.insert(sb.length(), ')');
1516 return sb.toString();
1519 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1520 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1523 private static String binaryToDef(final String defaultValue) {
1524 StringBuilder sb = new StringBuilder();
1525 BaseEncoding en = BaseEncoding.base64();
1526 byte[] encoded = en.decode(defaultValue);
1527 sb.append("new byte[] {");
1528 for (int i = 0; i < encoded.length; i++) {
1529 sb.append(encoded[i]);
1530 if (i != encoded.length - 1) {
1535 return sb.toString();
1538 private static final Comparator<Bit> BIT_NAME_COMPARATOR = new Comparator<Bit>() {
1540 public int compare(final Bit o1, final Bit o2) {
1541 return o1.getName().compareTo(o2.getName());
1545 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1546 final boolean isExt) {
1547 List<Bit> bits = new ArrayList<>(type.getBits());
1548 Collections.sort(bits, BIT_NAME_COMPARATOR);
1549 StringBuilder sb = new StringBuilder();
1552 sb.append(className);
1555 for (int i = 0; i < bits.size(); i++) {
1556 if (bits.get(i).getName().equals(defaultValue)) {
1561 if (i != bits.size() - 1) {
1568 return sb.toString();
1571 private Module getParentModule(final SchemaNode node) {
1572 QName qname = node.getPath().getPathFromRoot().iterator().next();
1573 URI namespace = qname.getNamespace();
1574 Date revision = qname.getRevision();
1575 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1578 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1579 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1580 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1581 "The Path Statement for Leafref Type Definition cannot be NULL!");
1583 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1584 final String strXPath = xpath.toString();
1586 if (strXPath != null) {
1587 if (strXPath.indexOf('[') == -1) {
1588 final Module module = findParentModule(schemaContext, parentNode);
1589 if (module != null) {
1590 final SchemaNode dataNode;
1591 if (xpath.isAbsolute()) {
1592 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1594 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1596 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1600 return "new java.lang.Object()";
1607 private String unionToDef(final LeafSchemaNode node) {
1611 if (node.getType() instanceof ExtendedType) {
1612 ExtendedType type = (ExtendedType) node.getType();
1613 QName typeQName = type.getQName();
1614 Module module = null;
1615 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1616 if (modules.size() > 1) {
1617 for (Module m : modules) {
1618 if (m.getRevision().equals(typeQName.getRevision())) {
1623 if (module == null) {
1624 List<Module> modulesList = new ArrayList<>(modules);
1625 Collections.sort(modulesList, new Comparator<Module>() {
1627 public int compare(final Module o1, final Module o2) {
1628 return o1.getRevision().compareTo(o2.getRevision());
1631 module = modulesList.get(0);
1634 module = modules.iterator().next();
1637 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1638 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1640 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1641 QName first = path.next();
1642 if (!(path.hasNext())) {
1643 URI namespace = first.getNamespace();
1644 Date revision = first.getRevision();
1645 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1646 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1647 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1648 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1650 URI namespace = first.getNamespace();
1651 Date revision = first.getRevision();
1652 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1653 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1654 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1655 node.getType().getPath());
1656 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1659 return union(className, node.getDefault(), node);
1662 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1663 StringBuilder sb = new StringBuilder();
1665 sb.append(className);
1667 sb.append(defaultValue);
1668 sb.append("\".toCharArray())");
1669 return sb.toString();
1673 public String getConstructorPropertyName(final SchemaNode node) {
1674 if (node instanceof TypeDefinition<?>) {
1682 public String getParamNameFromType(final TypeDefinition<?> type) {
1683 return BindingMapping.getPropertyName(type.getQName().getLocalName());