2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.sal.binding.yang.types;
10 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
11 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
12 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Sets;
16 import com.google.common.io.BaseEncoding;
17 import java.io.Serializable;
18 import java.math.BigDecimal;
19 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.Comparator;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
31 import java.util.TreeMap;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34 import org.apache.commons.lang3.StringEscapeUtils;
35 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
36 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
37 import org.opendaylight.yangtools.binding.generator.util.Types;
38 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
39 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
40 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
41 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
42 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
43 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
44 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
45 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty;
46 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
47 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
48 import org.opendaylight.yangtools.sal.binding.model.api.Type;
49 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
50 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
51 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
53 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
54 import org.opendaylight.yangtools.yang.binding.BindingMapping;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.Module;
60 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
62 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
64 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
68 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
69 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
76 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
79 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
80 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
81 import org.opendaylight.yangtools.yang.model.util.Int16;
82 import org.opendaylight.yangtools.yang.model.util.Int32;
83 import org.opendaylight.yangtools.yang.model.util.Int64;
84 import org.opendaylight.yangtools.yang.model.util.Int8;
85 import org.opendaylight.yangtools.yang.model.util.StringType;
86 import org.opendaylight.yangtools.yang.model.util.Uint16;
87 import org.opendaylight.yangtools.yang.model.util.Uint32;
88 import org.opendaylight.yangtools.yang.model.util.Uint64;
89 import org.opendaylight.yangtools.yang.model.util.Uint8;
90 import org.opendaylight.yangtools.yang.model.util.UnionType;
92 public final class TypeProviderImpl implements TypeProvider {
93 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
96 * Contains the schema data red from YANG files.
98 private final SchemaContext schemaContext;
101 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
103 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
106 * The map which maps schema paths to JAVA <code>Type</code>.
108 private final Map<SchemaPath, Type> referencedTypes;
109 private final Map<Module, Set<Type>> additionalTypes;
112 * Creates new instance of class <code>TypeProviderImpl</code>.
114 * @param schemaContext
115 * contains the schema data red from YANG files
116 * @throws IllegalArgumentException
117 * if <code>schemaContext</code> equal null.
119 public TypeProviderImpl(final SchemaContext schemaContext) {
120 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
122 this.schemaContext = schemaContext;
123 this.genTypeDefsContextMap = new HashMap<>();
124 this.referencedTypes = new HashMap<>();
125 this.additionalTypes = new HashMap<>();
126 resolveTypeDefsFromContext();
130 * Puts <code>refType</code> to map with key <code>refTypePath</code>
133 * schema path used as the map key
135 * type which represents the map value
136 * @throws IllegalArgumentException
138 * <li>if <code>refTypePath</code> equal null</li>
139 * <li>if <code>refType</code> equal null</li>
143 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
144 Preconditions.checkArgument(refTypePath != null,
145 "Path reference of Enumeration Type Definition cannot be NULL!");
146 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
147 referencedTypes.put(refTypePath, refType);
150 public Map<Module, Set<Type>> getAdditionalTypes() {
151 return additionalTypes;
156 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
159 * string with YANG name of type
160 * @return JAVA <code>Type</code> for YANG type <code>type</code>
161 * @see TypeProvider#javaTypeForYangType(String)
165 public Type javaTypeForYangType(final String type) {
166 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
170 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
171 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
175 * Converts schema definition type <code>typeDefinition</code> to JAVA
178 * @param typeDefinition
179 * type definition which is converted to JAVA type
180 * @throws IllegalArgumentException
182 * <li>if <code>typeDefinition</code> equal null</li>
183 * <li>if Qname of <code>typeDefinition</code> equal null</li>
184 * <li>if name of <code>typeDefinition</code> equal null</li>
188 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
189 final Restrictions r) {
191 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
192 Preconditions.checkArgument(typeDefinition.getQName() != null,
193 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
194 String typedefName = typeDefinition.getQName().getLocalName();
195 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
197 if (typeDefinition instanceof ExtendedType) {
198 returnType = javaTypeForExtendedType(typeDefinition);
199 if (r != null && returnType instanceof GeneratedTransferObject) {
200 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
201 Module module = findParentModule(schemaContext, parentNode);
202 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
203 String packageName = packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
204 String genTOName = BindingMapping.getClassName(typedefName);
205 String name = packageName + "." + genTOName;
206 if (!(returnType.getFullyQualifiedName().equals(name))) {
207 returnType = shadedTOWithRestrictions(gto, r);
211 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
212 if (returnType == null) {
213 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
220 private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
221 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
222 GeneratedTransferObject parent = gto.getSuperType();
223 if (parent != null) {
224 gtob.setExtendsType(parent);
226 gtob.setRestrictions(r);
227 for (GeneratedProperty gp : gto.getProperties()) {
228 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
229 gpb.setValue(gp.getValue());
230 gpb.setReadOnly(gp.isReadOnly());
231 gpb.setAccessModifier(gp.getAccessModifier());
232 gpb.setReturnType(gp.getReturnType());
233 gpb.setFinal(gp.isFinal());
234 gpb.setStatic(gp.isStatic());
236 return gtob.toInstance();
240 * Returns JAVA <code>Type</code> for instances of the type
241 * <code>LeafrefTypeDefinition</code> or
242 * <code>IdentityrefTypeDefinition</code>.
244 * @param typeDefinition
245 * type definition which is converted to JAVA <code>Type</code>
246 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
248 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
249 if (typeDefinition instanceof LeafrefTypeDefinition) {
250 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
251 return provideTypeForLeafref(leafref, parentNode);
252 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
253 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
254 return provideTypeForIdentityref(idref);
261 * Returns JAVA <code>Type</code> for instances of the type
262 * <code>ExtendedType</code>.
264 * @param typeDefinition
265 * type definition which is converted to JAVA <code>Type</code>
266 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
268 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
269 final String typedefName = typeDefinition.getQName().getLocalName();
270 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
271 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
272 if (returnType == null) {
273 if (baseTypeDef instanceof EnumTypeDefinition) {
274 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
275 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
277 final Module module = findParentModule(schemaContext, typeDefinition);
278 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
279 if (module != null) {
280 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
281 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
282 if (genTOs != null) {
283 returnType = genTOs.get(typedefName);
285 if (returnType == null) {
286 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
287 baseTypeDef, typeDefinition, r);
296 * Seeks for identity reference <code>idref</code> the JAVA
297 * <code>type</code>.<br />
301 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
302 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
305 * identityref type definition for which JAVA <code>Type</code>
307 * @return JAVA <code>Type</code> of the identity which is refrenced through
310 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
311 QName baseIdQName = idref.getIdentity().getQName();
312 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
313 baseIdQName.getRevision());
314 IdentitySchemaNode identity = null;
315 for (IdentitySchemaNode id : module.getIdentities()) {
316 if (id.getQName().equals(baseIdQName)) {
320 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
322 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
323 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
324 final String genTypeName = BindingMapping.getClassName(identity.getQName());
326 Type baseType = Types.typeForClass(Class.class);
327 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
328 return Types.parameterizedTypeFor(baseType, paramType);
332 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
334 * @param typeDefinition
335 * type definition which should be converted to JAVA
337 * @return JAVA <code>Type</code> which represents
338 * <code>typeDefinition</code>
339 * @throws IllegalArgumentException
341 * <li>if <code>typeDefinition</code> equal null</li>
342 * <li>if Q name of <code>typeDefinition</code></li>
343 * <li>if name of <code>typeDefinition</code></li>
346 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
347 final SchemaNode parentNode) {
348 Type returnType = null;
349 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
350 if (typeDefinition.getQName() == null) {
351 throw new IllegalArgumentException(
352 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
354 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
355 "Type Definitions Local Name cannot be NULL!");
357 final String typedefName = typeDefinition.getQName().getLocalName();
358 if (typeDefinition instanceof ExtendedType) {
359 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
361 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
362 final Module module = findParentModule(schemaContext, parentNode);
364 if (module != null) {
365 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
366 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
367 if (genTOs != null) {
368 returnType = genTOs.get(typedefName);
377 * Gets base type definition for <code>extendTypeDef</code>. The method is
378 * recursivelly called until non <code>ExtendedType</code> type is found.
380 * @param extendTypeDef
381 * type definition for which is the base type definition sought
382 * @return type definition which is base type for <code>extendTypeDef</code>
383 * @throws IllegalArgumentException
384 * if <code>extendTypeDef</code> equal null
386 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
387 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
388 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
389 if (baseTypeDef == null) {
390 return extendTypeDef;
391 } else if (baseTypeDef instanceof ExtendedType) {
392 return baseTypeDefForExtendedType(baseTypeDef);
400 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
402 * The path of <code>leafrefType</code> is followed to find referenced node
403 * and its <code>Type</code> is returned.
406 * leafref type definition for which is the type sought
407 * @return JAVA <code>Type</code> of data schema node which is referenced in
408 * <code>leafrefType</code>
409 * @throws IllegalArgumentException
411 * <li>if <code>leafrefType</code> equal null</li>
412 * <li>if path statement of <code>leafrefType</code> equal null</li>
416 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
417 Type returnType = null;
418 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
420 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
421 "The Path Statement for Leafref Type Definition cannot be NULL!");
423 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
424 final String strXPath = xpath.toString();
426 if (strXPath != null) {
427 if (strXPath.indexOf('[') == -1) {
428 final Module module = findParentModule(schemaContext, parentNode);
429 if (module != null) {
430 final SchemaNode dataNode;
431 if (xpath.isAbsolute()) {
432 dataNode = findDataSchemaNode(schemaContext, module, xpath);
434 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
437 if (leafContainsEnumDefinition(dataNode)) {
438 returnType = referencedTypes.get(dataNode.getPath());
439 } else if (leafListContainsEnumDefinition(dataNode)) {
440 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
442 returnType = resolveTypeFromDataSchemaNode(dataNode);
446 returnType = Types.typeForClass(Object.class);
449 if (returnType == null) {
450 throw new IllegalArgumentException("Failed to find leafref target: " + strXPath);
456 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
457 * so then checks if it is of type <code>EnumTypeDefinition</code>.
460 * data schema node for which is checked if it is leaf and if it
462 * @return boolean value
464 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
465 * <li>false - other cases</li>
468 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
469 if (dataNode instanceof LeafSchemaNode) {
470 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
471 if (leaf.getType() instanceof EnumTypeDefinition) {
479 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
480 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
483 * data schema node for which is checked if it is leaflist and if
485 * @return boolean value
487 * <li>true - if <code>dataNode</code> is leaflist of type
489 * <li>false - other cases</li>
492 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
493 if (dataNode instanceof LeafListSchemaNode) {
494 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
495 if (leafList.getType() instanceof EnumTypeDefinition) {
503 * Converts <code>enumTypeDef</code> to
504 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
508 * enumeration type definition which is converted to enumeration
510 * string with name which is used as the enumeration name
511 * @return enumeration type which is built with data (name, enum values)
512 * from <code>enumTypeDef</code>
513 * @throws IllegalArgumentException
515 * <li>if <code>enumTypeDef</code> equals null</li>
516 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
517 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
518 * <li>if name of <code>enumTypeDef</code> equal null</li>
521 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
522 final SchemaNode parentNode) {
523 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
524 Preconditions.checkArgument(enumTypeDef.getValues() != null,
525 "EnumTypeDefinition MUST contain at least ONE value definition!");
526 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
527 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
528 "Local Name in EnumTypeDefinition QName cannot be NULL!");
530 final String enumerationName = BindingMapping.getClassName(enumName);
532 Module module = findParentModule(schemaContext, parentNode);
533 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
535 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
536 enumBuilder.setDescription(enumTypeDef.getDescription());
537 enumBuilder.setReference(enumTypeDef.getReference());
538 enumBuilder.setModuleName(module.getName());
539 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
540 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
541 return enumBuilder.toInstance(null);
545 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
546 * taken from <code>enumTypeDef</code>.
549 * enumeration type definition is source of enumeration data for
550 * <code>typeBuilder</code>
552 * string with the name of enumeration
554 * generated type builder to which is enumeration added
555 * @return enumeration type which contains enumeration data form
556 * <code>enumTypeDef</code>
557 * @throws IllegalArgumentException
559 * <li>if <code>enumTypeDef</code> equals null</li>
560 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
561 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
562 * <li>if name of <code>enumTypeDef</code> equal null</li>
563 * <li>if name of <code>typeBuilder</code> equal null</li>
567 private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
568 final GeneratedTypeBuilderBase<?> typeBuilder) {
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!");
575 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
577 final String enumerationName = BindingMapping.getClassName(enumName);
579 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
580 enumBuilder.setDescription(enumTypeDef.getDescription());
581 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
582 return enumBuilder.toInstance(enumBuilder);
586 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
589 * contains information about YANG type
590 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
592 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
593 Type returnType = null;
594 if (dataNode != null) {
595 if (dataNode instanceof LeafSchemaNode) {
596 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
597 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
598 } else if (dataNode instanceof LeafListSchemaNode) {
599 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
600 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
607 * Passes through all modules and through all its type definitions and
608 * convert it to generated types.
610 * The modules are firstly sorted by mutual dependencies. The modules are
611 * sequentially passed. All type definitions of a module are at the
612 * beginning sorted so that type definition with less amount of references
613 * to other type definition are processed first.<br />
614 * For each module is created mapping record in the map
615 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
616 * which map current module name to the map which maps type names to
617 * returned types (generated types).
620 private void resolveTypeDefsFromContext() {
621 final Set<Module> modules = schemaContext.getModules();
622 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
623 final Module[] modulesArray = new Module[modules.size()];
625 for (Module modul : modules) {
626 modulesArray[i++] = modul;
628 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
631 for (final Module module : modulesSortedByDependency) {
632 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
633 if (dateTypeMap == null) {
634 dateTypeMap = new HashMap<>();
636 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
637 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
640 for (final Module module : modulesSortedByDependency) {
641 if (module == null) {
644 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
646 final DataNodeIterator it = new DataNodeIterator(module);
647 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
648 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
650 if ((listTypeDefinitions != null) && (basePackageName != null)) {
651 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
652 typedefToGeneratedType(basePackageName, module, typedef);
660 * @param basePackageName
661 * string with name of package to which the module belongs
663 * string with the name of the module for to which the
664 * <code>typedef</code> belongs
666 * type definition of the node for which should be creted JAVA
667 * <code>Type</code> (usually generated TO)
668 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
669 * <code>null</code> value if <code>basePackageName</code> or
670 * <code>modulName</code> or <code>typedef</code> or Q name of
671 * <code>typedef</code> equals <code>null</code>
673 private Type typedefToGeneratedType(final String basePackageName, final Module module,
674 final TypeDefinition<?> typedef) {
675 final String moduleName = module.getName();
676 final Date moduleRevision = module.getRevision();
677 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
678 final String typedefName = typedef.getQName().getLocalName();
679 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
680 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
681 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
682 Type returnType = null;
683 if (innerTypeDefinition instanceof ExtendedType) {
684 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
685 returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName,
687 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
688 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
689 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
690 genTOBuilder.setTypedef(true);
691 genTOBuilder.setIsUnion(true);
692 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
693 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
694 returnType = genTOBuilder.toInstance();
696 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
697 genTOBuilder.getName() + "Builder");
698 unionBuilder.setIsUnionBuilder(true);
699 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
700 method.setReturnType(returnType);
701 method.addParameter(Types.STRING, "defaultValue");
702 method.setAccessModifier(AccessModifier.PUBLIC);
703 method.setStatic(true);
704 Set<Type> types = additionalTypes.get(module);
706 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
707 additionalTypes.put(module, types);
709 types.add(unionBuilder.toInstance());
711 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
712 // enums are automatically Serializable
713 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
714 // TODO units for typedef enum
715 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
716 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
717 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
718 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
719 basePackageName, bitsTypeDefinition, typedefName, module.getName());
720 genTOBuilder.setTypedef(true);
721 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
722 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
723 returnType = genTOBuilder.toInstance();
725 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
726 innerTypeDefinition, typedef);
727 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
729 if (returnType != null) {
730 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
731 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
732 if (typeMap != null) {
733 if (typeMap.isEmpty()) {
734 typeMap = new HashMap<>(4);
735 modulesByDate.put(moduleRevision, typeMap);
737 typeMap.put(typedefName, returnType);
747 * Wraps base YANG type to generated TO.
749 * @param basePackageName
750 * string with name of package to which the module belongs
752 * type definition which is converted to the TO
754 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
755 * @return generated transfer object which represent<code>javaType</code>
757 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
758 final Type javaType, final String moduleName) {
759 Preconditions.checkNotNull(javaType, "javaType cannot be null");
760 final String propertyName = "value";
762 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
763 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
764 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
765 genPropBuilder.setReturnType(javaType);
766 genTOBuilder.addEqualsIdentity(genPropBuilder);
767 genTOBuilder.addHashIdentity(genPropBuilder);
768 genTOBuilder.addToStringProperty(genPropBuilder);
769 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef instanceof ExtendedType) {
770 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
771 addStringRegExAsConstant(genTOBuilder, regExps);
773 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
774 genTOBuilder.setTypedef(true);
775 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
776 return genTOBuilder.toInstance();
780 * Converts output list of generated TO builders to one TO builder (first
781 * from list) which contains the remaining builders as its enclosing TO.
783 * @param basePackageName
784 * string with name of package to which the module belongs
786 * type definition which should be of type
787 * <code>UnionTypeDefinition</code>
789 * string with name for generated TO
790 * @return generated TO builder with the list of enclosed generated TO
793 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
794 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
795 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
796 typedef, typeDefName, parentNode);
797 GeneratedTOBuilder resultTOBuilder = null;
798 if (genTOBuilders.isEmpty()) {
799 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typedef);
802 resultTOBuilder = genTOBuilders.remove(0);
803 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
804 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
807 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
808 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
809 resultTOBuilder.addEqualsIdentity(genPropBuilder);
810 resultTOBuilder.addHashIdentity(genPropBuilder);
811 resultTOBuilder.addToStringProperty(genPropBuilder);
813 return resultTOBuilder;
817 * Converts <code>typedef</code> to generated TO with
818 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
819 * added to generated TO builder as property.
821 * @param basePackageName
822 * string with name of package to which the module belongs
824 * type definition which should be of type
825 * <code>UnionTypeDefinition</code>
827 * string with name for generated TO
828 * @return generated TO builder which represents <code>typedef</code>
829 * @throws NullPointerException
831 * <li>if <code>basePackageName</code> is null</li>
832 * <li>if <code>typedef</code> is null</li>
833 * <li>if Qname of <code>typedef</code> is null</li>
836 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
837 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
838 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
839 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
840 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
842 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
843 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
844 final Module module = findParentModule(schemaContext, parentNode);
846 final GeneratedTOBuilderImpl unionGenTOBuilder;
847 if (typeDefName != null && !typeDefName.isEmpty()) {
848 final String typeName = BindingMapping.getClassName(typeDefName);
849 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
850 unionGenTOBuilder.setDescription(typedef.getDescription());
851 unionGenTOBuilder.setReference(typedef.getReference());
852 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
853 unionGenTOBuilder.setModuleName(module.getName());
855 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
858 generatedTOBuilders.add(unionGenTOBuilder);
859 unionGenTOBuilder.setIsUnion(true);
860 final List<String> regularExpressions = new ArrayList<String>();
861 for (final TypeDefinition<?> unionType : unionTypes) {
862 final String unionTypeName = unionType.getQName().getLocalName();
863 if (unionType instanceof UnionType) {
864 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
865 basePackageName, parentNode));
866 } else if (unionType instanceof ExtendedType) {
867 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, regularExpressions,
869 } else if (unionType instanceof EnumTypeDefinition) {
870 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
871 unionTypeName, unionGenTOBuilder);
872 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
874 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
876 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
879 if (!regularExpressions.isEmpty()) {
880 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
883 storeGenTO(typedef, unionGenTOBuilder, parentNode);
885 return generatedTOBuilders;
889 * Wraps code which handle case when union subtype is also of the type
890 * <code>UnionType</code>.
892 * In this case the new generated TO is created for union subtype (recursive
894 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
895 * String, SchemaNode)}
896 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
897 * <code>parentUnionGenTOBuilder</code> is created property which type is
898 * equal to new generated TO.
900 * @param parentUnionGenTOBuilder
901 * generated TO builder to which is the property with the child
902 * union subtype added
903 * @param basePackageName
904 * string with the name of the module package
905 * @param unionSubtype
906 * type definition which represents union subtype
907 * @return list of generated TO builders. The number of the builders can be
908 * bigger one due to recursive call of
909 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
911 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
912 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
913 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
914 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
915 basePackageName, unionSubtype, newTOBuilderName, parentNode);
917 final GeneratedPropertyBuilder propertyBuilder;
918 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
919 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
920 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
921 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
923 return subUnionGenTOBUilders;
927 * Wraps code which handle case when union subtype is of the type
928 * <code>ExtendedType</code>.
930 * If TO for this type already exists it is used for the creation of the
931 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
932 * type is used for the property creation.
934 * @param parentUnionGenTOBuilder
935 * generated TO builder in which new property is created
936 * @param unionSubtype
937 * type definition of the <code>ExtendedType</code> type which
938 * represents union subtype
939 * @param regularExpressions
940 * list of strings with the regular expressions
942 * parent Schema Node for Extended Subtype
945 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
946 final ExtendedType unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
947 final String unionTypeName = unionSubtype.getQName().getLocalName();
948 final Type genTO = findGenTO(unionTypeName, unionSubtype);
950 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
952 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
953 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
954 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
956 if (javaType != null) {
957 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
960 if (baseType instanceof StringType) {
961 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
967 * Searches for generated TO for <code>searchedTypeDef</code> type
968 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
970 * @param searchedTypeName
971 * string with name of <code>searchedTypeDef</code>
972 * @return generated TO for <code>searchedTypeDef</code> or
973 * <code>null</code> it it doesn't exist
975 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
976 final Module typeModule = findParentModule(schemaContext, parentNode);
977 if (typeModule != null && typeModule.getName() != null) {
978 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
979 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
980 if (genTOs != null) {
981 return genTOs.get(searchedTypeName);
988 * Stores generated TO created from <code>genTOBuilder</code> for
989 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
990 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
993 * type definition for which is <code>genTOBuilder</code> created
994 * @param genTOBuilder
995 * generated TO builder which is converted to generated TO and
998 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
999 final SchemaNode parentNode) {
1000 if (!(newTypeDef instanceof UnionType)) {
1002 final Module parentModule = findParentModule(schemaContext, parentNode);
1003 if (parentModule != null && parentModule.getName() != null) {
1004 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1005 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1006 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1012 * Adds a new property with the name <code>propertyName</code> and with type
1013 * <code>type</code> to <code>unonGenTransObject</code>.
1015 * @param unionGenTransObject
1016 * generated TO to which should be property added
1018 * JAVA <code>type</code> of the property which should be added
1019 * to <code>unionGentransObject</code>
1020 * @param propertyName
1021 * string with name of property which should be added to
1022 * <code>unionGentransObject</code>
1024 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1025 final String propertyName) {
1026 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1027 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1028 .addProperty(BindingMapping.getPropertyName(propertyName));
1029 propBuilder.setReturnType(type);
1031 unionGenTransObject.addEqualsIdentity(propBuilder);
1032 unionGenTransObject.addHashIdentity(propBuilder);
1033 unionGenTransObject.addToStringProperty(propBuilder);
1038 * Converts <code>typedef</code> to the generated TO builder.
1040 * @param basePackageName
1041 * string with name of package to which the module belongs
1043 * type definition from which is the generated TO builder created
1044 * @return generated TO builder which contains data from
1045 * <code>typedef</code> and <code>basePackageName</code>
1047 private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName,
1048 final TypeDefinition<?> typedef, final String moduleName) {
1050 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
1051 final String typeDefTOName = typedef.getQName().getLocalName();
1053 if ((packageName != null) && (typeDefTOName != null)) {
1054 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1055 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1057 newType.setDescription(typedef.getDescription());
1058 newType.setReference(typedef.getReference());
1059 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1060 newType.setModuleName(moduleName);
1068 * Converts <code>typeDef</code> which should be of the type
1069 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1071 * All the bits of the typeDef are added to returning generated TO as
1074 * @param basePackageName
1075 * string with name of package to which the module belongs
1077 * type definition from which is the generated TO builder created
1078 * @param typeDefName
1079 * string with the name for generated TO builder
1080 * @return generated TO builder which represents <code>typeDef</code>
1081 * @throws IllegalArgumentException
1083 * <li>if <code>typeDef</code> equals null</li>
1084 * <li>if <code>basePackageName</code> equals null</li>
1087 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1088 final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1090 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1091 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1093 if (typeDef instanceof BitsTypeDefinition) {
1094 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1096 final String typeName = BindingMapping.getClassName(typeDefName);
1097 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1099 genTOBuilder.setDescription(typeDef.getDescription());
1100 genTOBuilder.setReference(typeDef.getReference());
1101 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1102 genTOBuilder.setModuleName(moduleName);
1103 genTOBuilder.setBaseType(typeDef);
1105 final List<Bit> bitList = bitsTypeDefinition.getBits();
1106 GeneratedPropertyBuilder genPropertyBuilder;
1107 for (final Bit bit : bitList) {
1108 String name = bit.getName();
1109 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1110 genPropertyBuilder.setReadOnly(true);
1111 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1113 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1114 genTOBuilder.addHashIdentity(genPropertyBuilder);
1115 genTOBuilder.addToStringProperty(genPropertyBuilder);
1118 return genTOBuilder;
1124 * Converts the pattern constraints from <code>typedef</code> to the list of
1125 * the strings which represents these constraints.
1128 * extended type in which are the pattern constraints sought
1129 * @return list of strings which represents the constraint patterns
1130 * @throws IllegalArgumentException
1131 * if <code>typedef</code> equals null
1134 private List<String> resolveRegExpressionsFromTypedef(final ExtendedType typedef) {
1135 final List<String> regExps = new ArrayList<String>();
1136 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1137 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1138 if (strTypeDef instanceof StringType) {
1139 final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1140 if (!patternConstraints.isEmpty()) {
1142 String modifiedRegEx;
1143 for (PatternConstraint patternConstraint : patternConstraints) {
1144 regEx = patternConstraint.getRegularExpression();
1145 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1146 regExps.add(modifiedRegEx);
1155 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1156 * expressions from the <code>regularExpressions</code>
1158 * @param genTOBuilder
1159 * generated TO builder to which are
1160 * <code>regular expressions</code> added
1161 * @param regularExpressions
1162 * list of string which represent regular expressions
1163 * @throws IllegalArgumentException
1165 * <li>if <code>genTOBuilder</code> equals null</li>
1166 * <li>if <code>regularExpressions</code> equals null</li>
1169 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1170 if (genTOBuilder == null) {
1171 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1173 if (regularExpressions == null) {
1174 throw new IllegalArgumentException("List of regular expressions can't be null");
1176 if (!regularExpressions.isEmpty()) {
1177 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1178 regularExpressions);
1183 * Creates generated TO with data about inner extended type
1184 * <code>innerExtendedType</code>, about the package name
1185 * <code>typedefName</code> and about the generated TO name
1186 * <code>typedefName</code>.
1188 * It is supposed that <code>innerExtendedType</code> is already present in
1189 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1190 * be possible set it as extended type for the returning generated TO.
1194 * @param innerExtendedType
1195 * extended type which is part of some other extended type
1196 * @param basePackageName
1197 * string with the package name of the module
1200 * @return generated TO which extends generated TO for
1201 * <code>innerExtendedType</code>
1202 * @throws IllegalArgumentException
1204 * <li>if <code>extendedType</code> equals null</li>
1205 * <li>if <code>basePackageName</code> equals null</li>
1206 * <li>if <code>typedefName</code> equals null</li>
1209 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1210 final ExtendedType innerExtendedType, final String basePackageName, final String moduleName) {
1211 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1212 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1214 final String typedefName = typedef.getQName().getLocalName();
1215 final String classTypedefName = BindingMapping.getClassName(typedefName);
1216 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1217 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1219 genTOBuilder.setDescription(typedef.getDescription());
1220 genTOBuilder.setReference(typedef.getReference());
1221 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1222 genTOBuilder.setModuleName(moduleName);
1223 genTOBuilder.setTypedef(true);
1224 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1225 genTOBuilder.setRestrictions(r);
1227 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1228 genTOBuilder.setIsUnion(true);
1231 Map<Date, Map<String, Type>> modulesByDate = null;
1232 Map<String, Type> typeMap = null;
1233 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1234 if (parentModule != null) {
1235 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1236 typeMap = modulesByDate.get(parentModule.getRevision());
1239 if (typeMap != null) {
1240 Type type = typeMap.get(innerTypeDef);
1241 if (type instanceof GeneratedTransferObject) {
1242 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1245 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1246 makeSerializable(genTOBuilder);
1248 return genTOBuilder.toInstance();
1252 * Add {@link Serializable} to implemented interfaces of this TO. Also
1253 * compute and add serialVersionUID property.
1256 * transfer object which needs to be serializable
1258 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1259 gto.addImplementsType(Types.typeForClass(Serializable.class));
1260 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1261 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1266 * Finds out for each type definition how many immersion (depth) is
1267 * necessary to get to the base type. Every type definition is inserted to
1268 * the map which key is depth and value is list of type definitions with
1269 * equal depth. In next step are lists from this map concatenated to one
1270 * list in ascending order according to their depth. All type definitions
1271 * are in the list behind all type definitions on which depends.
1273 * @param unsortedTypeDefinitions
1274 * list of type definitions which should be sorted by depth
1275 * @return list of type definitions sorted according their each other
1276 * dependencies (type definitions which are depend on other type
1277 * definitions are in list behind them).
1279 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1280 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1281 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1283 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1284 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1285 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1286 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1287 if (typeDefinitionsConcreteDepth == null) {
1288 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1289 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1291 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1294 // SortedMap guarantees order corresponding to keys in ascending order
1295 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1296 sortedTypeDefinition.addAll(v);
1299 return sortedTypeDefinition;
1303 * Returns how many immersion is necessary to get from the type definition
1306 * @param typeDefinition
1307 * type definition for which is depth sought.
1308 * @return number of immersions which are necessary to get from the type
1309 * definition to the base type
1311 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1312 if (typeDefinition == null) {
1316 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1318 if (baseType instanceof ExtendedType) {
1319 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1320 } else if (baseType instanceof UnionType) {
1321 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1322 int maxChildDepth = 0;
1324 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1325 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1326 if (childDepth > maxChildDepth) {
1327 maxChildDepth = childDepth;
1330 return maxChildDepth;
1336 * Returns string which contains the same value as <code>name</code> but
1337 * integer suffix is incremented by one. If <code>name</code> contains no
1338 * number suffix then number 1 is added.
1341 * string with name of augmented node
1342 * @return string with the number suffix incremented by one (or 1 is added)
1344 private static String provideAvailableNameForGenTOBuilder(final String name) {
1345 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1347 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1348 return name.substring(0, mtch.start()) + newSuffix;
1354 public void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1355 if (units != null && !units.isEmpty()) {
1356 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1357 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1358 prop.setReturnType(Types.STRING);
1359 to.addToStringProperty(prop);
1364 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1365 return getTypeDefaultConstruction(node, node.getDefault());
1368 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1369 TypeDefinition<?> type = node.getType();
1370 QName typeQName = type.getQName();
1371 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1372 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1373 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1376 StringBuilder sb = new StringBuilder();
1377 String result = null;
1378 if (base instanceof BinaryTypeDefinition) {
1379 result = binaryToDef(defaultValue);
1380 } else if (base instanceof BitsTypeDefinition) {
1383 Module parent = getParentModule(node);
1384 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1386 if (!(path.hasNext())) {
1387 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1388 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1389 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1391 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1392 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1393 parentName = BindingMapping.getClassName(parent.getName());
1394 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1396 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1397 } else if (base instanceof BooleanTypeDefinition) {
1398 result = typeToDef(Boolean.class, defaultValue);
1399 } else if (base instanceof DecimalTypeDefinition) {
1400 result = typeToDef(BigDecimal.class, defaultValue);
1401 } else if (base instanceof EmptyTypeDefinition) {
1402 result = typeToDef(Boolean.class, defaultValue);
1403 } else if (base instanceof EnumTypeDefinition) {
1404 char[] defValArray = defaultValue.toCharArray();
1405 char first = Character.toUpperCase(defaultValue.charAt(0));
1406 defValArray[0] = first;
1407 String newDefVal = new String(defValArray);
1409 if (type instanceof ExtendedType) {
1410 Module m = getParentModule(type);
1411 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1412 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1413 className = packageName + "." + BindingMapping.getClassName(typeQName);
1415 Module parentModule = getParentModule(node);
1416 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1417 String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
1418 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1420 result = className + "." + newDefVal;
1421 } else if (base instanceof IdentityrefTypeDefinition) {
1422 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1423 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1424 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1425 } else if (base instanceof Int8) {
1426 result = typeToDef(Byte.class, defaultValue);
1427 } else if (base instanceof Int16) {
1428 result = typeToDef(Short.class, defaultValue);
1429 } else if (base instanceof Int32) {
1430 result = typeToDef(Integer.class, defaultValue);
1431 } else if (base instanceof Int64) {
1432 result = typeToDef(Long.class, defaultValue);
1433 } else if (base instanceof LeafrefTypeDefinition) {
1434 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1435 } else if (base instanceof StringTypeDefinition) {
1436 result = "\"" + defaultValue + "\"";
1437 } else if (base instanceof Uint8) {
1438 result = typeToDef(Short.class, defaultValue);
1439 } else if (base instanceof Uint16) {
1440 result = typeToDef(Integer.class, defaultValue);
1441 } else if (base instanceof Uint32) {
1442 result = typeToDef(Long.class, defaultValue);
1443 } else if (base instanceof Uint64) {
1444 result = typeToDef(BigInteger.class, defaultValue);
1445 } else if (base instanceof UnionTypeDefinition) {
1446 result = unionToDef(node);
1452 if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
1453 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
1454 Module m = getParentModule(type);
1455 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1456 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1457 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1458 sb.insert(0, "new " + className + "(");
1459 sb.insert(sb.length(), ')');
1462 return sb.toString();
1465 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1466 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1469 private static String binaryToDef(final String defaultValue) {
1470 StringBuilder sb = new StringBuilder();
1471 BaseEncoding en = BaseEncoding.base64();
1472 byte[] encoded = en.decode(defaultValue);
1473 sb.append("new byte[] {");
1474 for (int i = 0; i < encoded.length; i++) {
1475 sb.append(encoded[i]);
1476 if (i != encoded.length - 1) {
1481 return sb.toString();
1484 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1485 final boolean isExt) {
1486 List<Bit> bits = new ArrayList<>(type.getBits());
1487 Collections.sort(bits, new Comparator<Bit>() {
1489 public int compare(final Bit o1, final Bit o2) {
1490 return o1.getName().compareTo(o2.getName());
1493 StringBuilder sb = new StringBuilder();
1496 sb.append(className);
1499 for (int i = 0; i < bits.size(); i++) {
1500 if (bits.get(i).getName().equals(defaultValue)) {
1505 if (i != bits.size() - 1) {
1512 return sb.toString();
1515 private Module getParentModule(final SchemaNode node) {
1516 QName qname = node.getPath().getPathFromRoot().iterator().next();
1517 URI namespace = qname.getNamespace();
1518 Date revision = qname.getRevision();
1519 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1522 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1523 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1524 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1525 "The Path Statement for Leafref Type Definition cannot be NULL!");
1527 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1528 final String strXPath = xpath.toString();
1530 if (strXPath != null) {
1531 if (strXPath.indexOf('[') == -1) {
1532 final Module module = findParentModule(schemaContext, parentNode);
1533 if (module != null) {
1534 final SchemaNode dataNode;
1535 if (xpath.isAbsolute()) {
1536 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1538 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1540 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1544 return "new java.lang.Object()";
1551 private String unionToDef(final LeafSchemaNode node) {
1555 if (node.getType() instanceof ExtendedType) {
1556 ExtendedType type = (ExtendedType) node.getType();
1557 QName typeQName = type.getQName();
1558 Module module = null;
1559 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1560 if (modules.size() > 1) {
1561 for (Module m : modules) {
1562 if (m.getRevision().equals(typeQName.getRevision())) {
1567 if (module == null) {
1568 List<Module> modulesList = new ArrayList<>(modules);
1569 Collections.sort(modulesList, new Comparator<Module>() {
1571 public int compare(final Module o1, final Module o2) {
1572 return o1.getRevision().compareTo(o2.getRevision());
1575 module = modulesList.get(0);
1578 module = modules.iterator().next();
1581 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1582 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1584 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1585 QName first = path.next();
1586 if (!(path.hasNext())) {
1587 URI namespace = first.getNamespace();
1588 Date revision = first.getRevision();
1589 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1590 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1591 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1592 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1594 URI namespace = first.getNamespace();
1595 Date revision = first.getRevision();
1596 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1597 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1598 String packageName = packageNameForGeneratedType(basePackageName, node.getType().getPath());
1599 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1602 return union(className, node.getDefault(), node);
1605 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1606 StringBuilder sb = new StringBuilder();
1608 sb.append(className);
1610 sb.append(defaultValue);
1611 sb.append("\".toCharArray())");
1612 return sb.toString();
1616 public String getConstructorPropertyName(final SchemaNode node) {
1617 if (node instanceof TypeDefinition<?>) {
1625 public String getParamNameFromType(final TypeDefinition<?> type) {
1626 return BindingMapping.getPropertyName(type.getQName().getLocalName());