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.packageNameForGeneratedType;
15 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_OBJECT;
16 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_ROOT;
17 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIABLE;
18 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIER;
19 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.NOTIFICATION;
20 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.augmentable;
21 import static org.opendaylight.yangtools.binding.generator.util.Types.BOOLEAN;
22 import static org.opendaylight.yangtools.binding.generator.util.Types.FUTURE;
23 import static org.opendaylight.yangtools.binding.generator.util.Types.VOID;
24 import static org.opendaylight.yangtools.binding.generator.util.Types.typeForClass;
25 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
26 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
28 import com.google.common.annotations.VisibleForTesting;
29 import com.google.common.base.Preconditions;
30 import com.google.common.base.Splitter;
31 import com.google.common.base.Strings;
32 import com.google.common.collect.Iterables;
33 import com.google.common.collect.Sets;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
42 import java.util.regex.Pattern;
43 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
44 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
45 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
46 import org.opendaylight.yangtools.binding.generator.util.Types;
47 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
48 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
49 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
50 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
51 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
52 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
53 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
54 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
55 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
56 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
57 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
58 import org.opendaylight.yangtools.sal.binding.model.api.Type;
59 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
60 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
61 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
62 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
66 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
67 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
68 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
69 import org.opendaylight.yangtools.yang.binding.BindingMapping;
70 import org.opendaylight.yangtools.yang.binding.DataContainer;
71 import org.opendaylight.yangtools.yang.binding.RpcService;
72 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
73 import org.opendaylight.yangtools.yang.common.QName;
74 import org.opendaylight.yangtools.yang.common.RpcResult;
75 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
76 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
77 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
80 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
83 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.Module;
88 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
89 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
90 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
91 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
92 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
94 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
95 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.UsesNode;
97 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
98 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
99 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
100 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
101 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
102 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
103 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
104 import org.opendaylight.yangtools.yang.model.util.UnionType;
105 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
106 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
107 import org.slf4j.Logger;
108 import org.slf4j.LoggerFactory;
110 public class BindingGeneratorImpl implements BindingGenerator {
111 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
112 private static final Splitter COLON_SPLITTER = Splitter.on(':');
113 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
114 private static final char NEW_LINE = '\n';
115 private static final String QNAME_FQCN = QName.class.getName();
118 * Constant with the concrete name of identifier.
120 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
123 * Constant with the concrete name of namespace.
125 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
127 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
129 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
132 * When set to true, generated classes will include javadoc comments which
133 * are useful for users.
135 private final boolean verboseClassComments;
138 * Outer key represents the package name. Outer value represents map of all
139 * builders in the same package. Inner key represents the schema node name
140 * (in JAVA class/interface name format). Inner value represents instance of
141 * builder for schema node specified in key part.
143 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
146 * Provide methods for converting YANG types to JAVA types.
148 private TypeProvider typeProvider;
151 * Holds reference to schema context to resolve data of augmented element
152 * when creating augmentation builder
154 private SchemaContext schemaContext;
157 * Create a new binding generator with verboe comments.
159 * @deprecated Use {@link #BindingGeneratorImpl(boolean)} instead.
162 public BindingGeneratorImpl() {
167 * Create a new binding generator.
169 * @param verboseClassComments generate verbose comments
171 public BindingGeneratorImpl(final boolean verboseClassComments) {
172 this.verboseClassComments = verboseClassComments;
176 * Resolves generated types from <code>context</code> schema nodes of all
179 * Generated types are created for modules, groupings, types, containers,
180 * lists, choices, augments, rpcs, notification, identities.
183 * schema context which contains data about all schema nodes
185 * @return list of types (usually <code>GeneratedType</code>
186 * <code>GeneratedTransferObject</code>which are generated from
187 * <code>context</code> data.
188 * @throws IllegalArgumentException
189 * if arg <code>context</code> is null
190 * @throws IllegalStateException
191 * if <code>context</code> contain no modules
194 public List<Type> generateTypes(final SchemaContext context) {
195 checkArgument(context != null, "Schema Context reference cannot be NULL.");
196 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
197 schemaContext = context;
198 typeProvider = new TypeProviderImpl(context);
199 final Set<Module> modules = context.getModules();
200 return generateTypes(context, modules);
204 * Resolves generated types from <code>context</code> schema nodes only for
205 * modules specified in <code>modules</code>
207 * Generated types are created for modules, groupings, types, containers,
208 * lists, choices, augments, rpcs, notification, identities.
211 * schema context which contains data about all schema nodes
214 * set of modules for which schema nodes should be generated
216 * @return list of types (usually <code>GeneratedType</code> or
217 * <code>GeneratedTransferObject</code>) which:
219 * <li>are generated from <code>context</code> schema nodes and</li>
220 * <li>are also part of some of the module in <code>modules</code>
223 * @throws IllegalArgumentException
225 * <li>if arg <code>context</code> is null or</li>
226 * <li>if arg <code>modules</code> is null</li>
228 * @throws IllegalStateException
229 * if <code>context</code> contain no modules
232 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
233 checkArgument(context != null, "Schema Context reference cannot be NULL.");
234 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
235 checkArgument(modules != null, "Set of Modules cannot be NULL.");
237 schemaContext = context;
238 typeProvider = new TypeProviderImpl(context);
239 final Module[] modulesArray = new Module[context.getModules().size()];
240 context.getModules().toArray(modulesArray);
241 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
242 genTypeBuilders = new HashMap<>();
244 for (final Module contextModule : contextModules) {
245 moduleToGenTypes(contextModule, context);
247 for (final Module contextModule : contextModules) {
248 allAugmentsToGenTypes(contextModule);
251 final List<Type> filteredGenTypes = new ArrayList<>();
252 for (final Module m : modules) {
253 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
254 filteredGenTypes.addAll(ctx.getGeneratedTypes());
255 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
256 if (additionalTypes != null) {
257 filteredGenTypes.addAll(additionalTypes);
261 return filteredGenTypes;
264 private void moduleToGenTypes(final Module m, final SchemaContext context) {
265 genCtx.put(m, new ModuleContext());
266 allTypeDefinitionsToGenTypes(m);
267 groupingsToGenTypes(m, m.getGroupings());
268 rpcMethodsToGenType(m);
269 allIdentitiesToGenTypes(m, context);
270 notificationsToGenType(m);
272 if (!m.getChildNodes().isEmpty()) {
273 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
274 genCtx.get(m).addModuleNode(moduleType);
275 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
276 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
281 * Converts all extended type definitions of module to the list of
282 * <code>Type</code> objects.
285 * module from which is obtained set of type definitions
286 * @throws IllegalArgumentException
288 * <li>if module is null</li>
289 * <li>if name of module is null</li>
291 * @throws IllegalStateException
292 * if set of type definitions from module is null
294 private void allTypeDefinitionsToGenTypes(final Module module) {
295 checkArgument(module != null, "Module reference cannot be NULL.");
296 checkArgument(module.getName() != null, "Module name cannot be NULL.");
297 final DataNodeIterator it = new DataNodeIterator(module);
298 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
299 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
301 for (final TypeDefinition<?> typedef : typeDefinitions) {
302 if (typedef != null) {
303 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
306 final ModuleContext ctx = genCtx.get(module);
307 ctx.addTypedefType(typedef.getPath(), type);
308 ctx.addTypeToSchema(type,typedef);
314 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
315 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
316 if (node.isAugmenting() || node.isAddedByUses()) {
319 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
320 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
321 genType.addComment(node.getDescription());
322 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
323 genType.setModuleName(module.getName());
324 genType.setReference(node.getReference());
325 genType.setSchemaPath(node.getPath().getPathFromRoot());
326 if (node instanceof DataNodeContainer) {
327 genCtx.get(module).addChildNodeType(node, genType);
328 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
329 processUsesAugments((DataNodeContainer) node, module);
334 private void containerToGenType(final Module module, final String basePackageName,
335 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
336 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
337 if (genType != null) {
338 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType);
339 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
343 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
344 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
345 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
346 if (genType != null) {
347 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), Types.listTypeFor(genType));
349 final List<String> listKeys = listKeys(node);
350 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
351 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
352 if (genTOBuilder != null) {
353 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
354 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
355 genTOBuilder.addImplementsType(identifierMarker);
356 genType.addImplementsType(identifiableMarker);
359 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
360 if (!schemaNode.isAugmenting()) {
361 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
366 if (genTOBuilder != null) {
367 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
368 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
369 genTOBuilder.setSUID(prop);
372 typeBuildersToGenTypes(module, genType, genTOBuilder);
376 private void processUsesAugments(final DataNodeContainer node, final Module module) {
377 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
378 for (final UsesNode usesNode : node.getUses()) {
379 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
380 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
381 processUsesAugments(augment, module);
387 * Converts all <b>augmentation</b> of the module to the list
388 * <code>Type</code> objects.
391 * module from which is obtained list of all augmentation objects
392 * to iterate over them
393 * @throws IllegalArgumentException
395 * <li>if the module is null</li>
396 * <li>if the name of module is null</li>
398 * @throws IllegalStateException
399 * if set of augmentations from module is null
401 private void allAugmentsToGenTypes(final Module module) {
402 checkArgument(module != null, "Module reference cannot be NULL.");
403 checkArgument(module.getName() != null, "Module name cannot be NULL.");
404 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
406 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
407 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
408 for (final AugmentationSchema augment : augmentations) {
409 augmentationToGenTypes(basePackageName, augment, module);
414 * Returns list of <code>AugmentationSchema</code> objects. The objects are
415 * sorted according to the length of their target path from the shortest to
419 * module from which is obtained list of all augmentation objects
420 * @return list of sorted <code>AugmentationSchema</code> objects obtained
421 * from <code>module</code>
422 * @throws IllegalArgumentException
424 * @throws IllegalStateException
425 * if set of module augmentations is null
427 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
428 checkArgument(module != null, "Module reference cannot be NULL.");
429 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
431 final Set<AugmentationSchema> augmentations = module.getAugmentations();
432 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
433 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
435 return sortedAugmentations;
439 * Create GeneratedTypeBuilder object from module argument.
442 * Module object from which builder will be created
443 * @return <code>GeneratedTypeBuilder</code> which is internal
444 * representation of the module
445 * @throws IllegalArgumentException
448 private GeneratedTypeBuilder moduleToDataType(final Module module) {
449 checkArgument(module != null, "Module reference cannot be NULL.");
451 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
452 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
453 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
454 moduleDataTypeBuilder.addComment(module.getDescription());
455 moduleDataTypeBuilder.setDescription(createDescription(module));
456 moduleDataTypeBuilder.setReference(module.getReference());
457 return moduleDataTypeBuilder;
461 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
462 * to the list of <code>Type</code> objects. In addition are to containers
463 * and lists which belong to input or output also part of returning list.
466 * module from which is obtained set of all rpc objects to
468 * @throws IllegalArgumentException
470 * <li>if the module is null</li>
471 * <li>if the name of module is null</li>
473 * @throws IllegalStateException
474 * if set of rpcs from module is null
476 private void rpcMethodsToGenType(final Module module) {
477 checkArgument(module != null, "Module reference cannot be NULL.");
478 checkArgument(module.getName() != null, "Module name cannot be NULL.");
479 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
480 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
481 if (rpcDefinitions.isEmpty()) {
485 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
486 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
487 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
488 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
490 for (final RpcDefinition rpc : rpcDefinitions) {
492 final String rpcName = BindingMapping.getClassName(rpc.getQName());
493 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
494 final String rpcComment = rpc.getDescription();
495 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
496 final ContainerSchemaNode input = rpc.getInput();
497 final ContainerSchemaNode output = rpc.getOutput();
500 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
501 addImplementedInterfaceFromUses(input, inType);
502 inType.addImplementsType(DATA_OBJECT);
503 inType.addImplementsType(augmentable(inType));
504 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
505 genCtx.get(module).addChildNodeType(input, inType);
506 final GeneratedType inTypeInstance = inType.toInstance();
507 method.addParameter(inTypeInstance, "input");
510 Type outTypeInstance = VOID;
511 if (output != null) {
512 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
513 addImplementedInterfaceFromUses(output, outType);
514 outType.addImplementsType(DATA_OBJECT);
515 outType.addImplementsType(augmentable(outType));
516 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
517 genCtx.get(module).addChildNodeType(output, outType);
518 outTypeInstance = outType.toInstance();
521 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
522 method.setComment(rpcComment);
523 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
527 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
531 * Converts all <b>notifications</b> of the module to the list of
532 * <code>Type</code> objects. In addition are to this list added containers
533 * and lists which are part of this notification.
536 * module from which is obtained set of all notification objects
537 * to iterate over them
538 * @throws IllegalArgumentException
540 * <li>if the module equals null</li>
541 * <li>if the name of module equals null</li>
543 * @throws IllegalStateException
544 * if set of notifications from module is null
546 private void notificationsToGenType(final Module module) {
547 checkArgument(module != null, "Module reference cannot be NULL.");
548 checkArgument(module.getName() != null, "Module name cannot be NULL.");
549 final Set<NotificationDefinition> notifications = module.getNotifications();
550 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
551 if (notifications.isEmpty()) {
555 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
556 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
557 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
561 for (final NotificationDefinition notification : notifications) {
562 if (notification != null) {
563 processUsesAugments(notification, module);
565 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
566 notification, null, module);
567 notificationInterface.addImplementsType(NOTIFICATION);
568 genCtx.get(module).addChildNodeType(notification, notificationInterface);
570 // Notification object
571 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
572 notification.getChildNodes());
574 listenerInterface.addMethod("on" + notificationInterface.getName())
575 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
576 .setComment(notification.getDescription()).setReturnType(Types.VOID);
579 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
581 genCtx.get(module).addTopLevelNodeType(listenerInterface);
585 * Converts all <b>identities</b> of the module to the list of
586 * <code>Type</code> objects.
589 * module from which is obtained set of all identity objects to
592 * schema context only used as input parameter for method
593 * {@link identityToGenType}
596 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
597 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
598 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
600 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
601 for (final IdentitySchemaNode identity : schemaIdentities) {
602 identityToGenType(module, basePackageName, identity, context);
608 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
609 * created transport object builder. If identity contains base identity then
610 * reference to base identity is added to superior identity as its extend.
611 * If identity doesn't contain base identity then only reference to abstract
612 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
613 * BaseIdentity} is added
617 * @param basePackageName
618 * string contains the module package name
620 * IdentitySchemaNode which contains data about identity
622 * SchemaContext which is used to get package and name
623 * information about base of identity
626 private void identityToGenType(final Module module, final String basePackageName,
627 final IdentitySchemaNode identity, final SchemaContext context) {
628 if (identity == null) {
631 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
632 final String genTypeName = BindingMapping.getClassName(identity.getQName());
633 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
634 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
635 if (baseIdentity == null) {
636 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
637 BaseIdentity.class.getSimpleName());
638 newType.setExtendsType(gto.toInstance());
640 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
641 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
643 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
644 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
646 newType.setExtendsType(gto);
648 newType.setAbstract(true);
649 newType.addComment(identity.getDescription());
650 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
651 newType.setReference(identity.getReference());
652 newType.setModuleName(module.getName());
653 newType.setSchemaPath(identity.getPath().getPathFromRoot());
655 final QName qname = identity.getQName();
656 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
658 genCtx.get(module).addIdentityType(identity.getQName(), newType);
661 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
663 final StringBuilder sb = new StringBuilder(QNAME_FQCN);
664 sb.append(".cachedReference(");
665 sb.append(QNAME_FQCN);
666 sb.append(".create(");
668 sb.append(name.getNamespace());
670 sb.append(name.getFormattedRevision());
672 sb.append(name.getLocalName());
675 return toBuilder.addConstant(typeForClass(QName.class), constantName, sb.toString());
679 * Converts all <b>groupings</b> of the module to the list of
680 * <code>Type</code> objects. Firstly are groupings sorted according mutual
681 * dependencies. At least dependent (independent) groupings are in the list
682 * saved at first positions. For every grouping the record is added to map
683 * {@link BindingGeneratorImpl#allGroupings allGroupings}
688 * of groupings from which types will be generated
691 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
692 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
693 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
695 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
696 groupingToGenType(basePackageName, grouping, module);
701 * Converts individual grouping to GeneratedType. Firstly generated type
702 * builder is created and every child node of grouping is resolved to the
705 * @param basePackageName
706 * string contains the module package name
708 * GroupingDefinition which contains data about grouping
711 * @return GeneratedType which is generated from grouping (object of type
712 * <code>GroupingDefinition</code>)
714 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
715 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
716 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
717 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
718 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
719 groupingsToGenTypes(module, grouping.getGroupings());
720 processUsesAugments(grouping, module);
724 * Adds enumeration builder created from <code>enumTypeDef</code> to
725 * <code>typeBuilder</code>.
727 * Each <code>enumTypeDef</code> item is added to builder with its name and
731 * EnumTypeDefinition contains enum data
733 * string contains name which will be assigned to enumeration
736 * GeneratedTypeBuilder to which will be enum builder assigned
738 * Module in which type should be generated
739 * @return enumeration builder which contains data from
740 * <code>enumTypeDef</code>
742 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
743 final GeneratedTypeBuilder typeBuilder, final Module module) {
744 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
745 && (enumTypeDef.getQName().getLocalName() != null)) {
746 final String enumerationName = BindingMapping.getClassName(enumName);
747 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
748 enumBuilder.setDescription(enumTypeDef.getDescription());
749 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
750 ModuleContext ctx = genCtx.get(module);
751 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
758 * Generates type builder for <code>module</code>.
761 * Module which is source of package name for generated type
764 * string which is added to the module class name representation
766 * @return instance of GeneratedTypeBuilder which represents
767 * <code>module</code>.
768 * @throws IllegalArgumentException
769 * if <code>module</code> is null
771 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
772 checkArgument(module != null, "Module reference cannot be NULL.");
773 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
774 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
776 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
777 moduleBuilder.setDescription(createDescription(module));
778 moduleBuilder.setReference(module.getReference());
779 moduleBuilder.setModuleName(moduleName);
781 return moduleBuilder;
785 * Converts <code>augSchema</code> to list of <code>Type</code> which
786 * contains generated type for augmentation. In addition there are also
787 * generated types for all containers, list and choices which are child of
788 * <code>augSchema</code> node or a generated types for cases are added if
789 * augmented node is choice.
791 * @param augmentPackageName
792 * string with the name of the package to which the augmentation
795 * AugmentationSchema which is contains data about augmentation
796 * (target path, childs...)
799 * @param parentUsesNode
800 * @throws IllegalArgumentException
802 * <li>if <code>augmentPackageName</code> equals null</li>
803 * <li>if <code>augSchema</code> equals null</li>
805 * @throws IllegalStateException
806 * if augment target path is null
808 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
809 final Module module) {
810 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
811 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
812 checkState(augSchema.getTargetPath() != null,
813 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
815 processUsesAugments(augSchema, module);
816 final SchemaPath targetPath = augSchema.getTargetPath();
817 SchemaNode targetSchemaNode = null;
819 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
820 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
821 if (targetSchemaNode instanceof DerivableSchemaNode) {
822 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
824 if (targetSchemaNode == null) {
825 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
826 + " in module " + module.getName());
829 if (targetSchemaNode == null) {
830 throw new IllegalArgumentException("augment target not found: " + targetPath);
833 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
834 if (targetTypeBuilder == null) {
835 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
837 if (targetTypeBuilder == null) {
838 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
841 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
842 final String packageName = augmentPackageName;
843 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
844 targetTypeBuilder.getName());
845 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
848 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
849 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
853 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
854 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
855 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
856 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
857 checkState(augSchema.getTargetPath() != null,
858 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
860 processUsesAugments(augSchema, module);
861 final SchemaPath targetPath = augSchema.getTargetPath();
862 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
863 if (targetSchemaNode == null) {
864 throw new IllegalArgumentException("augment target not found: " + targetPath);
867 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
868 if (targetTypeBuilder == null) {
869 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
871 if (targetTypeBuilder == null) {
872 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
875 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
876 String packageName = augmentPackageName;
877 if (usesNodeParent instanceof SchemaNode) {
878 packageName = packageNameForGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath(),
881 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
884 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
885 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
890 * Convenient method to find node added by uses statement.
894 * @param parentUsesNode
895 * parent of uses node
896 * @return node from its original location in grouping
898 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
899 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
901 if (!(targetGrouping instanceof GroupingDefinition)) {
902 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
905 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
906 SchemaNode result = grouping;
907 for (final QName node : targetPath.getPathFromRoot()) {
908 // finding by local name is valid, grouping cannot contain nodes
909 // with same name and different namespace
910 if (result instanceof DataNodeContainer) {
911 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
912 } else if (result instanceof ChoiceSchemaNode) {
913 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
916 if (result == null) {
920 boolean fromUses = ((DataSchemaNode) result).isAddedByUses();
921 final Iterator<UsesNode> groupingUses = grouping.getUses().iterator();
922 while (groupingUses.hasNext() && fromUses) {
923 result = findOriginalTargetFromGrouping(targetPath, groupingUses.next());
924 if (result != null) {
925 fromUses = ((DataSchemaNode) result).isAddedByUses();
929 // this indicates invalid yang and thus possible bug in code because
930 // invalid yang should be already spotted by parser
931 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
934 return (DataSchemaNode) result;
938 * Returns a generated type builder for an augmentation.
940 * The name of the type builder is equal to the name of augmented node with
941 * serial number as suffix.
945 * @param augmentPackageName
946 * string with contains the package name to which the augment
948 * @param basePackageName
949 * string with the package name to which the augmented node
951 * @param targetTypeRef
954 * augmentation schema which contains data about the child nodes
955 * and uses of augment
956 * @return generated type builder for augment
958 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
959 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
960 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
961 if (augmentBuilders == null) {
962 augmentBuilders = new HashMap<>();
963 genTypeBuilders.put(augmentPackageName, augmentBuilders);
965 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
968 if (augIdentifier != null) {
969 augTypeName = BindingMapping.getClassName(augIdentifier);
971 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
974 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
976 augTypeBuilder.addImplementsType(DATA_OBJECT);
977 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
978 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
980 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
981 augmentBuilders.put(augTypeName, augTypeBuilder);
983 if(!augSchema.getChildNodes().isEmpty()) {
984 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
985 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
988 genCtx.get(module).addAugmentType(augTypeBuilder);
989 return augTypeBuilder;
994 * @param unknownSchemaNodes
995 * @return nodeParameter of UnknownSchemaNode
997 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
998 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
999 final QName nodeType = unknownSchemaNode.getNodeType();
1000 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1001 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1002 return unknownSchemaNode.getNodeParameter();
1009 * Returns first unique name for the augment generated type builder. The
1010 * generated type builder name for augment consists from name of augmented
1011 * node and serial number of its augmentation.
1014 * map of builders which were created in the package to which the
1015 * augmentation belongs
1016 * @param genTypeName
1017 * string with name of augmented node
1018 * @return string with unique name for augmentation builder
1020 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1022 if (builders != null) {
1023 while (builders.containsKey(genTypeName + index)) {
1027 return genTypeName + index;
1031 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1032 * node for which <code>typeBuilder</code> was created.
1034 * The subnodes aren't mapped to the methods if they are part of grouping or
1035 * augment (in this case are already part of them).
1039 * @param basePackageName
1040 * string contains the module package name
1042 * generated type builder which represents any node. The subnodes
1043 * of this node are added to the <code>typeBuilder</code> as
1044 * methods. The subnode can be of type leaf, leaf-list, list,
1045 * container, choice.
1048 * @param schemaNodes
1049 * set of data schema nodes which are the children of the node
1050 * for which <code>typeBuilder</code> was created
1051 * @return generated type builder which is the same builder as input
1052 * parameter. The getter methods (representing child nodes) could be
1055 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1056 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1057 if (schemaNodes != null && parent != null) {
1058 for (final DataSchemaNode schemaNode : schemaNodes) {
1059 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1060 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1068 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1069 * node for which <code>typeBuilder</code> was created.
1073 * @param basePackageName
1074 * string contains the module package name
1075 * @param typeBuilder
1076 * generated type builder which represents any node. The subnodes
1077 * of this node are added to the <code>typeBuilder</code> as
1078 * methods. The subnode can be of type leaf, leaf-list, list,
1079 * container, choice.
1082 * @param schemaNodes
1083 * set of data schema nodes which are the children of the node
1084 * for which <code>typeBuilder</code> was created
1085 * @return generated type builder which is the same object as the input
1086 * parameter <code>typeBuilder</code>. The getter method could be
1089 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1090 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1091 final Iterable<DataSchemaNode> schemaNodes) {
1092 if ((schemaNodes != null) && (typeBuilder != null)) {
1093 for (final DataSchemaNode schemaNode : schemaNodes) {
1094 if (!schemaNode.isAugmenting()) {
1095 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1103 * Adds to <code>typeBuilder</code> a method which is derived from
1104 * <code>schemaNode</code>.
1106 * @param basePackageName
1107 * string with the module package name
1109 * data schema node which is added to <code>typeBuilder</code> as
1111 * @param typeBuilder
1112 * generated type builder to which is <code>schemaNode</code>
1113 * added as a method.
1119 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1120 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1121 if (node != null && typeBuilder != null) {
1122 if (node instanceof LeafSchemaNode) {
1123 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1124 } else if (node instanceof LeafListSchemaNode) {
1125 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1126 } else if (node instanceof ContainerSchemaNode) {
1127 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1128 } else if (node instanceof ListSchemaNode) {
1129 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1130 } else if (node instanceof ChoiceSchemaNode) {
1131 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1133 // TODO: anyxml not yet supported
1134 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1135 typeBuilder.getFullyQualifiedName());
1141 * Converts <code>choiceNode</code> to the list of generated types for
1142 * choice and its cases.
1144 * The package names for choice and for its cases are created as
1145 * concatenation of the module package (<code>basePackageName</code>) and
1146 * names of all parents node.
1150 * @param basePackageName
1151 * string with the module package name
1155 * choice node which is mapped to generated type. Also child
1156 * nodes - cases are mapped to generated types.
1157 * @throws IllegalArgumentException
1159 * <li>if <code>basePackageName</code> is null</li>
1160 * <li>if <code>choiceNode</code> is null</li>
1163 private void choiceToGeneratedType(final Module module, final String basePackageName,
1164 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1165 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1166 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1168 if (!choiceNode.isAddedByUses()) {
1169 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1170 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1171 constructGetter(parent, choiceNode.getQName().getLocalName(), choiceNode.getDescription(),
1173 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1174 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1175 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1180 * Converts <code>caseNodes</code> set to list of corresponding generated
1183 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1184 * created generated type builder. The package names for the builder is
1185 * created as concatenation of the module package (
1186 * <code>basePackageName</code>) and names of all parents nodes of the
1187 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1188 * between every case builder and <i>choice</i> type
1192 * @param basePackageName
1193 * string with the module package name
1194 * @param refChoiceType
1195 * type which represents superior <i>case</i>
1197 * choice case node which is mapped to generated type
1198 * @return list of generated types for <code>caseNodes</code>.
1199 * @throws IllegalArgumentException
1201 * <li>if <code>basePackageName</code> equals null</li>
1202 * <li>if <code>refChoiceType</code> equals null</li>
1203 * <li>if <code>caseNodes</code> equals null</li>
1206 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1207 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1208 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1209 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1210 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1212 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1213 if (caseNodes == null) {
1217 for (final ChoiceCaseNode caseNode : caseNodes) {
1218 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1219 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1220 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1221 caseTypeBuilder.addImplementsType(refChoiceType);
1222 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1223 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1224 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1225 if (caseChildNodes != null) {
1226 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1228 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1229 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1231 if (parent instanceof AugmentationSchema) {
1232 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1233 final SchemaPath targetPath = augSchema.getTargetPath();
1234 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1235 if (targetSchemaNode instanceof DataSchemaNode
1236 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1237 if (targetSchemaNode instanceof DerivableSchemaNode) {
1238 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1240 if (targetSchemaNode == null) {
1241 throw new IllegalStateException(
1242 "Failed to find target node from grouping for augmentation " + augSchema
1243 + " in module " + module.getName());
1246 parent = targetSchemaNode;
1249 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1250 choiceNodeParentPath);
1251 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1252 if (childOfType == null) {
1253 childOfType = findGroupingByPath(parent.getPath());
1255 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1257 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1262 processUsesAugments(caseNode, module);
1267 * Generates list of generated types for all the cases of a choice which are
1268 * added to the choice through the augment.
1272 * @param basePackageName
1273 * string contains name of package to which augment belongs. If
1274 * an augmented choice is from an other package (pcg1) than an
1275 * augmenting choice (pcg2) then case's of the augmenting choice
1276 * will belong to pcg2.
1278 * Type which represents target choice
1280 * node which represents target choice
1281 * @param augmentedNodes
1282 * set of choice case nodes for which is checked if are/aren't
1283 * added to choice through augmentation
1284 * @return list of generated types which represents augmented cases of
1285 * choice <code>refChoiceType</code>
1286 * @throws IllegalArgumentException
1288 * <li>if <code>basePackageName</code> is null</li>
1289 * <li>if <code>targetType</code> is null</li>
1290 * <li>if <code>augmentedNodes</code> is null</li>
1293 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1294 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
1295 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1296 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1297 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1299 for (final DataSchemaNode caseNode : augmentedNodes) {
1300 if (caseNode != null) {
1301 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1302 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1303 caseTypeBuilder.addImplementsType(targetType);
1305 SchemaNode parent = null;
1306 final SchemaPath nodeSp = targetNode.getPath();
1307 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1309 GeneratedTypeBuilder childOfType = null;
1310 if (parent instanceof Module) {
1311 childOfType = genCtx.get(parent).getModuleNode();
1312 } else if (parent instanceof ChoiceCaseNode) {
1313 childOfType = findCaseByPath(parent.getPath());
1314 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1315 childOfType = findChildNodeByPath(parent.getPath());
1316 } else if (parent instanceof GroupingDefinition) {
1317 childOfType = findGroupingByPath(parent.getPath());
1320 if (childOfType == null) {
1321 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1324 ChoiceCaseNode node = null;
1325 if (caseNode instanceof ChoiceCaseNode) {
1326 node = (ChoiceCaseNode) caseNode;
1328 node = targetNode.getCaseNodeByName(caseNode.getQName().getLocalName());
1330 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1331 if (childNodes != null) {
1332 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1334 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1335 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1341 * Converts <code>leaf</code> to the getter method which is added to
1342 * <code>typeBuilder</code>.
1344 * @param typeBuilder
1345 * generated type builder to which is added getter method as
1346 * <code>leaf</code> mapping
1348 * leaf schema node which is mapped as getter method which is
1349 * added to <code>typeBuilder</code>
1351 * Module in which type was defined
1352 * @return boolean value
1354 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1356 * <li>true - in other cases</li>
1359 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1360 Type returnType = null;
1361 if ((leaf != null) && (typeBuilder != null)) {
1362 final String leafName = leaf.getQName().getLocalName();
1363 String leafDesc = leaf.getDescription();
1364 if (leafDesc == null) {
1368 final Module parentModule = findParentModule(schemaContext, leaf);
1369 if (leafName != null && !leaf.isAddedByUses()) {
1370 final TypeDefinition<?> typeDef = leaf.getType();
1372 GeneratedTOBuilder genTOBuilder;
1373 if (typeDef instanceof EnumTypeDefinition) {
1374 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1375 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1376 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1377 typeBuilder,module);
1379 if (enumBuilder != null) {
1380 returnType = enumBuilder.toInstance(typeBuilder);
1382 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1383 } else if (typeDef instanceof UnionType) {
1384 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1385 if (genTOBuilder != null) {
1386 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1388 } else if (typeDef instanceof BitsTypeDefinition) {
1389 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1390 if (genTOBuilder != null) {
1391 returnType = genTOBuilder.toInstance();
1394 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1395 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1397 if (returnType != null) {
1398 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1399 processContextRefExtension(leaf, getter, parentModule);
1406 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1407 final Module module) {
1408 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1409 final QName nodeType = node.getNodeType();
1410 if ("context-reference".equals(nodeType.getLocalName())) {
1411 final String nodeParam = node.getNodeParameter();
1412 IdentitySchemaNode identity = null;
1413 String basePackageName = null;
1414 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1415 final Iterator<String> iterator = splittedElement.iterator();
1416 final int length = Iterables.size(splittedElement);
1418 identity = findIdentityByName(module.getIdentities(), iterator.next());
1419 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1420 } else if (length == 2) {
1421 final String prefix = iterator.next();
1422 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1423 if (dependentModule == null) {
1424 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1427 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1428 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1430 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1433 if (identity == null) {
1434 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1438 final Class<RoutingContext> clazz = RoutingContext.class;
1439 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1440 clazz.getSimpleName());
1441 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1442 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1443 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1448 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1449 for (final IdentitySchemaNode id : identities) {
1450 if (id.getQName().getLocalName().equals(name)) {
1457 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1458 for (final ModuleImport imp : imports) {
1459 if (imp.getPrefix().equals(prefix)) {
1460 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1466 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1467 final boolean isReadOnly, final Module module) {
1468 if ((leaf != null) && (toBuilder != null)) {
1469 final String leafName = leaf.getQName().getLocalName();
1470 String leafDesc = leaf.getDescription();
1471 if (leafDesc == null) {
1474 Type returnType = null;
1475 final TypeDefinition<?> typeDef = leaf.getType();
1476 if (typeDef instanceof UnionTypeDefinition) {
1477 // GeneratedType for this type definition should be already
1479 final QName qname = typeDef.getQName();
1480 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1481 qname.getRevision());
1482 final ModuleContext mc = genCtx.get(unionModule);
1483 returnType = mc.getTypedefs().get(typeDef.getPath());
1484 } else if (typeDef instanceof EnumTypeDefinition && BaseTypes.ENUMERATION_QNAME.equals(typeDef.getQName())) {
1485 // Annonymous enumeration (already generated, since it is inherited via uses).
1486 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1487 QName qname = originalLeaf.getQName();
1488 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1489 qname.getRevision());
1490 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1492 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1494 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1500 * Converts <code>leaf</code> schema node to property of generated TO
1504 * generated TO builder to which is <code>leaf</code> added as
1507 * leaf schema node which is added to <code>toBuilder</code> as
1512 * boolean value which says if leaf property is|isn't read only
1513 * @return boolean value
1515 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1516 * name equals null or if leaf is added by <i>uses</i>.</li>
1517 * <li>true - other cases</li>
1520 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1521 final Type returnType, final boolean isReadOnly) {
1522 if (returnType == null) {
1525 final String leafName = leaf.getQName().getLocalName();
1526 final String leafDesc = leaf.getDescription();
1527 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1528 propBuilder.setReadOnly(isReadOnly);
1529 propBuilder.setReturnType(returnType);
1530 propBuilder.setComment(leafDesc);
1531 toBuilder.addEqualsIdentity(propBuilder);
1532 toBuilder.addHashIdentity(propBuilder);
1533 toBuilder.addToStringProperty(propBuilder);
1538 * Converts <code>node</code> leaf list schema node to getter method of
1539 * <code>typeBuilder</code>.
1541 * @param typeBuilder
1542 * generated type builder to which is <code>node</code> added as
1545 * leaf list schema node which is added to
1546 * <code>typeBuilder</code> as getter method
1548 * @return boolean value
1550 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1551 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1552 * <li>false - other cases</li>
1555 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1556 if ((node != null) && (typeBuilder != null)) {
1557 final QName nodeName = node.getQName();
1559 if (nodeName != null && !node.isAddedByUses()) {
1560 final TypeDefinition<?> typeDef = node.getType();
1561 final Module parentModule = findParentModule(schemaContext, node);
1563 Type returnType = null;
1564 if (typeDef instanceof EnumTypeDefinition) {
1565 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1566 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1567 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1568 typeBuilder,module);
1569 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1570 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1571 } else if (typeDef instanceof UnionType) {
1572 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1573 if (genTOBuilder != null) {
1574 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1576 } else if (typeDef instanceof BitsTypeDefinition) {
1577 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1578 returnType = genTOBuilder.toInstance();
1580 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1581 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1584 final ParameterizedType listType = Types.listTypeFor(returnType);
1585 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1592 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1593 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1594 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1595 genTOBuilder.getName());
1597 returnType.setDescription(typeDef.getDescription());
1598 returnType.setReference(typeDef.getReference());
1599 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1600 returnType.setModuleName(parentModule.getName());
1602 genTOBuilder.setTypedef(true);
1603 genTOBuilder.setIsUnion(true);
1604 ((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1608 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1611 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1612 method.setReturnType(returnType);
1613 method.addParameter(Types.STRING, "defaultValue");
1614 method.setAccessModifier(AccessModifier.PUBLIC);
1615 method.setStatic(true);
1617 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1618 if (types == null) {
1619 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1620 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1622 types.add(unionBuilder.toInstance());
1624 return returnType.toInstance();
1627 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1628 final String outerCls = Types.getOuterClassName(genTOBuilder);
1629 final StringBuilder name;
1630 if (outerCls != null) {
1631 name = new StringBuilder(outerCls);
1633 name = new StringBuilder();
1635 name.append(genTOBuilder.getName());
1636 name.append("Builder");
1637 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1638 unionBuilder.setIsUnionBuilder(true);
1639 return unionBuilder;
1642 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1643 final Module module) {
1644 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1648 * Instantiates generated type builder with <code>packageName</code> and
1649 * <code>schemaNode</code>.
1651 * The new builder always implements
1652 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1653 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1654 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1656 * If <code>schemaNode</code> is instance of
1657 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1658 * DataNodeContainer} it can also implement nodes which are specified in
1661 * @param packageName
1662 * string with the name of the package to which
1663 * <code>schemaNode</code> belongs.
1665 * schema node for which is created generated type builder
1667 * parent type (can be null)
1668 * @return generated type builder <code>schemaNode</code>
1670 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1671 final Type parent, final Module module) {
1672 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1673 if (parent == null) {
1674 it.addImplementsType(DATA_OBJECT);
1676 it.addImplementsType(BindingTypes.childOf(parent));
1678 if (!(schemaNode instanceof GroupingDefinition)) {
1679 it.addImplementsType(augmentable(it));
1682 if (schemaNode instanceof DataNodeContainer) {
1683 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1684 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1691 * Wraps the calling of the same overloaded method.
1693 * @param packageName
1694 * string with the package name to which returning generated type
1697 * schema node which provide data about the schema node name
1698 * @return generated type builder for <code>schemaNode</code>
1700 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1701 return addRawInterfaceDefinition(packageName, schemaNode, "");
1705 * Returns reference to generated type builder for specified
1706 * <code>schemaNode</code> with <code>packageName</code>.
1708 * Firstly the generated type builder is searched in
1709 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1710 * found it is created and added to <code>genTypeBuilders</code>.
1712 * @param packageName
1713 * string with the package name to which returning generated type
1716 * schema node which provide data about the schema node name
1718 * return type name prefix
1719 * @return generated type builder for <code>schemaNode</code>
1720 * @throws IllegalArgumentException
1722 * <li>if <code>schemaNode</code> is null</li>
1723 * <li>if <code>packageName</code> is null</li>
1724 * <li>if QName of schema node is null</li>
1725 * <li>if schemaNode name is null</li>
1729 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1730 final String prefix) {
1731 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1732 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1733 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1734 final String schemaNodeName = schemaNode.getQName().getLocalName();
1735 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1738 if (prefix == null) {
1739 genTypeName = BindingMapping.getClassName(schemaNodeName);
1741 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1744 // FIXME: Validation of name conflict
1745 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1746 final Module module = findParentModule(schemaContext, schemaNode);
1747 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1748 newType.addComment(schemaNode.getDescription());
1749 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1750 newType.setReference(schemaNode.getReference());
1751 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1752 newType.setModuleName(module.getName());
1754 if (!genTypeBuilders.containsKey(packageName)) {
1755 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1756 builders.put(genTypeName, newType);
1757 genTypeBuilders.put(packageName, builders);
1759 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1760 if (!builders.containsKey(genTypeName)) {
1761 builders.put(genTypeName, newType);
1768 * Creates the name of the getter method name from <code>localName</code>.
1771 * string with the name of the getter method
1774 * @return string with the name of the getter method for
1775 * <code>methodName</code> in JAVA method format
1777 public static String getterMethodName(final String localName, final Type returnType) {
1778 final StringBuilder method = new StringBuilder();
1779 if (BOOLEAN.equals(returnType)) {
1780 method.append("is");
1782 method.append("get");
1784 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1785 method.append(name);
1786 return method.toString();
1790 * Created a method signature builder as part of
1791 * <code>interfaceBuilder</code>.
1793 * The method signature builder is created for the getter method of
1794 * <code>schemaNodeName</code>. Also <code>comment</code> and
1795 * <code>returnType</code> information are added to the builder.
1797 * @param interfaceBuilder
1798 * generated type builder for which the getter method should be
1800 * @param schemaNodeName
1801 * string with schema node name. The name will be the part of the
1802 * getter method name.
1804 * string with comment for the getter method
1806 * type which represents the return type of the getter method
1807 * @return method signature builder which represents the getter method of
1808 * <code>interfaceBuilder</code>
1810 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1811 final String schemaNodeName, final String comment, final Type returnType) {
1812 final MethodSignatureBuilder getMethod = interfaceBuilder
1813 .addMethod(getterMethodName(schemaNodeName, returnType));
1814 getMethod.setComment(comment);
1815 getMethod.setReturnType(returnType);
1820 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1821 * or to <code>genTOBuilder</code> as property.
1823 * @param basePackageName
1824 * string contains the module package name
1826 * data schema node which should be added as getter method to
1827 * <code>typeBuilder</code> or as a property to
1828 * <code>genTOBuilder</code> if is part of the list key
1829 * @param typeBuilder
1830 * generated type builder for the list schema node
1831 * @param genTOBuilder
1832 * generated TO builder for the list keys
1834 * list of string which contains names of the list keys
1837 * @throws IllegalArgumentException
1839 * <li>if <code>schemaNode</code> equals null</li>
1840 * <li>if <code>typeBuilder</code> equals null</li>
1843 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1844 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1845 final Module module) {
1846 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1847 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1849 if (schemaNode instanceof LeafSchemaNode) {
1850 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1851 final String leafName = leaf.getQName().getLocalName();
1852 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1853 if (listKeys.contains(leafName)) {
1855 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1857 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1860 } else if (!schemaNode.isAddedByUses()) {
1861 if (schemaNode instanceof LeafListSchemaNode) {
1862 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1863 } else if (schemaNode instanceof ContainerSchemaNode) {
1864 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1865 } else if (schemaNode instanceof ChoiceSchemaNode) {
1866 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1867 } else if (schemaNode instanceof ListSchemaNode) {
1868 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1873 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1874 final GeneratedTOBuilder genTOBuilder) {
1875 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1877 if (genTOBuilder != null) {
1878 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1879 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
1880 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1885 * Selects the names of the list keys from <code>list</code> and returns
1886 * them as the list of the strings
1889 * of string with names of the list keys
1890 * @return list of string which represents names of the list keys. If the
1891 * <code>list</code> contains no keys then the empty list is
1894 private static List<String> listKeys(final ListSchemaNode list) {
1895 final List<String> listKeys = new ArrayList<>();
1897 final List<QName> keyDefinition = list.getKeyDefinition();
1898 if (keyDefinition != null) {
1899 for (final QName keyDef : keyDefinition) {
1900 listKeys.add(keyDef.getLocalName());
1907 * Generates for the <code>list</code> which contains any list keys special
1908 * generated TO builder.
1910 * @param packageName
1911 * string with package name to which the list belongs
1913 * list schema node which is source of data about the list name
1914 * @return generated TO builder which represents the keys of the
1915 * <code>list</code> or null if <code>list</code> is null or list of
1916 * key definitions is null or empty.
1918 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1919 GeneratedTOBuilder genTOBuilder = null;
1920 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1921 final String listName = list.getQName().getLocalName() + "Key";
1922 final String genTOName = BindingMapping.getClassName(listName);
1923 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1925 return genTOBuilder;
1929 * Builds generated TO builders for <code>typeDef</code> of type
1930 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
1931 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
1932 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
1933 * enclosing transfer object.
1935 * If more then one generated TO builder is created for enclosing then all
1936 * of the generated TO builders are added to <code>typeBuilder</code> as
1937 * enclosing transfer objects.
1940 * type definition which can be of type <code>UnionType</code> or
1941 * <code>BitsTypeDefinition</code>
1942 * @param typeBuilder
1943 * generated type builder to which is added generated TO created
1944 * from <code>typeDef</code>
1946 * string with name for generated TO builder
1948 * @return generated TO builder for <code>typeDef</code>
1950 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
1951 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1952 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
1953 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
1954 final String packageName = typeBuilder.getFullyQualifiedName();
1955 if (typeDef instanceof UnionTypeDefinition) {
1956 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
1957 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
1958 classNameFromLeaf, leaf);
1959 genTOBuilders.addAll(types);
1961 GeneratedTOBuilder resultTOBuilder = null;
1962 if (types.isEmpty()) {
1963 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
1965 resultTOBuilder = types.remove(0);
1966 for (final GeneratedTOBuilder genTOBuilder : types) {
1967 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1970 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1971 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1972 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1973 resultTOBuilder.addHashIdentity(genPropBuilder);
1974 resultTOBuilder.addToStringProperty(genPropBuilder);
1976 } else if (typeDef instanceof BitsTypeDefinition) {
1977 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
1978 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
1980 if (genTOBuilders != null && !genTOBuilders.isEmpty()) {
1981 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1982 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1984 return genTOBuilders.get(0);
1991 * Adds the implemented types to type builder.
1993 * The method passes through the list of <i>uses</i> in
1994 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1995 * generated type from {@link BindingGeneratorImpl#allGroupings
1996 * allGroupings} which is added as <i>implements type</i> to
1997 * <code>builder</code>
1999 * @param dataNodeContainer
2000 * element which contains the list of used YANG groupings
2002 * builder to which are added implemented types according to
2003 * <code>dataNodeContainer</code>
2004 * @return generated type builder with all implemented types
2006 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2007 final GeneratedTypeBuilder builder) {
2008 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2009 if (usesNode.getGroupingPath() != null) {
2010 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2011 if (genType == null) {
2012 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2013 + builder.getName());
2016 builder.addImplementsType(genType);
2018 builder.addComment(genType.getDescription());
2019 builder.setDescription(genType.getDescription());
2020 builder.setModuleName(genType.getModuleName());
2021 builder.setReference(genType.getReference());
2022 builder.setSchemaPath(genType.getSchemaPath());
2029 private static boolean isNullOrEmpty(final Collection<?> list) {
2030 return list == null || list.isEmpty();
2033 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
2034 final StringBuilder sb = new StringBuilder();
2036 if (!isNullOrEmpty(schemaNodes)) {
2037 final SchemaNode node = schemaNodes.iterator().next();
2039 if (node instanceof RpcDefinition) {
2040 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2041 } else if (node instanceof NotificationDefinition) {
2042 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2045 sb.append(NEW_LINE);
2046 sb.append("<br>(Source path: <i>");
2047 sb.append(moduleSourcePath);
2048 sb.append("</i>):");
2049 sb.append(NEW_LINE);
2051 if (verboseClassComments) {
2053 sb.append(NEW_LINE);
2054 sb.append(YangTemplate.generateYangSnipet(schemaNodes));
2055 sb.append("</pre>");
2056 sb.append(NEW_LINE);
2059 return replaceAllIllegalChars(sb);
2062 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2063 final StringBuilder sb = new StringBuilder();
2064 final String formattedDescription = YangTemplate.formatToParagraph(schemaNode.getDescription(), 0);
2066 if (!Strings.isNullOrEmpty(formattedDescription)) {
2067 sb.append(formattedDescription);
2068 sb.append(NEW_LINE);
2071 if (verboseClassComments) {
2072 final Module module = findParentModule(schemaContext, schemaNode);
2073 final StringBuilder linkToBuilderClass = new StringBuilder();
2074 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2075 final String className = namespace[namespace.length - 1];
2077 if (hasBuilderClass(schemaNode)) {
2078 linkToBuilderClass.append(className);
2079 linkToBuilderClass.append("Builder");
2083 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2084 sb.append(module.getName());
2086 sb.append(NEW_LINE);
2087 sb.append("<br>(Source path: <i>");
2088 sb.append(module.getModuleSourcePath());
2089 sb.append("</i>):");
2090 sb.append(NEW_LINE);
2092 sb.append(NEW_LINE);
2093 sb.append(YangTemplate.generateYangSnipet(schemaNode));
2094 sb.append("</pre>");
2095 sb.append(NEW_LINE);
2096 sb.append("The schema path to identify an instance is");
2097 sb.append(NEW_LINE);
2099 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2101 sb.append(NEW_LINE);
2103 if (hasBuilderClass(schemaNode)) {
2104 sb.append(NEW_LINE);
2105 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2106 sb.append(NEW_LINE);
2108 sb.append(linkToBuilderClass);
2109 sb.append(NEW_LINE);
2110 if (schemaNode instanceof ListSchemaNode) {
2111 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2112 if (keyDef != null && !keyDef.isEmpty()) {
2114 sb.append(className);
2117 sb.append(NEW_LINE);
2122 return replaceAllIllegalChars(sb);
2125 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2126 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2127 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2133 private String createDescription(final Module module) {
2134 final StringBuilder sb = new StringBuilder();
2135 final String formattedDescription = YangTemplate.formatToParagraph(module.getDescription(), 0);
2137 if (!Strings.isNullOrEmpty(formattedDescription)) {
2138 sb.append(formattedDescription);
2139 sb.append(NEW_LINE);
2142 if (verboseClassComments) {
2144 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2145 sb.append(module.getName());
2147 sb.append(NEW_LINE);
2148 sb.append("<br>Source path: <i>");
2149 sb.append(module.getModuleSourcePath());
2150 sb.append("</i>):");
2151 sb.append(NEW_LINE);
2153 sb.append(NEW_LINE);
2154 sb.append(YangTemplate.generateYangSnipet(module));
2155 sb.append("</pre>");
2158 return replaceAllIllegalChars(sb);
2161 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2162 for (final ModuleContext ctx : genCtx.values()) {
2163 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2164 if (result != null) {
2171 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2172 for (final ModuleContext ctx : genCtx.values()) {
2173 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2174 if (result != null) {
2181 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2182 for (final ModuleContext ctx : genCtx.values()) {
2183 final GeneratedTypeBuilder result = ctx.getCase(path);
2184 if (result != null) {
2191 public Map<Module, ModuleContext> getModuleContexts() {
2196 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2197 return UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");