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;
29 import com.google.common.annotations.VisibleForTesting;
30 import com.google.common.base.Optional;
31 import com.google.common.base.Preconditions;
32 import com.google.common.base.Splitter;
33 import com.google.common.base.Strings;
34 import com.google.common.collect.Iterables;
35 import com.google.common.collect.Sets;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.Collections;
39 import java.util.HashMap;
40 import java.util.Iterator;
41 import java.util.List;
44 import java.util.regex.Pattern;
45 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
46 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
47 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
48 import org.opendaylight.yangtools.binding.generator.util.Types;
49 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
50 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
51 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
52 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
53 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
54 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
55 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
56 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
57 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
58 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
59 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
60 import org.opendaylight.yangtools.sal.binding.model.api.Type;
61 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
62 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
66 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
67 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
68 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
69 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
70 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
71 import org.opendaylight.yangtools.yang.binding.BindingMapping;
72 import org.opendaylight.yangtools.yang.binding.DataContainer;
73 import org.opendaylight.yangtools.yang.binding.RpcService;
74 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
75 import org.opendaylight.yangtools.yang.common.QName;
76 import org.opendaylight.yangtools.yang.common.RpcResult;
77 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
78 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
79 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
82 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
85 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.Module;
90 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
91 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
92 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
93 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
94 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
96 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
97 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.UsesNode;
99 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
100 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
102 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
103 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
104 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
105 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
106 import org.opendaylight.yangtools.yang.model.util.UnionType;
107 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
108 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
109 import org.slf4j.Logger;
110 import org.slf4j.LoggerFactory;
112 public class BindingGeneratorImpl implements BindingGenerator {
113 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
114 private static final Splitter COLON_SPLITTER = Splitter.on(':');
115 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
116 private static final char NEW_LINE = '\n';
119 * Constant with the concrete name of identifier.
121 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
124 * Constant with the concrete name of namespace.
126 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
128 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
130 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
133 * When set to true, generated classes will include javadoc comments which
134 * are useful for users.
136 private final boolean verboseClassComments;
139 * Outer key represents the package name. Outer value represents map of all
140 * builders in the same package. Inner key represents the schema node name
141 * (in JAVA class/interface name format). Inner value represents instance of
142 * builder for schema node specified in key part.
144 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
147 * Provide methods for converting YANG types to JAVA types.
149 private TypeProvider typeProvider;
152 * Holds reference to schema context to resolve data of augmented element
153 * when creating augmentation builder
155 private SchemaContext schemaContext;
158 * Create a new binding generator with verboe comments.
160 * @deprecated Use {@link #BindingGeneratorImpl(boolean)} instead.
163 public BindingGeneratorImpl() {
168 * Create a new binding generator.
170 * @param verboseClassComments generate verbose comments
172 public BindingGeneratorImpl(final boolean verboseClassComments) {
173 this.verboseClassComments = verboseClassComments;
177 * Resolves generated types from <code>context</code> schema nodes of all
180 * Generated types are created for modules, groupings, types, containers,
181 * lists, choices, augments, rpcs, notification, identities.
184 * schema context which contains data about all schema nodes
186 * @return list of types (usually <code>GeneratedType</code>
187 * <code>GeneratedTransferObject</code>which are generated from
188 * <code>context</code> data.
189 * @throws IllegalArgumentException
190 * if arg <code>context</code> is null
191 * @throws IllegalStateException
192 * if <code>context</code> contain no modules
195 public List<Type> generateTypes(final SchemaContext context) {
196 checkArgument(context != null, "Schema Context reference cannot be NULL.");
197 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
198 schemaContext = context;
199 typeProvider = new TypeProviderImpl(context);
200 final Set<Module> modules = context.getModules();
201 return generateTypes(context, modules);
205 * Resolves generated types from <code>context</code> schema nodes only for
206 * modules specified in <code>modules</code>
208 * Generated types are created for modules, groupings, types, containers,
209 * lists, choices, augments, rpcs, notification, identities.
212 * schema context which contains data about all schema nodes
215 * set of modules for which schema nodes should be generated
217 * @return list of types (usually <code>GeneratedType</code> or
218 * <code>GeneratedTransferObject</code>) which:
220 * <li>are generated from <code>context</code> schema nodes and</li>
221 * <li>are also part of some of the module in <code>modules</code>
224 * @throws IllegalArgumentException
226 * <li>if arg <code>context</code> is null or</li>
227 * <li>if arg <code>modules</code> is null</li>
229 * @throws IllegalStateException
230 * if <code>context</code> contain no modules
233 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
234 checkArgument(context != null, "Schema Context reference cannot be NULL.");
235 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
236 checkArgument(modules != null, "Set of Modules cannot be NULL.");
238 schemaContext = context;
239 typeProvider = new TypeProviderImpl(context);
240 final Module[] modulesArray = new Module[context.getModules().size()];
241 context.getModules().toArray(modulesArray);
242 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
243 genTypeBuilders = new HashMap<>();
245 for (final Module contextModule : contextModules) {
246 moduleToGenTypes(contextModule, context);
248 for (final Module contextModule : contextModules) {
249 allAugmentsToGenTypes(contextModule);
252 final List<Type> filteredGenTypes = new ArrayList<>();
253 for (final Module m : modules) {
254 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
255 filteredGenTypes.addAll(ctx.getGeneratedTypes());
256 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
257 if (additionalTypes != null) {
258 filteredGenTypes.addAll(additionalTypes);
262 return filteredGenTypes;
265 private void moduleToGenTypes(final Module m, final SchemaContext context) {
266 genCtx.put(m, new ModuleContext());
267 allTypeDefinitionsToGenTypes(m);
268 groupingsToGenTypes(m, m.getGroupings());
269 rpcMethodsToGenType(m);
270 allIdentitiesToGenTypes(m, context);
271 notificationsToGenType(m);
273 if (!m.getChildNodes().isEmpty()) {
274 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
275 genCtx.get(m).addModuleNode(moduleType);
276 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
277 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
282 * Converts all extended type definitions of module to the list of
283 * <code>Type</code> objects.
286 * module from which is obtained set of type definitions
287 * @throws IllegalArgumentException
289 * <li>if module is null</li>
290 * <li>if name of module is null</li>
292 * @throws IllegalStateException
293 * if set of type definitions from module is null
295 private void allTypeDefinitionsToGenTypes(final Module module) {
296 checkArgument(module != null, "Module reference cannot be NULL.");
297 checkArgument(module.getName() != null, "Module name cannot be NULL.");
298 final DataNodeIterator it = new DataNodeIterator(module);
299 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
300 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
302 for (final TypeDefinition<?> typedef : typeDefinitions) {
303 if (typedef != null) {
304 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
307 final ModuleContext ctx = genCtx.get(module);
308 ctx.addTypedefType(typedef.getPath(), type);
309 ctx.addTypeToSchema(type,typedef);
315 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
316 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
317 if (node.isAugmenting() || node.isAddedByUses()) {
320 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
321 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
322 genType.addComment(node.getDescription());
323 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
324 genType.setModuleName(module.getName());
325 genType.setReference(node.getReference());
326 genType.setSchemaPath(node.getPath().getPathFromRoot());
327 if (node instanceof DataNodeContainer) {
328 genCtx.get(module).addChildNodeType(node, genType);
329 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
330 processUsesAugments((DataNodeContainer) node, module);
335 private void containerToGenType(final Module module, final String basePackageName,
336 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
337 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
338 if (genType != null) {
339 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType);
340 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
344 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
345 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
346 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
347 if (genType != null) {
348 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), Types.listTypeFor(genType));
350 final List<String> listKeys = listKeys(node);
351 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
352 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
353 if (genTOBuilder != null) {
354 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
355 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
356 genTOBuilder.addImplementsType(identifierMarker);
357 genType.addImplementsType(identifiableMarker);
360 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
361 if (!schemaNode.isAugmenting()) {
362 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
367 if (genTOBuilder != null) {
368 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
369 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
370 genTOBuilder.setSUID(prop);
373 typeBuildersToGenTypes(module, genType, genTOBuilder);
377 private void processUsesAugments(final DataNodeContainer node, final Module module) {
378 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
379 for (final UsesNode usesNode : node.getUses()) {
380 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
381 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
382 processUsesAugments(augment, module);
388 * Converts all <b>augmentation</b> of the module to the list
389 * <code>Type</code> objects.
392 * module from which is obtained list of all augmentation objects
393 * to iterate over them
394 * @throws IllegalArgumentException
396 * <li>if the module is null</li>
397 * <li>if the name of module is null</li>
399 * @throws IllegalStateException
400 * if set of augmentations from module is null
402 private void allAugmentsToGenTypes(final Module module) {
403 checkArgument(module != null, "Module reference cannot be NULL.");
404 checkArgument(module.getName() != null, "Module name cannot be NULL.");
405 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
407 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
408 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
409 for (final AugmentationSchema augment : augmentations) {
410 augmentationToGenTypes(basePackageName, augment, module);
415 * Returns list of <code>AugmentationSchema</code> objects. The objects are
416 * sorted according to the length of their target path from the shortest to
420 * module from which is obtained list of all augmentation objects
421 * @return list of sorted <code>AugmentationSchema</code> objects obtained
422 * from <code>module</code>
423 * @throws IllegalArgumentException
425 * @throws IllegalStateException
426 * if set of module augmentations is null
428 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
429 checkArgument(module != null, "Module reference cannot be NULL.");
430 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
432 final Set<AugmentationSchema> augmentations = module.getAugmentations();
433 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
434 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
436 return sortedAugmentations;
440 * Create GeneratedTypeBuilder object from module argument.
443 * Module object from which builder will be created
444 * @return <code>GeneratedTypeBuilder</code> which is internal
445 * representation of the module
446 * @throws IllegalArgumentException
449 private GeneratedTypeBuilder moduleToDataType(final Module module) {
450 checkArgument(module != null, "Module reference cannot be NULL.");
452 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
453 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
454 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
455 moduleDataTypeBuilder.addComment(module.getDescription());
456 moduleDataTypeBuilder.setDescription(createDescription(module));
457 moduleDataTypeBuilder.setReference(module.getReference());
458 return moduleDataTypeBuilder;
462 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
463 * to the list of <code>Type</code> objects. In addition are to containers
464 * and lists which belong to input or output also part of returning list.
467 * module from which is obtained set of all rpc objects to
469 * @throws IllegalArgumentException
471 * <li>if the module is null</li>
472 * <li>if the name of module is null</li>
474 * @throws IllegalStateException
475 * if set of rpcs from module is null
477 private void rpcMethodsToGenType(final Module module) {
478 checkArgument(module != null, "Module reference cannot be NULL.");
479 checkArgument(module.getName() != null, "Module name cannot be NULL.");
480 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
481 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
482 if (rpcDefinitions.isEmpty()) {
486 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
487 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
488 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
489 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
491 for (final RpcDefinition rpc : rpcDefinitions) {
493 final String rpcName = BindingMapping.getClassName(rpc.getQName());
494 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
495 final String rpcComment = rpc.getDescription();
496 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
497 final ContainerSchemaNode input = rpc.getInput();
498 final ContainerSchemaNode output = rpc.getOutput();
501 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
502 addImplementedInterfaceFromUses(input, inType);
503 inType.addImplementsType(DATA_OBJECT);
504 inType.addImplementsType(augmentable(inType));
505 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
506 genCtx.get(module).addChildNodeType(input, inType);
507 final GeneratedType inTypeInstance = inType.toInstance();
508 method.addParameter(inTypeInstance, "input");
511 Type outTypeInstance = VOID;
512 if (output != null) {
513 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
514 addImplementedInterfaceFromUses(output, outType);
515 outType.addImplementsType(DATA_OBJECT);
516 outType.addImplementsType(augmentable(outType));
517 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
518 genCtx.get(module).addChildNodeType(output, outType);
519 outTypeInstance = outType.toInstance();
522 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
523 method.setComment(rpcComment);
524 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
528 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
532 * Converts all <b>notifications</b> of the module to the list of
533 * <code>Type</code> objects. In addition are to this list added containers
534 * and lists which are part of this notification.
537 * module from which is obtained set of all notification objects
538 * to iterate over them
539 * @throws IllegalArgumentException
541 * <li>if the module equals null</li>
542 * <li>if the name of module equals null</li>
544 * @throws IllegalStateException
545 * if set of notifications from module is null
547 private void notificationsToGenType(final Module module) {
548 checkArgument(module != null, "Module reference cannot be NULL.");
549 checkArgument(module.getName() != null, "Module name cannot be NULL.");
550 final Set<NotificationDefinition> notifications = module.getNotifications();
551 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
552 if (notifications.isEmpty()) {
556 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
557 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
558 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
562 for (final NotificationDefinition notification : notifications) {
563 if (notification != null) {
564 processUsesAugments(notification, module);
566 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
567 notification, null, module);
568 notificationInterface.addImplementsType(NOTIFICATION);
569 genCtx.get(module).addChildNodeType(notification, notificationInterface);
571 // Notification object
572 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
573 notification.getChildNodes());
575 listenerInterface.addMethod("on" + notificationInterface.getName())
576 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
577 .setComment(notification.getDescription()).setReturnType(Types.VOID);
580 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
582 genCtx.get(module).addTopLevelNodeType(listenerInterface);
586 * Converts all <b>identities</b> of the module to the list of
587 * <code>Type</code> objects.
590 * module from which is obtained set of all identity objects to
593 * schema context only used as input parameter for method
594 * {@link identityToGenType}
597 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
598 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
599 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
601 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
602 for (final IdentitySchemaNode identity : schemaIdentities) {
603 identityToGenType(module, basePackageName, identity, context);
609 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
610 * created transport object builder. If identity contains base identity then
611 * reference to base identity is added to superior identity as its extend.
612 * If identity doesn't contain base identity then only reference to abstract
613 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
614 * BaseIdentity} is added
618 * @param basePackageName
619 * string contains the module package name
621 * IdentitySchemaNode which contains data about identity
623 * SchemaContext which is used to get package and name
624 * information about base of identity
627 private void identityToGenType(final Module module, final String basePackageName,
628 final IdentitySchemaNode identity, final SchemaContext context) {
629 if (identity == null) {
632 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
633 final String genTypeName = BindingMapping.getClassName(identity.getQName());
634 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
635 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
636 if (baseIdentity == null) {
637 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
638 BaseIdentity.class.getSimpleName());
639 newType.setExtendsType(gto.toInstance());
641 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
642 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
644 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
645 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
647 newType.setExtendsType(gto);
649 newType.setAbstract(true);
650 newType.addComment(identity.getDescription());
651 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
652 newType.setReference(identity.getReference());
653 newType.setModuleName(module.getName());
654 newType.setSchemaPath(identity.getPath().getPathFromRoot());
656 final QName qname = identity.getQName();
657 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
659 genCtx.get(module).addIdentityType(identity.getQName(), newType);
662 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
664 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
668 * Converts all <b>groupings</b> of the module to the list of
669 * <code>Type</code> objects. Firstly are groupings sorted according mutual
670 * dependencies. At least dependent (independent) groupings are in the list
671 * saved at first positions. For every grouping the record is added to map
672 * {@link BindingGeneratorImpl#allGroupings allGroupings}
677 * of groupings from which types will be generated
680 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
681 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
682 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
684 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
685 groupingToGenType(basePackageName, grouping, module);
690 * Converts individual grouping to GeneratedType. Firstly generated type
691 * builder is created and every child node of grouping is resolved to the
694 * @param basePackageName
695 * string contains the module package name
697 * GroupingDefinition which contains data about grouping
700 * @return GeneratedType which is generated from grouping (object of type
701 * <code>GroupingDefinition</code>)
703 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
704 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
705 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
706 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
707 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
708 groupingsToGenTypes(module, grouping.getGroupings());
709 processUsesAugments(grouping, module);
713 * Adds enumeration builder created from <code>enumTypeDef</code> to
714 * <code>typeBuilder</code>.
716 * Each <code>enumTypeDef</code> item is added to builder with its name and
720 * EnumTypeDefinition contains enum data
722 * string contains name which will be assigned to enumeration
725 * GeneratedTypeBuilder to which will be enum builder assigned
727 * Module in which type should be generated
728 * @return enumeration builder which contains data from
729 * <code>enumTypeDef</code>
731 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
732 final GeneratedTypeBuilder typeBuilder, final Module module) {
733 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
734 && (enumTypeDef.getQName().getLocalName() != null)) {
735 final String enumerationName = BindingMapping.getClassName(enumName);
736 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
737 enumBuilder.setDescription(enumTypeDef.getDescription());
738 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
739 ModuleContext ctx = genCtx.get(module);
740 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
747 * Generates type builder for <code>module</code>.
750 * Module which is source of package name for generated type
753 * string which is added to the module class name representation
755 * @return instance of GeneratedTypeBuilder which represents
756 * <code>module</code>.
757 * @throws IllegalArgumentException
758 * if <code>module</code> is null
760 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
761 checkArgument(module != null, "Module reference cannot be NULL.");
762 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
763 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
765 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
766 moduleBuilder.setDescription(createDescription(module));
767 moduleBuilder.setReference(module.getReference());
768 moduleBuilder.setModuleName(moduleName);
770 return moduleBuilder;
774 * Converts <code>augSchema</code> to list of <code>Type</code> which
775 * contains generated type for augmentation. In addition there are also
776 * generated types for all containers, list and choices which are child of
777 * <code>augSchema</code> node or a generated types for cases are added if
778 * augmented node is choice.
780 * @param augmentPackageName
781 * string with the name of the package to which the augmentation
784 * AugmentationSchema which is contains data about augmentation
785 * (target path, childs...)
788 * @param parentUsesNode
789 * @throws IllegalArgumentException
791 * <li>if <code>augmentPackageName</code> equals null</li>
792 * <li>if <code>augSchema</code> equals null</li>
794 * @throws IllegalStateException
795 * if augment target path is null
797 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
798 final Module module) {
799 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
800 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
801 checkState(augSchema.getTargetPath() != null,
802 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
804 processUsesAugments(augSchema, module);
805 final SchemaPath targetPath = augSchema.getTargetPath();
806 SchemaNode targetSchemaNode = null;
808 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
809 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
810 if (targetSchemaNode instanceof DerivableSchemaNode) {
811 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
813 if (targetSchemaNode == null) {
814 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
815 + " in module " + module.getName());
818 if (targetSchemaNode == null) {
819 throw new IllegalArgumentException("augment target not found: " + targetPath);
822 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
823 if (targetTypeBuilder == null) {
824 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
826 if (targetTypeBuilder == null) {
827 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
830 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
831 final String packageName = augmentPackageName;
832 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
833 targetTypeBuilder.getName());
834 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
837 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
838 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
842 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
843 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
844 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
845 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
846 checkState(augSchema.getTargetPath() != null,
847 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
849 processUsesAugments(augSchema, module);
850 final SchemaPath targetPath = augSchema.getTargetPath();
851 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
852 if (targetSchemaNode == null) {
853 throw new IllegalArgumentException("augment target not found: " + targetPath);
856 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
857 if (targetTypeBuilder == null) {
858 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
860 if (targetTypeBuilder == null) {
861 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
864 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
865 String packageName = augmentPackageName;
866 if (usesNodeParent instanceof SchemaNode) {
867 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
869 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
872 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
873 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
878 * Convenient method to find node added by uses statement.
882 * @param parentUsesNode
883 * parent of uses node
884 * @return node from its original location in grouping
886 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
887 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
889 if (!(targetGrouping instanceof GroupingDefinition)) {
890 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
893 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
894 SchemaNode result = grouping;
895 for (final QName node : targetPath.getPathFromRoot()) {
896 // finding by local name is valid, grouping cannot contain nodes
897 // with same name and different namespace
898 if (result instanceof DataNodeContainer) {
899 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
900 } else if (result instanceof ChoiceSchemaNode) {
901 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
904 if (result == null) {
908 if (result instanceof DerivableSchemaNode) {
909 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
910 Optional<? extends SchemaNode> originalNode = castedResult
912 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
913 result = originalNode.get();
917 if (result instanceof DataSchemaNode) {
918 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
919 if (resultDataSchemaNode.isAddedByUses()) {
920 // The original node is required, but we have only the copy of
921 // the original node.
922 // Maybe this indicates a bug in Yang parser.
923 throw new IllegalStateException(
924 "Failed to generate code for augment in "
927 return resultDataSchemaNode;
930 throw new IllegalStateException(
931 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
937 * Returns a generated type builder for an augmentation.
939 * The name of the type builder is equal to the name of augmented node with
940 * serial number as suffix.
944 * @param augmentPackageName
945 * string with contains the package name to which the augment
947 * @param basePackageName
948 * string with the package name to which the augmented node
950 * @param targetTypeRef
953 * augmentation schema which contains data about the child nodes
954 * and uses of augment
955 * @return generated type builder for augment
957 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
958 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
959 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
960 if (augmentBuilders == null) {
961 augmentBuilders = new HashMap<>();
962 genTypeBuilders.put(augmentPackageName, augmentBuilders);
964 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
967 if (augIdentifier != null) {
968 augTypeName = BindingMapping.getClassName(augIdentifier);
970 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
973 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
975 augTypeBuilder.addImplementsType(DATA_OBJECT);
976 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
977 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
979 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
980 augmentBuilders.put(augTypeName, augTypeBuilder);
982 if(!augSchema.getChildNodes().isEmpty()) {
983 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
984 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
987 genCtx.get(module).addAugmentType(augTypeBuilder);
988 return augTypeBuilder;
993 * @param unknownSchemaNodes
994 * @return nodeParameter of UnknownSchemaNode
996 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
997 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
998 final QName nodeType = unknownSchemaNode.getNodeType();
999 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1000 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1001 return unknownSchemaNode.getNodeParameter();
1008 * Returns first unique name for the augment generated type builder. The
1009 * generated type builder name for augment consists from name of augmented
1010 * node and serial number of its augmentation.
1013 * map of builders which were created in the package to which the
1014 * augmentation belongs
1015 * @param genTypeName
1016 * string with name of augmented node
1017 * @return string with unique name for augmentation builder
1019 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1021 if (builders != null) {
1022 while (builders.containsKey(genTypeName + index)) {
1026 return genTypeName + index;
1030 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1031 * node for which <code>typeBuilder</code> was created.
1033 * The subnodes aren't mapped to the methods if they are part of grouping or
1034 * augment (in this case are already part of them).
1038 * @param basePackageName
1039 * string contains the module package name
1041 * generated type builder which represents any node. The subnodes
1042 * of this node are added to the <code>typeBuilder</code> as
1043 * methods. The subnode can be of type leaf, leaf-list, list,
1044 * container, choice.
1047 * @param schemaNodes
1048 * set of data schema nodes which are the children of the node
1049 * for which <code>typeBuilder</code> was created
1050 * @return generated type builder which is the same builder as input
1051 * parameter. The getter methods (representing child nodes) could be
1054 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1055 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1056 if (schemaNodes != null && parent != null) {
1057 for (final DataSchemaNode schemaNode : schemaNodes) {
1058 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1059 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1067 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1068 * node for which <code>typeBuilder</code> was created.
1072 * @param basePackageName
1073 * string contains the module package name
1074 * @param typeBuilder
1075 * generated type builder which represents any node. The subnodes
1076 * of this node are added to the <code>typeBuilder</code> as
1077 * methods. The subnode can be of type leaf, leaf-list, list,
1078 * container, choice.
1081 * @param schemaNodes
1082 * set of data schema nodes which are the children of the node
1083 * for which <code>typeBuilder</code> was created
1084 * @return generated type builder which is the same object as the input
1085 * parameter <code>typeBuilder</code>. The getter method could be
1088 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1089 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1090 final Iterable<DataSchemaNode> schemaNodes) {
1091 if ((schemaNodes != null) && (typeBuilder != null)) {
1092 for (final DataSchemaNode schemaNode : schemaNodes) {
1093 if (!schemaNode.isAugmenting()) {
1094 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1102 * Adds to <code>typeBuilder</code> a method which is derived from
1103 * <code>schemaNode</code>.
1105 * @param basePackageName
1106 * string with the module package name
1108 * data schema node which is added to <code>typeBuilder</code> as
1110 * @param typeBuilder
1111 * generated type builder to which is <code>schemaNode</code>
1112 * added as a method.
1118 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1119 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1120 if (node != null && typeBuilder != null) {
1121 if (node instanceof LeafSchemaNode) {
1122 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1123 } else if (node instanceof LeafListSchemaNode) {
1124 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1125 } else if (node instanceof ContainerSchemaNode) {
1126 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1127 } else if (node instanceof ListSchemaNode) {
1128 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1129 } else if (node instanceof ChoiceSchemaNode) {
1130 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1132 // TODO: anyxml not yet supported
1133 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1134 typeBuilder.getFullyQualifiedName());
1140 * Converts <code>choiceNode</code> to the list of generated types for
1141 * choice and its cases.
1143 * The package names for choice and for its cases are created as
1144 * concatenation of the module package (<code>basePackageName</code>) and
1145 * names of all parents node.
1149 * @param basePackageName
1150 * string with the module package name
1154 * choice node which is mapped to generated type. Also child
1155 * nodes - cases are mapped to generated types.
1156 * @throws IllegalArgumentException
1158 * <li>if <code>basePackageName</code> is null</li>
1159 * <li>if <code>choiceNode</code> is null</li>
1162 private void choiceToGeneratedType(final Module module, final String basePackageName,
1163 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1164 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1165 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1167 if (!choiceNode.isAddedByUses()) {
1168 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1169 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1170 constructGetter(parent, choiceNode.getQName().getLocalName(), choiceNode.getDescription(),
1172 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1173 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1174 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1179 * Converts <code>caseNodes</code> set to list of corresponding generated
1182 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1183 * created generated type builder. The package names for the builder is
1184 * created as concatenation of the module package (
1185 * <code>basePackageName</code>) and names of all parents nodes of the
1186 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1187 * between every case builder and <i>choice</i> type
1191 * @param basePackageName
1192 * string with the module package name
1193 * @param refChoiceType
1194 * type which represents superior <i>case</i>
1196 * choice case node which is mapped to generated type
1197 * @return list of generated types for <code>caseNodes</code>.
1198 * @throws IllegalArgumentException
1200 * <li>if <code>basePackageName</code> equals null</li>
1201 * <li>if <code>refChoiceType</code> equals null</li>
1202 * <li>if <code>caseNodes</code> equals null</li>
1205 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1206 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1207 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1208 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1209 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1211 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1212 if (caseNodes == null) {
1216 for (final ChoiceCaseNode caseNode : caseNodes) {
1217 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1218 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1219 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1220 caseTypeBuilder.addImplementsType(refChoiceType);
1221 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1222 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1223 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1224 if (caseChildNodes != null) {
1225 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1227 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1228 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1230 if (parent instanceof AugmentationSchema) {
1231 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1232 final SchemaPath targetPath = augSchema.getTargetPath();
1233 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1234 if (targetSchemaNode instanceof DataSchemaNode
1235 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1236 if (targetSchemaNode instanceof DerivableSchemaNode) {
1237 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1239 if (targetSchemaNode == null) {
1240 throw new IllegalStateException(
1241 "Failed to find target node from grouping for augmentation " + augSchema
1242 + " in module " + module.getName());
1245 parent = targetSchemaNode;
1248 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1249 choiceNodeParentPath);
1250 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1251 if (childOfType == null) {
1252 childOfType = findGroupingByPath(parent.getPath());
1254 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1256 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1261 processUsesAugments(caseNode, module);
1266 * Generates list of generated types for all the cases of a choice which are
1267 * added to the choice through the augment.
1271 * @param basePackageName
1272 * string contains name of package to which augment belongs. If
1273 * an augmented choice is from an other package (pcg1) than an
1274 * augmenting choice (pcg2) then case's of the augmenting choice
1275 * will belong to pcg2.
1277 * Type which represents target choice
1279 * node which represents target choice
1280 * @param augmentedNodes
1281 * set of choice case nodes for which is checked if are/aren't
1282 * added to choice through augmentation
1283 * @return list of generated types which represents augmented cases of
1284 * choice <code>refChoiceType</code>
1285 * @throws IllegalArgumentException
1287 * <li>if <code>basePackageName</code> is null</li>
1288 * <li>if <code>targetType</code> is null</li>
1289 * <li>if <code>augmentedNodes</code> is null</li>
1292 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1293 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
1294 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1295 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1296 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1298 for (final DataSchemaNode caseNode : augmentedNodes) {
1299 if (caseNode != null) {
1300 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1301 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1302 caseTypeBuilder.addImplementsType(targetType);
1304 SchemaNode parent = null;
1305 final SchemaPath nodeSp = targetNode.getPath();
1306 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1308 GeneratedTypeBuilder childOfType = null;
1309 if (parent instanceof Module) {
1310 childOfType = genCtx.get(parent).getModuleNode();
1311 } else if (parent instanceof ChoiceCaseNode) {
1312 childOfType = findCaseByPath(parent.getPath());
1313 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1314 childOfType = findChildNodeByPath(parent.getPath());
1315 } else if (parent instanceof GroupingDefinition) {
1316 childOfType = findGroupingByPath(parent.getPath());
1319 if (childOfType == null) {
1320 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1323 ChoiceCaseNode node = null;
1324 if (caseNode instanceof ChoiceCaseNode) {
1325 node = (ChoiceCaseNode) caseNode;
1327 node = targetNode.getCaseNodeByName(caseNode.getQName().getLocalName());
1329 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1330 if (childNodes != null) {
1331 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1333 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1334 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1340 * Converts <code>leaf</code> to the getter method which is added to
1341 * <code>typeBuilder</code>.
1343 * @param typeBuilder
1344 * generated type builder to which is added getter method as
1345 * <code>leaf</code> mapping
1347 * leaf schema node which is mapped as getter method which is
1348 * added to <code>typeBuilder</code>
1350 * Module in which type was defined
1351 * @return boolean value
1353 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1355 * <li>true - in other cases</li>
1358 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1359 Type returnType = null;
1360 if ((leaf != null) && (typeBuilder != null)) {
1361 final String leafName = leaf.getQName().getLocalName();
1362 String leafDesc = leaf.getDescription();
1363 if (leafDesc == null) {
1367 final Module parentModule = findParentModule(schemaContext, leaf);
1368 if (leafName != null && !leaf.isAddedByUses()) {
1369 final TypeDefinition<?> typeDef = leaf.getType();
1371 GeneratedTOBuilder genTOBuilder;
1372 if (typeDef instanceof EnumTypeDefinition) {
1373 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1374 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1375 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1376 typeBuilder,module);
1378 if (enumBuilder != null) {
1379 returnType = enumBuilder.toInstance(typeBuilder);
1381 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1382 } else if (typeDef instanceof UnionType) {
1383 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1384 if (genTOBuilder != null) {
1385 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1387 } else if (typeDef instanceof BitsTypeDefinition) {
1388 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1389 if (genTOBuilder != null) {
1390 returnType = genTOBuilder.toInstance();
1393 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1394 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1396 if (returnType != null) {
1397 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1398 processContextRefExtension(leaf, getter, parentModule);
1405 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1406 final Module module) {
1407 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1408 final QName nodeType = node.getNodeType();
1409 if ("context-reference".equals(nodeType.getLocalName())) {
1410 final String nodeParam = node.getNodeParameter();
1411 IdentitySchemaNode identity = null;
1412 String basePackageName = null;
1413 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1414 final Iterator<String> iterator = splittedElement.iterator();
1415 final int length = Iterables.size(splittedElement);
1417 identity = findIdentityByName(module.getIdentities(), iterator.next());
1418 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1419 } else if (length == 2) {
1420 final String prefix = iterator.next();
1421 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1422 if (dependentModule == null) {
1423 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1426 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1427 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1429 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1432 if (identity == null) {
1433 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1437 final Class<RoutingContext> clazz = RoutingContext.class;
1438 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1439 clazz.getSimpleName());
1440 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1441 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1442 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1447 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1448 for (final IdentitySchemaNode id : identities) {
1449 if (id.getQName().getLocalName().equals(name)) {
1456 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1457 for (final ModuleImport imp : imports) {
1458 if (imp.getPrefix().equals(prefix)) {
1459 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1465 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1466 final boolean isReadOnly, final Module module) {
1467 if ((leaf != null) && (toBuilder != null)) {
1468 String leafDesc = leaf.getDescription();
1469 if (leafDesc == null) {
1472 Type returnType = null;
1473 final TypeDefinition<?> typeDef = leaf.getType();
1474 if (typeDef instanceof UnionTypeDefinition) {
1475 // GeneratedType for this type definition should be already
1477 final QName qname = typeDef.getQName();
1478 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1479 qname.getRevision());
1480 final ModuleContext mc = genCtx.get(unionModule);
1481 returnType = mc.getTypedefs().get(typeDef.getPath());
1482 } else if (typeDef instanceof EnumTypeDefinition && BaseTypes.ENUMERATION_QNAME.equals(typeDef.getQName())) {
1483 // Annonymous enumeration (already generated, since it is inherited via uses).
1484 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1485 QName qname = originalLeaf.getQName();
1486 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1487 qname.getRevision());
1488 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1490 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1492 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1498 * Converts <code>leaf</code> schema node to property of generated TO
1502 * generated TO builder to which is <code>leaf</code> added as
1505 * leaf schema node which is added to <code>toBuilder</code> as
1510 * boolean value which says if leaf property is|isn't read only
1511 * @return boolean value
1513 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1514 * name equals null or if leaf is added by <i>uses</i>.</li>
1515 * <li>true - other cases</li>
1518 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1519 final Type returnType, final boolean isReadOnly) {
1520 if (returnType == null) {
1523 final String leafName = leaf.getQName().getLocalName();
1524 final String leafDesc = leaf.getDescription();
1525 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1526 propBuilder.setReadOnly(isReadOnly);
1527 propBuilder.setReturnType(returnType);
1528 propBuilder.setComment(leafDesc);
1529 toBuilder.addEqualsIdentity(propBuilder);
1530 toBuilder.addHashIdentity(propBuilder);
1531 toBuilder.addToStringProperty(propBuilder);
1536 * Converts <code>node</code> leaf list schema node to getter method of
1537 * <code>typeBuilder</code>.
1539 * @param typeBuilder
1540 * generated type builder to which is <code>node</code> added as
1543 * leaf list schema node which is added to
1544 * <code>typeBuilder</code> as getter method
1546 * @return boolean value
1548 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1549 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1550 * <li>false - other cases</li>
1553 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1554 if ((node != null) && (typeBuilder != null)) {
1555 final QName nodeName = node.getQName();
1557 if (nodeName != null && !node.isAddedByUses()) {
1558 final TypeDefinition<?> typeDef = node.getType();
1559 final Module parentModule = findParentModule(schemaContext, node);
1561 Type returnType = null;
1562 if (typeDef instanceof EnumTypeDefinition) {
1563 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1564 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1565 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1566 typeBuilder,module);
1567 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1568 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1569 } else if (typeDef instanceof UnionType) {
1570 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1571 if (genTOBuilder != null) {
1572 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1574 } else if (typeDef instanceof BitsTypeDefinition) {
1575 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1576 returnType = genTOBuilder.toInstance();
1578 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1579 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1582 final ParameterizedType listType = Types.listTypeFor(returnType);
1583 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1590 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1591 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1592 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1593 genTOBuilder.getName());
1595 returnType.setDescription(typeDef.getDescription());
1596 returnType.setReference(typeDef.getReference());
1597 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1598 returnType.setModuleName(parentModule.getName());
1600 genTOBuilder.setTypedef(true);
1601 genTOBuilder.setIsUnion(true);
1602 ((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1606 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1609 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1610 method.setReturnType(returnType);
1611 method.addParameter(Types.STRING, "defaultValue");
1612 method.setAccessModifier(AccessModifier.PUBLIC);
1613 method.setStatic(true);
1615 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1616 if (types == null) {
1617 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1618 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1620 types.add(unionBuilder.toInstance());
1622 return returnType.toInstance();
1625 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1626 final String outerCls = Types.getOuterClassName(genTOBuilder);
1627 final StringBuilder name;
1628 if (outerCls != null) {
1629 name = new StringBuilder(outerCls);
1631 name = new StringBuilder();
1633 name.append(genTOBuilder.getName());
1634 name.append("Builder");
1635 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1636 unionBuilder.setIsUnionBuilder(true);
1637 return unionBuilder;
1640 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1641 final Module module) {
1642 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1646 * Instantiates generated type builder with <code>packageName</code> and
1647 * <code>schemaNode</code>.
1649 * The new builder always implements
1650 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1651 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1652 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1654 * If <code>schemaNode</code> is instance of
1655 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1656 * DataNodeContainer} it can also implement nodes which are specified in
1659 * @param packageName
1660 * string with the name of the package to which
1661 * <code>schemaNode</code> belongs.
1663 * schema node for which is created generated type builder
1665 * parent type (can be null)
1666 * @return generated type builder <code>schemaNode</code>
1668 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1669 final Type parent, final Module module) {
1670 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1671 if (parent == null) {
1672 it.addImplementsType(DATA_OBJECT);
1674 it.addImplementsType(BindingTypes.childOf(parent));
1676 if (!(schemaNode instanceof GroupingDefinition)) {
1677 it.addImplementsType(augmentable(it));
1680 if (schemaNode instanceof DataNodeContainer) {
1681 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1682 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1689 * Wraps the calling of the same overloaded method.
1691 * @param packageName
1692 * string with the package name to which returning generated type
1695 * schema node which provide data about the schema node name
1696 * @return generated type builder for <code>schemaNode</code>
1698 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1699 return addRawInterfaceDefinition(packageName, schemaNode, "");
1703 * Returns reference to generated type builder for specified
1704 * <code>schemaNode</code> with <code>packageName</code>.
1706 * Firstly the generated type builder is searched in
1707 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1708 * found it is created and added to <code>genTypeBuilders</code>.
1710 * @param packageName
1711 * string with the package name to which returning generated type
1714 * schema node which provide data about the schema node name
1716 * return type name prefix
1717 * @return generated type builder for <code>schemaNode</code>
1718 * @throws IllegalArgumentException
1720 * <li>if <code>schemaNode</code> is null</li>
1721 * <li>if <code>packageName</code> is null</li>
1722 * <li>if QName of schema node is null</li>
1723 * <li>if schemaNode name is null</li>
1727 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1728 final String prefix) {
1729 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1730 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1731 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1732 final String schemaNodeName = schemaNode.getQName().getLocalName();
1733 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1736 if (prefix == null) {
1737 genTypeName = BindingMapping.getClassName(schemaNodeName);
1739 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1742 // FIXME: Validation of name conflict
1743 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1744 final Module module = findParentModule(schemaContext, schemaNode);
1745 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1746 newType.addComment(schemaNode.getDescription());
1747 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1748 newType.setReference(schemaNode.getReference());
1749 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1750 newType.setModuleName(module.getName());
1752 if (!genTypeBuilders.containsKey(packageName)) {
1753 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1754 builders.put(genTypeName, newType);
1755 genTypeBuilders.put(packageName, builders);
1757 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1758 if (!builders.containsKey(genTypeName)) {
1759 builders.put(genTypeName, newType);
1766 * Creates the name of the getter method name from <code>localName</code>.
1769 * string with the name of the getter method
1772 * @return string with the name of the getter method for
1773 * <code>methodName</code> in JAVA method format
1775 public static String getterMethodName(final String localName, final Type returnType) {
1776 final StringBuilder method = new StringBuilder();
1777 if (BOOLEAN.equals(returnType)) {
1778 method.append("is");
1780 method.append("get");
1782 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1783 method.append(name);
1784 return method.toString();
1788 * Created a method signature builder as part of
1789 * <code>interfaceBuilder</code>.
1791 * The method signature builder is created for the getter method of
1792 * <code>schemaNodeName</code>. Also <code>comment</code> and
1793 * <code>returnType</code> information are added to the builder.
1795 * @param interfaceBuilder
1796 * generated type builder for which the getter method should be
1798 * @param schemaNodeName
1799 * string with schema node name. The name will be the part of the
1800 * getter method name.
1802 * string with comment for the getter method
1804 * type which represents the return type of the getter method
1805 * @return method signature builder which represents the getter method of
1806 * <code>interfaceBuilder</code>
1808 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1809 final String schemaNodeName, final String comment, final Type returnType) {
1810 final MethodSignatureBuilder getMethod = interfaceBuilder
1811 .addMethod(getterMethodName(schemaNodeName, returnType));
1812 getMethod.setComment(comment);
1813 getMethod.setReturnType(returnType);
1818 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1819 * or to <code>genTOBuilder</code> as property.
1821 * @param basePackageName
1822 * string contains the module package name
1824 * data schema node which should be added as getter method to
1825 * <code>typeBuilder</code> or as a property to
1826 * <code>genTOBuilder</code> if is part of the list key
1827 * @param typeBuilder
1828 * generated type builder for the list schema node
1829 * @param genTOBuilder
1830 * generated TO builder for the list keys
1832 * list of string which contains names of the list keys
1835 * @throws IllegalArgumentException
1837 * <li>if <code>schemaNode</code> equals null</li>
1838 * <li>if <code>typeBuilder</code> equals null</li>
1841 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1842 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1843 final Module module) {
1844 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1845 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1847 if (schemaNode instanceof LeafSchemaNode) {
1848 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1849 final String leafName = leaf.getQName().getLocalName();
1850 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1851 if (listKeys.contains(leafName)) {
1853 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1855 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1858 } else if (!schemaNode.isAddedByUses()) {
1859 if (schemaNode instanceof LeafListSchemaNode) {
1860 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1861 } else if (schemaNode instanceof ContainerSchemaNode) {
1862 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1863 } else if (schemaNode instanceof ChoiceSchemaNode) {
1864 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1865 } else if (schemaNode instanceof ListSchemaNode) {
1866 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1871 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1872 final GeneratedTOBuilder genTOBuilder) {
1873 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1875 if (genTOBuilder != null) {
1876 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1877 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
1878 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1883 * Selects the names of the list keys from <code>list</code> and returns
1884 * them as the list of the strings
1887 * of string with names of the list keys
1888 * @return list of string which represents names of the list keys. If the
1889 * <code>list</code> contains no keys then the empty list is
1892 private static List<String> listKeys(final ListSchemaNode list) {
1893 final List<String> listKeys = new ArrayList<>();
1895 final List<QName> keyDefinition = list.getKeyDefinition();
1896 if (keyDefinition != null) {
1897 for (final QName keyDef : keyDefinition) {
1898 listKeys.add(keyDef.getLocalName());
1905 * Generates for the <code>list</code> which contains any list keys special
1906 * generated TO builder.
1908 * @param packageName
1909 * string with package name to which the list belongs
1911 * list schema node which is source of data about the list name
1912 * @return generated TO builder which represents the keys of the
1913 * <code>list</code> or null if <code>list</code> is null or list of
1914 * key definitions is null or empty.
1916 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1917 GeneratedTOBuilder genTOBuilder = null;
1918 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1919 final String listName = list.getQName().getLocalName() + "Key";
1920 final String genTOName = BindingMapping.getClassName(listName);
1921 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1923 return genTOBuilder;
1927 * Builds generated TO builders for <code>typeDef</code> of type
1928 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
1929 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
1930 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
1931 * enclosing transfer object.
1933 * If more then one generated TO builder is created for enclosing then all
1934 * of the generated TO builders are added to <code>typeBuilder</code> as
1935 * enclosing transfer objects.
1938 * type definition which can be of type <code>UnionType</code> or
1939 * <code>BitsTypeDefinition</code>
1940 * @param typeBuilder
1941 * generated type builder to which is added generated TO created
1942 * from <code>typeDef</code>
1944 * string with name for generated TO builder
1946 * @return generated TO builder for <code>typeDef</code>
1948 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
1949 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1950 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
1951 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
1952 final String packageName = typeBuilder.getFullyQualifiedName();
1953 if (typeDef instanceof UnionTypeDefinition) {
1954 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
1955 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
1956 classNameFromLeaf, leaf);
1957 genTOBuilders.addAll(types);
1959 GeneratedTOBuilder resultTOBuilder = null;
1960 if (types.isEmpty()) {
1961 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
1963 resultTOBuilder = types.remove(0);
1964 for (final GeneratedTOBuilder genTOBuilder : types) {
1965 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1968 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1969 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1970 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1971 resultTOBuilder.addHashIdentity(genPropBuilder);
1972 resultTOBuilder.addToStringProperty(genPropBuilder);
1974 } else if (typeDef instanceof BitsTypeDefinition) {
1975 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
1976 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
1978 if (!genTOBuilders.isEmpty()) {
1979 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1980 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1982 return genTOBuilders.get(0);
1989 * Adds the implemented types to type builder.
1991 * The method passes through the list of <i>uses</i> in
1992 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1993 * generated type from {@link BindingGeneratorImpl#allGroupings
1994 * allGroupings} which is added as <i>implements type</i> to
1995 * <code>builder</code>
1997 * @param dataNodeContainer
1998 * element which contains the list of used YANG groupings
2000 * builder to which are added implemented types according to
2001 * <code>dataNodeContainer</code>
2002 * @return generated type builder with all implemented types
2004 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2005 final GeneratedTypeBuilder builder) {
2006 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2007 if (usesNode.getGroupingPath() != null) {
2008 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2009 if (genType == null) {
2010 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2011 + builder.getName());
2014 builder.addImplementsType(genType);
2016 builder.addComment(genType.getDescription());
2017 builder.setDescription(genType.getDescription());
2018 builder.setModuleName(genType.getModuleName());
2019 builder.setReference(genType.getReference());
2020 builder.setSchemaPath(genType.getSchemaPath());
2027 private static boolean isNullOrEmpty(final Collection<?> list) {
2028 return list == null || list.isEmpty();
2031 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
2032 final StringBuilder sb = new StringBuilder();
2034 if (!isNullOrEmpty(schemaNodes)) {
2035 final SchemaNode node = schemaNodes.iterator().next();
2037 if (node instanceof RpcDefinition) {
2038 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2039 } else if (node instanceof NotificationDefinition) {
2040 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2043 sb.append(NEW_LINE);
2044 sb.append("<br>(Source path: <i>");
2045 sb.append(moduleSourcePath);
2046 sb.append("</i>):");
2047 sb.append(NEW_LINE);
2049 if (verboseClassComments) {
2051 sb.append(NEW_LINE);
2052 sb.append(YangTemplate.generateYangSnipet(schemaNodes));
2053 sb.append("</pre>");
2054 sb.append(NEW_LINE);
2057 return replaceAllIllegalChars(sb);
2060 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2061 final StringBuilder sb = new StringBuilder();
2062 final String formattedDescription = YangTemplate.formatToParagraph(schemaNode.getDescription(), 0);
2064 if (!Strings.isNullOrEmpty(formattedDescription)) {
2065 sb.append(formattedDescription);
2066 sb.append(NEW_LINE);
2069 if (verboseClassComments) {
2070 final Module module = findParentModule(schemaContext, schemaNode);
2071 final StringBuilder linkToBuilderClass = new StringBuilder();
2072 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2073 final String className = namespace[namespace.length - 1];
2075 if (hasBuilderClass(schemaNode)) {
2076 linkToBuilderClass.append(className);
2077 linkToBuilderClass.append("Builder");
2081 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2082 sb.append(module.getName());
2084 sb.append(NEW_LINE);
2085 sb.append("<br>(Source path: <i>");
2086 sb.append(module.getModuleSourcePath());
2087 sb.append("</i>):");
2088 sb.append(NEW_LINE);
2090 sb.append(NEW_LINE);
2091 sb.append(YangTemplate.generateYangSnipet(schemaNode));
2092 sb.append("</pre>");
2093 sb.append(NEW_LINE);
2094 sb.append("The schema path to identify an instance is");
2095 sb.append(NEW_LINE);
2097 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2099 sb.append(NEW_LINE);
2101 if (hasBuilderClass(schemaNode)) {
2102 sb.append(NEW_LINE);
2103 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2104 sb.append(NEW_LINE);
2106 sb.append(linkToBuilderClass);
2107 sb.append(NEW_LINE);
2108 if (schemaNode instanceof ListSchemaNode) {
2109 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2110 if (keyDef != null && !keyDef.isEmpty()) {
2112 sb.append(className);
2115 sb.append(NEW_LINE);
2120 return replaceAllIllegalChars(sb);
2123 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2124 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2125 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2131 private String createDescription(final Module module) {
2132 final StringBuilder sb = new StringBuilder();
2133 final String formattedDescription = YangTemplate.formatToParagraph(module.getDescription(), 0);
2135 if (!Strings.isNullOrEmpty(formattedDescription)) {
2136 sb.append(formattedDescription);
2137 sb.append(NEW_LINE);
2140 if (verboseClassComments) {
2142 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2143 sb.append(module.getName());
2145 sb.append(NEW_LINE);
2146 sb.append("<br>Source path: <i>");
2147 sb.append(module.getModuleSourcePath());
2148 sb.append("</i>):");
2149 sb.append(NEW_LINE);
2151 sb.append(NEW_LINE);
2152 sb.append(YangTemplate.generateYangSnipet(module));
2153 sb.append("</pre>");
2156 return replaceAllIllegalChars(sb);
2159 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2160 for (final ModuleContext ctx : genCtx.values()) {
2161 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2162 if (result != null) {
2169 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2170 for (final ModuleContext ctx : genCtx.values()) {
2171 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2172 if (result != null) {
2179 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2180 for (final ModuleContext ctx : genCtx.values()) {
2181 final GeneratedTypeBuilder result = ctx.getCase(path);
2182 if (result != null) {
2189 public Map<Module, ModuleContext> getModuleContexts() {
2194 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2195 return UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");