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.generator.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static com.google.common.base.Preconditions.checkState;
13 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.computeDefaultSUID;
14 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
15 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
16 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_OBJECT;
17 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_ROOT;
18 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIABLE;
19 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIER;
20 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.augmentable;
22 import static org.opendaylight.yangtools.binding.generator.util.Types.BOOLEAN;
23 import static org.opendaylight.yangtools.binding.generator.util.Types.FUTURE;
24 import static org.opendaylight.yangtools.binding.generator.util.Types.VOID;
25 import static org.opendaylight.yangtools.binding.generator.util.Types.typeForClass;
26 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
30 import com.google.common.annotations.VisibleForTesting;
31 import com.google.common.base.Optional;
32 import com.google.common.base.Preconditions;
33 import com.google.common.base.Splitter;
34 import com.google.common.base.Strings;
35 import com.google.common.collect.Iterables;
36 import com.google.common.collect.Sets;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
45 import java.util.regex.Pattern;
46 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
47 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
48 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
49 import org.opendaylight.yangtools.binding.generator.util.Types;
50 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
51 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
52 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
53 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
54 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
55 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
56 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
57 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
58 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
59 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
60 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
61 import org.opendaylight.yangtools.sal.binding.model.api.Type;
62 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
66 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
67 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
68 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
69 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
70 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
71 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
72 import org.opendaylight.yangtools.yang.binding.BindingMapping;
73 import org.opendaylight.yangtools.yang.binding.DataContainer;
74 import org.opendaylight.yangtools.yang.binding.RpcService;
75 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
76 import org.opendaylight.yangtools.yang.common.QName;
77 import org.opendaylight.yangtools.yang.common.RpcResult;
78 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
79 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
80 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
83 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
86 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.Module;
91 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
92 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
93 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
94 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
95 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
97 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
98 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.UsesNode;
100 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
102 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
104 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
105 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
106 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
107 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
108 import org.opendaylight.yangtools.yang.model.util.UnionType;
109 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
110 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
111 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
115 public class BindingGeneratorImpl implements BindingGenerator {
116 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
117 private static final Splitter COLON_SPLITTER = Splitter.on(':');
118 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
119 private static final char NEW_LINE = '\n';
122 * Constant with the concrete name of identifier.
124 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
127 * Constant with the concrete name of namespace.
129 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
131 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
133 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
136 * When set to true, generated classes will include javadoc comments which
137 * are useful for users.
139 private final boolean verboseClassComments;
142 * Outer key represents the package name. Outer value represents map of all
143 * builders in the same package. Inner key represents the schema node name
144 * (in JAVA class/interface name format). Inner value represents instance of
145 * builder for schema node specified in key part.
147 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
150 * Provide methods for converting YANG types to JAVA types.
152 private TypeProvider typeProvider;
155 * Holds reference to schema context to resolve data of augmented element
156 * when creating augmentation builder
158 private SchemaContext schemaContext;
161 * Create a new binding generator.
163 * @param verboseClassComments generate verbose comments
165 public BindingGeneratorImpl(final boolean verboseClassComments) {
166 this.verboseClassComments = verboseClassComments;
170 * Resolves generated types from <code>context</code> schema nodes of all
173 * Generated types are created for modules, groupings, types, containers,
174 * lists, choices, augments, rpcs, notification, identities.
177 * schema context which contains data about all schema nodes
179 * @return list of types (usually <code>GeneratedType</code>
180 * <code>GeneratedTransferObject</code>which are generated from
181 * <code>context</code> data.
182 * @throws IllegalArgumentException
183 * if arg <code>context</code> is null
184 * @throws IllegalStateException
185 * if <code>context</code> contain no modules
188 public List<Type> generateTypes(final SchemaContext context) {
189 checkArgument(context != null, "Schema Context reference cannot be NULL.");
190 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
191 schemaContext = context;
192 typeProvider = new TypeProviderImpl(context);
193 final Set<Module> modules = context.getModules();
194 return generateTypes(context, modules);
198 * Resolves generated types from <code>context</code> schema nodes only for
199 * modules specified in <code>modules</code>
201 * Generated types are created for modules, groupings, types, containers,
202 * lists, choices, augments, rpcs, notification, identities.
205 * schema context which contains data about all schema nodes
208 * set of modules for which schema nodes should be generated
210 * @return list of types (usually <code>GeneratedType</code> or
211 * <code>GeneratedTransferObject</code>) which:
213 * <li>are generated from <code>context</code> schema nodes and</li>
214 * <li>are also part of some of the module in <code>modules</code>
217 * @throws IllegalArgumentException
219 * <li>if arg <code>context</code> is null or</li>
220 * <li>if arg <code>modules</code> is null</li>
222 * @throws IllegalStateException
223 * if <code>context</code> contain no modules
226 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
227 checkArgument(context != null, "Schema Context reference cannot be NULL.");
228 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
229 checkArgument(modules != null, "Set of Modules cannot be NULL.");
231 schemaContext = context;
232 typeProvider = new TypeProviderImpl(context);
233 final Module[] modulesArray = new Module[context.getModules().size()];
234 context.getModules().toArray(modulesArray);
235 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
236 genTypeBuilders = new HashMap<>();
238 for (final Module contextModule : contextModules) {
239 moduleToGenTypes(contextModule, context);
241 for (final Module contextModule : contextModules) {
242 allAugmentsToGenTypes(contextModule);
245 final List<Type> filteredGenTypes = new ArrayList<>();
246 for (final Module m : modules) {
247 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
248 filteredGenTypes.addAll(ctx.getGeneratedTypes());
249 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
250 if (additionalTypes != null) {
251 filteredGenTypes.addAll(additionalTypes);
255 return filteredGenTypes;
258 private void moduleToGenTypes(final Module m, final SchemaContext context) {
259 genCtx.put(m, new ModuleContext());
260 allTypeDefinitionsToGenTypes(m);
261 groupingsToGenTypes(m, m.getGroupings());
262 rpcMethodsToGenType(m);
263 allIdentitiesToGenTypes(m, context);
264 notificationsToGenType(m);
266 if (!m.getChildNodes().isEmpty()) {
267 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
268 genCtx.get(m).addModuleNode(moduleType);
269 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
270 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
275 * Converts all extended type definitions of module to the list of
276 * <code>Type</code> objects.
279 * module from which is obtained set of type definitions
280 * @throws IllegalArgumentException
282 * <li>if module is null</li>
283 * <li>if name of module is null</li>
285 * @throws IllegalStateException
286 * if set of type definitions from module is null
288 private void allTypeDefinitionsToGenTypes(final Module module) {
289 checkArgument(module != null, "Module reference cannot be NULL.");
290 checkArgument(module.getName() != null, "Module name cannot be NULL.");
291 final DataNodeIterator it = new DataNodeIterator(module);
292 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
293 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
295 for (final TypeDefinition<?> typedef : typeDefinitions) {
296 if (typedef != null) {
297 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
300 final ModuleContext ctx = genCtx.get(module);
301 ctx.addTypedefType(typedef.getPath(), type);
302 ctx.addTypeToSchema(type,typedef);
308 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
309 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
310 if (node.isAugmenting() || node.isAddedByUses()) {
313 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
314 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
315 genType.addComment(node.getDescription());
316 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
317 genType.setModuleName(module.getName());
318 genType.setReference(node.getReference());
319 genType.setSchemaPath(node.getPath().getPathFromRoot());
320 if (node instanceof DataNodeContainer) {
321 genCtx.get(module).addChildNodeType(node, genType);
322 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
323 processUsesAugments((DataNodeContainer) node, module);
328 private void containerToGenType(final Module module, final String basePackageName,
329 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
330 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
331 if (genType != null) {
332 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType);
333 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
337 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
338 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
339 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
340 if (genType != null) {
341 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), Types.listTypeFor(genType));
343 final List<String> listKeys = listKeys(node);
344 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
345 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
346 if (genTOBuilder != null) {
347 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
348 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
349 genTOBuilder.addImplementsType(identifierMarker);
350 genType.addImplementsType(identifiableMarker);
353 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
354 if (!schemaNode.isAugmenting()) {
355 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
360 if (genTOBuilder != null) {
361 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
362 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
363 genTOBuilder.setSUID(prop);
366 typeBuildersToGenTypes(module, genType, genTOBuilder);
370 private void processUsesAugments(final DataNodeContainer node, final Module module) {
371 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
372 for (final UsesNode usesNode : node.getUses()) {
373 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
374 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
375 processUsesAugments(augment, module);
381 * Converts all <b>augmentation</b> of the module to the list
382 * <code>Type</code> objects.
385 * module from which is obtained list of all augmentation objects
386 * to iterate over them
387 * @throws IllegalArgumentException
389 * <li>if the module is null</li>
390 * <li>if the name of module is null</li>
392 * @throws IllegalStateException
393 * if set of augmentations from module is null
395 private void allAugmentsToGenTypes(final Module module) {
396 checkArgument(module != null, "Module reference cannot be NULL.");
397 checkArgument(module.getName() != null, "Module name cannot be NULL.");
398 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
400 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
401 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
402 for (final AugmentationSchema augment : augmentations) {
403 augmentationToGenTypes(basePackageName, augment, module);
408 * Returns list of <code>AugmentationSchema</code> objects. The objects are
409 * sorted according to the length of their target path from the shortest to
413 * module from which is obtained list of all augmentation objects
414 * @return list of sorted <code>AugmentationSchema</code> objects obtained
415 * from <code>module</code>
416 * @throws IllegalArgumentException
418 * @throws IllegalStateException
419 * if set of module augmentations is null
421 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
422 checkArgument(module != null, "Module reference cannot be NULL.");
423 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
425 final Set<AugmentationSchema> augmentations = module.getAugmentations();
426 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
427 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
429 return sortedAugmentations;
433 * Create GeneratedTypeBuilder object from module argument.
436 * Module object from which builder will be created
437 * @return <code>GeneratedTypeBuilder</code> which is internal
438 * representation of the module
439 * @throws IllegalArgumentException
442 private GeneratedTypeBuilder moduleToDataType(final Module module) {
443 checkArgument(module != null, "Module reference cannot be NULL.");
445 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
446 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
447 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
448 moduleDataTypeBuilder.addComment(module.getDescription());
449 moduleDataTypeBuilder.setDescription(createDescription(module));
450 moduleDataTypeBuilder.setReference(module.getReference());
451 return moduleDataTypeBuilder;
455 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
456 * to the list of <code>Type</code> objects. In addition are to containers
457 * and lists which belong to input or output also part of returning list.
460 * module from which is obtained set of all rpc objects to
462 * @throws IllegalArgumentException
464 * <li>if the module is null</li>
465 * <li>if the name of module is null</li>
467 * @throws IllegalStateException
468 * if set of rpcs from module is null
470 private void rpcMethodsToGenType(final Module module) {
471 checkArgument(module != null, "Module reference cannot be NULL.");
472 checkArgument(module.getName() != null, "Module name cannot be NULL.");
473 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
474 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
475 if (rpcDefinitions.isEmpty()) {
479 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
480 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
481 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
482 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
484 for (final RpcDefinition rpc : rpcDefinitions) {
486 final String rpcName = BindingMapping.getClassName(rpc.getQName());
487 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
488 final String rpcComment = rpc.getDescription();
489 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
490 final ContainerSchemaNode input = rpc.getInput();
491 final ContainerSchemaNode output = rpc.getOutput();
494 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
495 addImplementedInterfaceFromUses(input, inType);
496 inType.addImplementsType(DATA_OBJECT);
497 inType.addImplementsType(augmentable(inType));
498 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
499 genCtx.get(module).addChildNodeType(input, inType);
500 final GeneratedType inTypeInstance = inType.toInstance();
501 method.addParameter(inTypeInstance, "input");
504 Type outTypeInstance = VOID;
505 if (output != null) {
506 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
507 addImplementedInterfaceFromUses(output, outType);
508 outType.addImplementsType(DATA_OBJECT);
509 outType.addImplementsType(augmentable(outType));
510 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
511 genCtx.get(module).addChildNodeType(output, outType);
512 outTypeInstance = outType.toInstance();
515 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
516 method.setComment(rpcComment);
517 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
521 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
525 * Converts all <b>notifications</b> of the module to the list of
526 * <code>Type</code> objects. In addition are to this list added containers
527 * and lists which are part of this notification.
530 * module from which is obtained set of all notification objects
531 * to iterate over them
532 * @throws IllegalArgumentException
534 * <li>if the module equals null</li>
535 * <li>if the name of module equals null</li>
537 * @throws IllegalStateException
538 * if set of notifications from module is null
540 private void notificationsToGenType(final Module module) {
541 checkArgument(module != null, "Module reference cannot be NULL.");
542 checkArgument(module.getName() != null, "Module name cannot be NULL.");
543 final Set<NotificationDefinition> notifications = module.getNotifications();
544 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
545 if (notifications.isEmpty()) {
549 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
550 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
551 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
555 for (final NotificationDefinition notification : notifications) {
556 if (notification != null) {
557 processUsesAugments(notification, module);
559 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
560 notification, null, module);
561 notificationInterface.addImplementsType(NOTIFICATION);
562 genCtx.get(module).addChildNodeType(notification, notificationInterface);
564 // Notification object
565 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
566 notification.getChildNodes());
568 listenerInterface.addMethod("on" + notificationInterface.getName())
569 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
570 .setComment(notification.getDescription()).setReturnType(Types.VOID);
573 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
575 genCtx.get(module).addTopLevelNodeType(listenerInterface);
579 * Converts all <b>identities</b> of the module to the list of
580 * <code>Type</code> objects.
583 * module from which is obtained set of all identity objects to
586 * schema context only used as input parameter for method
587 * {@link identityToGenType}
590 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
591 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
592 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
594 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
595 for (final IdentitySchemaNode identity : schemaIdentities) {
596 identityToGenType(module, basePackageName, identity, context);
602 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
603 * created transport object builder. If identity contains base identity then
604 * reference to base identity is added to superior identity as its extend.
605 * If identity doesn't contain base identity then only reference to abstract
606 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
607 * BaseIdentity} is added
611 * @param basePackageName
612 * string contains the module package name
614 * IdentitySchemaNode which contains data about identity
616 * SchemaContext which is used to get package and name
617 * information about base of identity
620 private void identityToGenType(final Module module, final String basePackageName,
621 final IdentitySchemaNode identity, final SchemaContext context) {
622 if (identity == null) {
625 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
626 final String genTypeName = BindingMapping.getClassName(identity.getQName());
627 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
628 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
629 if (baseIdentity == null) {
630 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
631 BaseIdentity.class.getSimpleName());
632 newType.setExtendsType(gto.toInstance());
634 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
635 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
637 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
638 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
640 newType.setExtendsType(gto);
642 newType.setAbstract(true);
643 newType.addComment(identity.getDescription());
644 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
645 newType.setReference(identity.getReference());
646 newType.setModuleName(module.getName());
647 newType.setSchemaPath(identity.getPath().getPathFromRoot());
649 final QName qname = identity.getQName();
650 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
652 genCtx.get(module).addIdentityType(identity.getQName(), newType);
655 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
657 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
661 * Converts all <b>groupings</b> of the module to the list of
662 * <code>Type</code> objects. Firstly are groupings sorted according mutual
663 * dependencies. At least dependent (independent) groupings are in the list
664 * saved at first positions. For every grouping the record is added to map
665 * {@link BindingGeneratorImpl#allGroupings allGroupings}
670 * of groupings from which types will be generated
673 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
674 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
675 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
677 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
678 groupingToGenType(basePackageName, grouping, module);
683 * Converts individual grouping to GeneratedType. Firstly generated type
684 * builder is created and every child node of grouping is resolved to the
687 * @param basePackageName
688 * string contains the module package name
690 * GroupingDefinition which contains data about grouping
693 * @return GeneratedType which is generated from grouping (object of type
694 * <code>GroupingDefinition</code>)
696 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
697 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
698 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
699 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
700 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
701 groupingsToGenTypes(module, grouping.getGroupings());
702 processUsesAugments(grouping, module);
706 * Adds enumeration builder created from <code>enumTypeDef</code> to
707 * <code>typeBuilder</code>.
709 * Each <code>enumTypeDef</code> item is added to builder with its name and
713 * EnumTypeDefinition contains enum data
715 * string contains name which will be assigned to enumeration
718 * GeneratedTypeBuilder to which will be enum builder assigned
720 * Module in which type should be generated
721 * @return enumeration builder which contains data from
722 * <code>enumTypeDef</code>
724 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
725 final GeneratedTypeBuilder typeBuilder, final Module module) {
726 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
727 && (enumTypeDef.getQName().getLocalName() != null)) {
728 final String enumerationName = BindingMapping.getClassName(enumName);
729 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
730 enumBuilder.setDescription(enumTypeDef.getDescription());
731 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
732 ModuleContext ctx = genCtx.get(module);
733 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
740 * Generates type builder for <code>module</code>.
743 * Module which is source of package name for generated type
746 * string which is added to the module class name representation
748 * @return instance of GeneratedTypeBuilder which represents
749 * <code>module</code>.
750 * @throws IllegalArgumentException
751 * if <code>module</code> is null
753 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
754 checkArgument(module != null, "Module reference cannot be NULL.");
755 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
756 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
758 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
759 moduleBuilder.setDescription(createDescription(module));
760 moduleBuilder.setReference(module.getReference());
761 moduleBuilder.setModuleName(moduleName);
763 return moduleBuilder;
767 * Converts <code>augSchema</code> to list of <code>Type</code> which
768 * contains generated type for augmentation. In addition there are also
769 * generated types for all containers, list and choices which are child of
770 * <code>augSchema</code> node or a generated types for cases are added if
771 * augmented node is choice.
773 * @param augmentPackageName
774 * string with the name of the package to which the augmentation
777 * AugmentationSchema which is contains data about augmentation
778 * (target path, childs...)
781 * @param parentUsesNode
782 * @throws IllegalArgumentException
784 * <li>if <code>augmentPackageName</code> equals null</li>
785 * <li>if <code>augSchema</code> equals null</li>
787 * @throws IllegalStateException
788 * if augment target path is null
790 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
791 final Module module) {
792 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
793 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
794 checkState(augSchema.getTargetPath() != null,
795 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
797 processUsesAugments(augSchema, module);
798 final SchemaPath targetPath = augSchema.getTargetPath();
799 SchemaNode targetSchemaNode = null;
801 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
802 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
803 if (targetSchemaNode instanceof DerivableSchemaNode) {
804 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
806 if (targetSchemaNode == null) {
807 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
808 + " in module " + module.getName());
811 if (targetSchemaNode == null) {
812 throw new IllegalArgumentException("augment target not found: " + targetPath);
815 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
816 if (targetTypeBuilder == null) {
817 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
819 if (targetTypeBuilder == null) {
820 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
823 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
824 final String packageName = augmentPackageName;
825 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
826 targetTypeBuilder.getName());
827 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
830 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
831 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
835 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
836 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
837 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
838 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
839 checkState(augSchema.getTargetPath() != null,
840 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
842 processUsesAugments(augSchema, module);
843 final SchemaPath targetPath = augSchema.getTargetPath();
844 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
845 if (targetSchemaNode == null) {
846 throw new IllegalArgumentException("augment target not found: " + targetPath);
849 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
850 if (targetTypeBuilder == null) {
851 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
853 if (targetTypeBuilder == null) {
854 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
857 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
858 String packageName = augmentPackageName;
859 if (usesNodeParent instanceof SchemaNode) {
860 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
862 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
865 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
866 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
871 * Convenient method to find node added by uses statement.
875 * @param parentUsesNode
876 * parent of uses node
877 * @return node from its original location in grouping
879 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
880 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
882 if (!(targetGrouping instanceof GroupingDefinition)) {
883 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
886 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
887 SchemaNode result = grouping;
888 for (final QName node : targetPath.getPathFromRoot()) {
889 // finding by local name is valid, grouping cannot contain nodes
890 // with same name and different namespace
891 if (result instanceof DataNodeContainer) {
892 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
893 } else if (result instanceof ChoiceSchemaNode) {
894 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
897 if (result == null) {
901 if (result instanceof DerivableSchemaNode) {
902 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
903 Optional<? extends SchemaNode> originalNode = castedResult
905 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
906 result = originalNode.get();
910 if (result instanceof DataSchemaNode) {
911 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
912 if (resultDataSchemaNode.isAddedByUses()) {
913 // The original node is required, but we have only the copy of
914 // the original node.
915 // Maybe this indicates a bug in Yang parser.
916 throw new IllegalStateException(
917 "Failed to generate code for augment in "
920 return resultDataSchemaNode;
923 throw new IllegalStateException(
924 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
930 * Returns a generated type builder for an augmentation.
932 * The name of the type builder is equal to the name of augmented node with
933 * serial number as suffix.
937 * @param augmentPackageName
938 * string with contains the package name to which the augment
940 * @param basePackageName
941 * string with the package name to which the augmented node
943 * @param targetTypeRef
946 * augmentation schema which contains data about the child nodes
947 * and uses of augment
948 * @return generated type builder for augment
950 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
951 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
952 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
953 if (augmentBuilders == null) {
954 augmentBuilders = new HashMap<>();
955 genTypeBuilders.put(augmentPackageName, augmentBuilders);
957 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
960 if (augIdentifier != null) {
961 augTypeName = BindingMapping.getClassName(augIdentifier);
963 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
966 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
968 augTypeBuilder.addImplementsType(DATA_OBJECT);
969 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
970 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
972 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
973 augmentBuilders.put(augTypeName, augTypeBuilder);
975 if(!augSchema.getChildNodes().isEmpty()) {
976 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
977 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
980 genCtx.get(module).addAugmentType(augTypeBuilder);
981 return augTypeBuilder;
986 * @param unknownSchemaNodes
987 * @return nodeParameter of UnknownSchemaNode
989 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
990 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
991 final QName nodeType = unknownSchemaNode.getNodeType();
992 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
993 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
994 return unknownSchemaNode.getNodeParameter();
1001 * Returns first unique name for the augment generated type builder. The
1002 * generated type builder name for augment consists from name of augmented
1003 * node and serial number of its augmentation.
1006 * map of builders which were created in the package to which the
1007 * augmentation belongs
1008 * @param genTypeName
1009 * string with name of augmented node
1010 * @return string with unique name for augmentation builder
1012 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1014 if (builders != null) {
1015 while (builders.containsKey(genTypeName + index)) {
1019 return genTypeName + index;
1023 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1024 * node for which <code>typeBuilder</code> was created.
1026 * The subnodes aren't mapped to the methods if they are part of grouping or
1027 * augment (in this case are already part of them).
1031 * @param basePackageName
1032 * string contains the module package name
1034 * generated type builder which represents any node. The subnodes
1035 * of this node are added to the <code>typeBuilder</code> as
1036 * methods. The subnode can be of type leaf, leaf-list, list,
1037 * container, choice.
1040 * @param schemaNodes
1041 * set of data schema nodes which are the children of the node
1042 * for which <code>typeBuilder</code> was created
1043 * @return generated type builder which is the same builder as input
1044 * parameter. The getter methods (representing child nodes) could be
1047 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1048 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1049 if (schemaNodes != null && parent != null) {
1050 for (final DataSchemaNode schemaNode : schemaNodes) {
1051 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1052 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1060 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1061 * node for which <code>typeBuilder</code> was created.
1065 * @param basePackageName
1066 * string contains the module package name
1067 * @param typeBuilder
1068 * generated type builder which represents any node. The subnodes
1069 * of this node are added to the <code>typeBuilder</code> as
1070 * methods. The subnode can be of type leaf, leaf-list, list,
1071 * container, choice.
1074 * @param schemaNodes
1075 * set of data schema nodes which are the children of the node
1076 * for which <code>typeBuilder</code> was created
1077 * @return generated type builder which is the same object as the input
1078 * parameter <code>typeBuilder</code>. The getter method could be
1081 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1082 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1083 final Iterable<DataSchemaNode> schemaNodes) {
1084 if ((schemaNodes != null) && (typeBuilder != null)) {
1085 for (final DataSchemaNode schemaNode : schemaNodes) {
1086 if (!schemaNode.isAugmenting()) {
1087 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1095 * Adds to <code>typeBuilder</code> a method which is derived from
1096 * <code>schemaNode</code>.
1098 * @param basePackageName
1099 * string with the module package name
1101 * data schema node which is added to <code>typeBuilder</code> as
1103 * @param typeBuilder
1104 * generated type builder to which is <code>schemaNode</code>
1105 * added as a method.
1111 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1112 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1113 if (node != null && typeBuilder != null) {
1114 if (node instanceof LeafSchemaNode) {
1115 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1116 } else if (node instanceof LeafListSchemaNode) {
1117 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1118 } else if (node instanceof ContainerSchemaNode) {
1119 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1120 } else if (node instanceof ListSchemaNode) {
1121 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1122 } else if (node instanceof ChoiceSchemaNode) {
1123 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1125 // TODO: anyxml not yet supported
1126 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1127 typeBuilder.getFullyQualifiedName());
1133 * Converts <code>choiceNode</code> to the list of generated types for
1134 * choice and its cases.
1136 * The package names for choice and for its cases are created as
1137 * concatenation of the module package (<code>basePackageName</code>) and
1138 * names of all parents node.
1142 * @param basePackageName
1143 * string with the module package name
1147 * choice node which is mapped to generated type. Also child
1148 * nodes - cases are mapped to generated types.
1149 * @throws IllegalArgumentException
1151 * <li>if <code>basePackageName</code> is null</li>
1152 * <li>if <code>choiceNode</code> is null</li>
1155 private void choiceToGeneratedType(final Module module, final String basePackageName,
1156 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1157 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1158 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1160 if (!choiceNode.isAddedByUses()) {
1161 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1162 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1163 constructGetter(parent, choiceNode.getQName().getLocalName(), choiceNode.getDescription(),
1165 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1166 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1167 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1172 * Converts <code>caseNodes</code> set to list of corresponding generated
1175 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1176 * created generated type builder. The package names for the builder is
1177 * created as concatenation of the module package (
1178 * <code>basePackageName</code>) and names of all parents nodes of the
1179 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1180 * between every case builder and <i>choice</i> type
1184 * @param basePackageName
1185 * string with the module package name
1186 * @param refChoiceType
1187 * type which represents superior <i>case</i>
1189 * choice case node which is mapped to generated type
1190 * @return list of generated types for <code>caseNodes</code>.
1191 * @throws IllegalArgumentException
1193 * <li>if <code>basePackageName</code> equals null</li>
1194 * <li>if <code>refChoiceType</code> equals null</li>
1195 * <li>if <code>caseNodes</code> equals null</li>
1198 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1199 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1200 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1201 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1202 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1204 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1205 if (caseNodes == null) {
1209 for (final ChoiceCaseNode caseNode : caseNodes) {
1210 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1211 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1212 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1213 caseTypeBuilder.addImplementsType(refChoiceType);
1214 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1215 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1216 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1217 if (caseChildNodes != null) {
1218 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1220 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1221 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1223 if (parent instanceof AugmentationSchema) {
1224 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1225 final SchemaPath targetPath = augSchema.getTargetPath();
1226 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1227 if (targetSchemaNode instanceof DataSchemaNode
1228 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1229 if (targetSchemaNode instanceof DerivableSchemaNode) {
1230 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1232 if (targetSchemaNode == null) {
1233 throw new IllegalStateException(
1234 "Failed to find target node from grouping for augmentation " + augSchema
1235 + " in module " + module.getName());
1238 parent = targetSchemaNode;
1241 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1242 choiceNodeParentPath);
1243 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1244 if (childOfType == null) {
1245 childOfType = findGroupingByPath(parent.getPath());
1247 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1249 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1254 processUsesAugments(caseNode, module);
1259 * Generates list of generated types for all the cases of a choice which are
1260 * added to the choice through the augment.
1264 * @param basePackageName
1265 * string contains name of package to which augment belongs. If
1266 * an augmented choice is from an other package (pcg1) than an
1267 * augmenting choice (pcg2) then case's of the augmenting choice
1268 * will belong to pcg2.
1270 * Type which represents target choice
1272 * node which represents target choice
1273 * @param augmentedNodes
1274 * set of choice case nodes for which is checked if are/aren't
1275 * added to choice through augmentation
1276 * @return list of generated types which represents augmented cases of
1277 * choice <code>refChoiceType</code>
1278 * @throws IllegalArgumentException
1280 * <li>if <code>basePackageName</code> is null</li>
1281 * <li>if <code>targetType</code> is null</li>
1282 * <li>if <code>augmentedNodes</code> is null</li>
1285 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1286 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
1287 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1288 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1289 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1291 for (final DataSchemaNode caseNode : augmentedNodes) {
1292 if (caseNode != null) {
1293 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1294 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1295 caseTypeBuilder.addImplementsType(targetType);
1297 SchemaNode parent = null;
1298 final SchemaPath nodeSp = targetNode.getPath();
1299 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1301 GeneratedTypeBuilder childOfType = null;
1302 if (parent instanceof Module) {
1303 childOfType = genCtx.get(parent).getModuleNode();
1304 } else if (parent instanceof ChoiceCaseNode) {
1305 childOfType = findCaseByPath(parent.getPath());
1306 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1307 childOfType = findChildNodeByPath(parent.getPath());
1308 } else if (parent instanceof GroupingDefinition) {
1309 childOfType = findGroupingByPath(parent.getPath());
1312 if (childOfType == null) {
1313 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1316 ChoiceCaseNode node = null;
1317 if (caseNode instanceof ChoiceCaseNode) {
1318 node = (ChoiceCaseNode) caseNode;
1320 node = targetNode.getCaseNodeByName(caseNode.getQName().getLocalName());
1322 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1323 if (childNodes != null) {
1324 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1326 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1327 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1332 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1333 // Deal with old parser, clearing out references to typedefs
1334 if (type instanceof ExtendedType) {
1338 // New parser with encapsulated type
1339 if (leaf.getPath().equals(type.getPath())) {
1343 // Embedded type definition with new parser. Also takes care of the old parser with bits
1344 if (leaf.getPath().equals(type.getPath().getParent())) {
1348 // Old parser uses broken Union type, which does not change its schema path
1349 if (type instanceof UnionType) {
1357 * Converts <code>leaf</code> to the getter method which is added to
1358 * <code>typeBuilder</code>.
1360 * @param typeBuilder
1361 * generated type builder to which is added getter method as
1362 * <code>leaf</code> mapping
1364 * leaf schema node which is mapped as getter method which is
1365 * added to <code>typeBuilder</code>
1367 * Module in which type was defined
1368 * @return boolean value
1370 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1372 * <li>true - in other cases</li>
1375 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1376 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1380 final String leafName = leaf.getQName().getLocalName();
1381 if (leafName == null) {
1385 final Module parentModule = findParentModule(schemaContext, leaf);
1386 Type returnType = null;
1388 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1389 if (isInnerType(leaf, typeDef)) {
1390 if (typeDef instanceof EnumTypeDefinition) {
1391 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1392 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1393 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1394 typeBuilder, module);
1396 if (enumBuilder != null) {
1397 returnType = enumBuilder.toInstance(typeBuilder);
1399 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1400 } else if (typeDef instanceof UnionTypeDefinition) {
1401 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1402 if (genTOBuilder != null) {
1403 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1405 } else if (typeDef instanceof BitsTypeDefinition) {
1406 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1407 if (genTOBuilder != null) {
1408 returnType = genTOBuilder.toInstance();
1411 // It is constrained version of already declared type (inner declared type exists,
1412 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1413 // In order to get proper class we need to look up closest derived type
1414 // and apply restrictions from leaf type
1415 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1416 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1420 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1421 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1424 if (returnType == null) {
1428 String leafDesc = leaf.getDescription();
1429 if (leafDesc == null) {
1433 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1434 processContextRefExtension(leaf, getter, parentModule);
1438 private static TypeDefinition<?> getBaseOrDeclaredType(TypeDefinition<?> typeDef) {
1439 if (typeDef instanceof ExtendedType) {
1440 // Legacy behaviour returning ExtendedType is enough
1443 // Returns DerivedType in case of new parser.
1444 final TypeDefinition<?> baseType = typeDef.getBaseType();
1445 return (baseType != null && baseType.getBaseType() != null) ? baseType : typeDef;
1448 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1449 final Module module) {
1450 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1451 final QName nodeType = node.getNodeType();
1452 if ("context-reference".equals(nodeType.getLocalName())) {
1453 final String nodeParam = node.getNodeParameter();
1454 IdentitySchemaNode identity = null;
1455 String basePackageName = null;
1456 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1457 final Iterator<String> iterator = splittedElement.iterator();
1458 final int length = Iterables.size(splittedElement);
1460 identity = findIdentityByName(module.getIdentities(), iterator.next());
1461 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1462 } else if (length == 2) {
1463 final String prefix = iterator.next();
1464 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1465 if (dependentModule == null) {
1466 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1469 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1470 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1472 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1475 if (identity == null) {
1476 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1480 final Class<RoutingContext> clazz = RoutingContext.class;
1481 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1482 clazz.getSimpleName());
1483 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1484 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1485 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1490 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1491 for (final IdentitySchemaNode id : identities) {
1492 if (id.getQName().getLocalName().equals(name)) {
1499 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1500 for (final ModuleImport imp : imports) {
1501 if (imp.getPrefix().equals(prefix)) {
1502 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1508 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1509 final boolean isReadOnly, final Module module) {
1510 if ((leaf != null) && (toBuilder != null)) {
1511 String leafDesc = leaf.getDescription();
1512 if (leafDesc == null) {
1515 Type returnType = null;
1516 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1517 if (typeDef instanceof UnionTypeDefinition) {
1518 // GeneratedType for this type definition should be already
1520 final QName qname = typeDef.getQName();
1521 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1522 qname.getRevision());
1523 final ModuleContext mc = genCtx.get(unionModule);
1524 returnType = mc.getTypedefs().get(typeDef.getPath());
1525 } else if (typeDef instanceof EnumTypeDefinition && BaseTypes.ENUMERATION_QNAME.equals(typeDef.getQName())) {
1526 // Annonymous enumeration (already generated, since it is inherited via uses).
1527 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1528 QName qname = originalLeaf.getQName();
1529 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1530 qname.getRevision());
1531 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1533 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1535 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1541 * Converts <code>leaf</code> schema node to property of generated TO
1545 * generated TO builder to which is <code>leaf</code> added as
1548 * leaf schema node which is added to <code>toBuilder</code> as
1553 * boolean value which says if leaf property is|isn't read only
1554 * @return boolean value
1556 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1557 * name equals null or if leaf is added by <i>uses</i>.</li>
1558 * <li>true - other cases</li>
1561 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1562 final Type returnType, final boolean isReadOnly) {
1563 if (returnType == null) {
1566 final String leafName = leaf.getQName().getLocalName();
1567 final String leafDesc = leaf.getDescription();
1568 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1569 propBuilder.setReadOnly(isReadOnly);
1570 propBuilder.setReturnType(returnType);
1571 propBuilder.setComment(leafDesc);
1572 toBuilder.addEqualsIdentity(propBuilder);
1573 toBuilder.addHashIdentity(propBuilder);
1574 toBuilder.addToStringProperty(propBuilder);
1579 * Converts <code>node</code> leaf list schema node to getter method of
1580 * <code>typeBuilder</code>.
1582 * @param typeBuilder
1583 * generated type builder to which is <code>node</code> added as
1586 * leaf list schema node which is added to
1587 * <code>typeBuilder</code> as getter method
1589 * @return boolean value
1591 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1592 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1593 * <li>false - other cases</li>
1596 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1597 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1601 final QName nodeName = node.getQName();
1602 if (nodeName == null) {
1606 final TypeDefinition<?> typeDef = node.getType();
1607 final Module parentModule = findParentModule(schemaContext, node);
1609 Type returnType = null;
1610 if (typeDef.getBaseType() == null) {
1611 if (typeDef instanceof EnumTypeDefinition) {
1612 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1613 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1614 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1615 typeBuilder,module);
1616 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1617 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1618 } else if (typeDef instanceof UnionTypeDefinition) {
1619 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1620 if (genTOBuilder != null) {
1621 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1623 } else if (typeDef instanceof BitsTypeDefinition) {
1624 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1625 returnType = genTOBuilder.toInstance();
1627 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1628 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1631 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1632 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1635 final ParameterizedType listType = Types.listTypeFor(returnType);
1636 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1640 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1641 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1642 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1643 genTOBuilder.getName());
1645 returnType.setDescription(typeDef.getDescription());
1646 returnType.setReference(typeDef.getReference());
1647 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1648 returnType.setModuleName(parentModule.getName());
1650 genTOBuilder.setTypedef(true);
1651 genTOBuilder.setIsUnion(true);
1652 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1656 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1659 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1660 method.setReturnType(returnType);
1661 method.addParameter(Types.STRING, "defaultValue");
1662 method.setAccessModifier(AccessModifier.PUBLIC);
1663 method.setStatic(true);
1665 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1666 if (types == null) {
1667 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1668 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1670 types.add(unionBuilder.toInstance());
1672 return returnType.toInstance();
1675 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1676 final String outerCls = Types.getOuterClassName(genTOBuilder);
1677 final StringBuilder name;
1678 if (outerCls != null) {
1679 name = new StringBuilder(outerCls);
1681 name = new StringBuilder();
1683 name.append(genTOBuilder.getName());
1684 name.append("Builder");
1685 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1686 unionBuilder.setIsUnionBuilder(true);
1687 return unionBuilder;
1690 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1691 final Module module) {
1692 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1696 * Instantiates generated type builder with <code>packageName</code> and
1697 * <code>schemaNode</code>.
1699 * The new builder always implements
1700 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1701 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1702 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1704 * If <code>schemaNode</code> is instance of
1705 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1706 * DataNodeContainer} it can also implement nodes which are specified in
1709 * @param packageName
1710 * string with the name of the package to which
1711 * <code>schemaNode</code> belongs.
1713 * schema node for which is created generated type builder
1715 * parent type (can be null)
1716 * @return generated type builder <code>schemaNode</code>
1718 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1719 final Type parent, final Module module) {
1720 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1721 if (parent == null) {
1722 it.addImplementsType(DATA_OBJECT);
1724 it.addImplementsType(BindingTypes.childOf(parent));
1726 if (!(schemaNode instanceof GroupingDefinition)) {
1727 it.addImplementsType(augmentable(it));
1730 if (schemaNode instanceof DataNodeContainer) {
1731 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1732 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1739 * Wraps the calling of the same overloaded method.
1741 * @param packageName
1742 * string with the package name to which returning generated type
1745 * schema node which provide data about the schema node name
1746 * @return generated type builder for <code>schemaNode</code>
1748 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1749 return addRawInterfaceDefinition(packageName, schemaNode, "");
1753 * Returns reference to generated type builder for specified
1754 * <code>schemaNode</code> with <code>packageName</code>.
1756 * Firstly the generated type builder is searched in
1757 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1758 * found it is created and added to <code>genTypeBuilders</code>.
1760 * @param packageName
1761 * string with the package name to which returning generated type
1764 * schema node which provide data about the schema node name
1766 * return type name prefix
1767 * @return generated type builder for <code>schemaNode</code>
1768 * @throws IllegalArgumentException
1770 * <li>if <code>schemaNode</code> is null</li>
1771 * <li>if <code>packageName</code> is null</li>
1772 * <li>if QName of schema node is null</li>
1773 * <li>if schemaNode name is null</li>
1777 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1778 final String prefix) {
1779 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1780 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1781 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1782 final String schemaNodeName = schemaNode.getQName().getLocalName();
1783 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1786 if (prefix == null) {
1787 genTypeName = BindingMapping.getClassName(schemaNodeName);
1789 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1792 // FIXME: Validation of name conflict
1793 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1794 final Module module = findParentModule(schemaContext, schemaNode);
1795 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1796 newType.addComment(schemaNode.getDescription());
1797 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1798 newType.setReference(schemaNode.getReference());
1799 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1800 newType.setModuleName(module.getName());
1802 if (!genTypeBuilders.containsKey(packageName)) {
1803 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1804 builders.put(genTypeName, newType);
1805 genTypeBuilders.put(packageName, builders);
1807 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1808 if (!builders.containsKey(genTypeName)) {
1809 builders.put(genTypeName, newType);
1816 * Creates the name of the getter method name from <code>localName</code>.
1819 * string with the name of the getter method
1822 * @return string with the name of the getter method for
1823 * <code>methodName</code> in JAVA method format
1825 public static String getterMethodName(final String localName, final Type returnType) {
1826 final StringBuilder method = new StringBuilder();
1827 if (BOOLEAN.equals(returnType)) {
1828 method.append("is");
1830 method.append("get");
1832 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1833 method.append(name);
1834 return method.toString();
1838 * Created a method signature builder as part of
1839 * <code>interfaceBuilder</code>.
1841 * The method signature builder is created for the getter method of
1842 * <code>schemaNodeName</code>. Also <code>comment</code> and
1843 * <code>returnType</code> information are added to the builder.
1845 * @param interfaceBuilder
1846 * generated type builder for which the getter method should be
1848 * @param schemaNodeName
1849 * string with schema node name. The name will be the part of the
1850 * getter method name.
1852 * string with comment for the getter method
1854 * type which represents the return type of the getter method
1855 * @return method signature builder which represents the getter method of
1856 * <code>interfaceBuilder</code>
1858 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1859 final String schemaNodeName, final String comment, final Type returnType) {
1860 final MethodSignatureBuilder getMethod = interfaceBuilder
1861 .addMethod(getterMethodName(schemaNodeName, returnType));
1862 getMethod.setComment(comment);
1863 getMethod.setReturnType(returnType);
1868 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1869 * or to <code>genTOBuilder</code> as property.
1871 * @param basePackageName
1872 * string contains the module package name
1874 * data schema node which should be added as getter method to
1875 * <code>typeBuilder</code> or as a property to
1876 * <code>genTOBuilder</code> if is part of the list key
1877 * @param typeBuilder
1878 * generated type builder for the list schema node
1879 * @param genTOBuilder
1880 * generated TO builder for the list keys
1882 * list of string which contains names of the list keys
1885 * @throws IllegalArgumentException
1887 * <li>if <code>schemaNode</code> equals null</li>
1888 * <li>if <code>typeBuilder</code> equals null</li>
1891 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1892 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1893 final Module module) {
1894 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1895 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1897 if (schemaNode instanceof LeafSchemaNode) {
1898 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1899 final String leafName = leaf.getQName().getLocalName();
1900 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1901 if (listKeys.contains(leafName)) {
1903 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1905 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1908 } else if (!schemaNode.isAddedByUses()) {
1909 if (schemaNode instanceof LeafListSchemaNode) {
1910 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1911 } else if (schemaNode instanceof ContainerSchemaNode) {
1912 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1913 } else if (schemaNode instanceof ChoiceSchemaNode) {
1914 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1915 } else if (schemaNode instanceof ListSchemaNode) {
1916 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1921 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1922 final GeneratedTOBuilder genTOBuilder) {
1923 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1925 if (genTOBuilder != null) {
1926 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1927 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
1928 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1933 * Selects the names of the list keys from <code>list</code> and returns
1934 * them as the list of the strings
1937 * of string with names of the list keys
1938 * @return list of string which represents names of the list keys. If the
1939 * <code>list</code> contains no keys then the empty list is
1942 private static List<String> listKeys(final ListSchemaNode list) {
1943 final List<String> listKeys = new ArrayList<>();
1945 final List<QName> keyDefinition = list.getKeyDefinition();
1946 if (keyDefinition != null) {
1947 for (final QName keyDef : keyDefinition) {
1948 listKeys.add(keyDef.getLocalName());
1955 * Generates for the <code>list</code> which contains any list keys special
1956 * generated TO builder.
1958 * @param packageName
1959 * string with package name to which the list belongs
1961 * list schema node which is source of data about the list name
1962 * @return generated TO builder which represents the keys of the
1963 * <code>list</code> or null if <code>list</code> is null or list of
1964 * key definitions is null or empty.
1966 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1967 GeneratedTOBuilder genTOBuilder = null;
1968 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1969 final String listName = list.getQName().getLocalName() + "Key";
1970 final String genTOName = BindingMapping.getClassName(listName);
1971 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1973 return genTOBuilder;
1977 * Builds generated TO builders for <code>typeDef</code> of type
1978 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
1979 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
1980 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
1981 * enclosing transfer object.
1983 * If more then one generated TO builder is created for enclosing then all
1984 * of the generated TO builders are added to <code>typeBuilder</code> as
1985 * enclosing transfer objects.
1988 * type definition which can be of type <code>UnionType</code> or
1989 * <code>BitsTypeDefinition</code>
1990 * @param typeBuilder
1991 * generated type builder to which is added generated TO created
1992 * from <code>typeDef</code>
1994 * string with name for generated TO builder
1996 * @return generated TO builder for <code>typeDef</code>
1998 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
1999 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2000 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2001 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2002 final String packageName = typeBuilder.getFullyQualifiedName();
2003 if (typeDef instanceof UnionTypeDefinition) {
2004 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2005 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
2006 classNameFromLeaf, leaf);
2007 genTOBuilders.addAll(types);
2009 GeneratedTOBuilder resultTOBuilder = null;
2010 if (types.isEmpty()) {
2011 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2013 resultTOBuilder = types.remove(0);
2014 for (final GeneratedTOBuilder genTOBuilder : types) {
2015 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2018 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2019 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2020 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2021 resultTOBuilder.addHashIdentity(genPropBuilder);
2022 resultTOBuilder.addToStringProperty(genPropBuilder);
2024 } else if (typeDef instanceof BitsTypeDefinition) {
2025 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
2026 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2028 if (!genTOBuilders.isEmpty()) {
2029 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2030 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2032 return genTOBuilders.get(0);
2039 * Adds the implemented types to type builder.
2041 * The method passes through the list of <i>uses</i> in
2042 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2043 * generated type from {@link BindingGeneratorImpl#allGroupings
2044 * allGroupings} which is added as <i>implements type</i> to
2045 * <code>builder</code>
2047 * @param dataNodeContainer
2048 * element which contains the list of used YANG groupings
2050 * builder to which are added implemented types according to
2051 * <code>dataNodeContainer</code>
2052 * @return generated type builder with all implemented types
2054 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2055 final GeneratedTypeBuilder builder) {
2056 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2057 if (usesNode.getGroupingPath() != null) {
2058 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2059 if (genType == null) {
2060 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2061 + builder.getName());
2064 builder.addImplementsType(genType);
2066 builder.addComment(genType.getDescription());
2067 builder.setDescription(genType.getDescription());
2068 builder.setModuleName(genType.getModuleName());
2069 builder.setReference(genType.getReference());
2070 builder.setSchemaPath(genType.getSchemaPath());
2077 private static boolean isNullOrEmpty(final Collection<?> list) {
2078 return list == null || list.isEmpty();
2081 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
2082 final StringBuilder sb = new StringBuilder();
2084 if (!isNullOrEmpty(schemaNodes)) {
2085 final SchemaNode node = schemaNodes.iterator().next();
2087 if (node instanceof RpcDefinition) {
2088 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2089 } else if (node instanceof NotificationDefinition) {
2090 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2093 sb.append(NEW_LINE);
2094 sb.append("<br>(Source path: <i>");
2095 sb.append(moduleSourcePath);
2096 sb.append("</i>):");
2097 sb.append(NEW_LINE);
2099 if (verboseClassComments) {
2101 sb.append(NEW_LINE);
2102 sb.append(YangTemplate.generateYangSnipet(schemaNodes));
2103 sb.append("</pre>");
2104 sb.append(NEW_LINE);
2107 return replaceAllIllegalChars(sb);
2110 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2111 final StringBuilder sb = new StringBuilder();
2112 final String formattedDescription = YangTemplate.formatToParagraph(schemaNode.getDescription(), 0);
2114 if (!Strings.isNullOrEmpty(formattedDescription)) {
2115 sb.append(formattedDescription);
2116 sb.append(NEW_LINE);
2119 if (verboseClassComments) {
2120 final Module module = findParentModule(schemaContext, schemaNode);
2121 final StringBuilder linkToBuilderClass = new StringBuilder();
2122 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2123 final String className = namespace[namespace.length - 1];
2125 if (hasBuilderClass(schemaNode)) {
2126 linkToBuilderClass.append(className);
2127 linkToBuilderClass.append("Builder");
2131 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2132 sb.append(module.getName());
2134 sb.append(NEW_LINE);
2135 sb.append("<br>(Source path: <i>");
2136 sb.append(module.getModuleSourcePath());
2137 sb.append("</i>):");
2138 sb.append(NEW_LINE);
2140 sb.append(NEW_LINE);
2141 sb.append(YangTemplate.generateYangSnipet(schemaNode));
2142 sb.append("</pre>");
2143 sb.append(NEW_LINE);
2144 sb.append("The schema path to identify an instance is");
2145 sb.append(NEW_LINE);
2147 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2149 sb.append(NEW_LINE);
2151 if (hasBuilderClass(schemaNode)) {
2152 sb.append(NEW_LINE);
2153 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2154 sb.append(NEW_LINE);
2156 sb.append(linkToBuilderClass);
2157 sb.append(NEW_LINE);
2158 if (schemaNode instanceof ListSchemaNode) {
2159 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2160 if (keyDef != null && !keyDef.isEmpty()) {
2162 sb.append(className);
2165 sb.append(NEW_LINE);
2170 return replaceAllIllegalChars(sb);
2173 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2174 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2175 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2181 private String createDescription(final Module module) {
2182 final StringBuilder sb = new StringBuilder();
2183 final String formattedDescription = YangTemplate.formatToParagraph(module.getDescription(), 0);
2185 if (!Strings.isNullOrEmpty(formattedDescription)) {
2186 sb.append(formattedDescription);
2187 sb.append(NEW_LINE);
2190 if (verboseClassComments) {
2192 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2193 sb.append(module.getName());
2195 sb.append(NEW_LINE);
2196 sb.append("<br>Source path: <i>");
2197 sb.append(module.getModuleSourcePath());
2198 sb.append("</i>):");
2199 sb.append(NEW_LINE);
2201 sb.append(NEW_LINE);
2202 sb.append(YangTemplate.generateYangSnipet(module));
2203 sb.append("</pre>");
2206 return replaceAllIllegalChars(sb);
2209 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2210 for (final ModuleContext ctx : genCtx.values()) {
2211 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2212 if (result != null) {
2219 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2220 for (final ModuleContext ctx : genCtx.values()) {
2221 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2222 if (result != null) {
2229 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2230 for (final ModuleContext ctx : genCtx.values()) {
2231 final GeneratedTypeBuilder result = ctx.getCase(path);
2232 if (result != null) {
2239 public Map<Module, ModuleContext> getModuleContexts() {
2244 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2245 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2246 return ret.isEmpty() ? "" : ret;