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;
29 import com.google.common.base.Preconditions;
30 import com.google.common.base.Splitter;
31 import com.google.common.collect.Iterables;
32 import com.google.common.collect.Sets;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
41 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
42 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
43 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
44 import org.opendaylight.yangtools.binding.generator.util.Types;
45 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
46 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
47 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
48 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
49 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
50 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
51 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
52 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
53 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
54 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
55 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
56 import org.opendaylight.yangtools.sal.binding.model.api.Type;
57 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
58 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
59 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
60 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
61 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
62 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
64 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
65 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
66 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
67 import org.opendaylight.yangtools.yang.binding.BindingMapping;
68 import org.opendaylight.yangtools.yang.binding.DataContainer;
69 import org.opendaylight.yangtools.yang.binding.RpcService;
70 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
71 import org.opendaylight.yangtools.yang.common.QName;
72 import org.opendaylight.yangtools.yang.common.RpcResult;
73 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
74 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
75 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
78 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
81 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.Module;
86 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
87 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
88 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
89 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
90 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
92 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
93 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.UsesNode;
95 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
96 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
97 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
98 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
99 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
100 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
101 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
102 import org.opendaylight.yangtools.yang.model.util.UnionType;
103 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
104 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
105 import org.slf4j.Logger;
106 import org.slf4j.LoggerFactory;
108 public class BindingGeneratorImpl implements BindingGenerator {
109 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
110 private static final Splitter COLON_SPLITTER = Splitter.on(':');
111 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
112 private static final char NEW_LINE = '\n';
113 private static final String QNAME_FQCN = QName.class.getName();
116 * Constant with the concrete name of identifier.
118 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
121 * Constant with the concrete name of namespace.
123 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
125 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
128 * When set to true, generated classes will include javadoc comments which
129 * are useful for users.
131 private final boolean verboseClassComments;
134 * Outer key represents the package name. Outer value represents map of all
135 * builders in the same package. Inner key represents the schema node name
136 * (in JAVA class/interface name format). Inner value represents instance of
137 * builder for schema node specified in key part.
139 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
142 * Provide methods for converting YANG types to JAVA types.
144 private TypeProvider typeProvider;
147 * Holds reference to schema context to resolve data of augmented element
148 * when creating augmentation builder
150 private SchemaContext schemaContext;
153 * Create a new binding generator with verboe comments.
155 * @deprecated Use {@link #BindingGeneratorImpl(boolean)} instead.
158 public BindingGeneratorImpl() {
163 * Create a new binding generator.
165 * @param verboseClassComments generate verbose comments
167 public BindingGeneratorImpl(final boolean verboseClassComments) {
168 this.verboseClassComments = verboseClassComments;
172 * Resolves generated types from <code>context</code> schema nodes of all
175 * Generated types are created for modules, groupings, types, containers,
176 * lists, choices, augments, rpcs, notification, identities.
179 * schema context which contains data about all schema nodes
181 * @return list of types (usually <code>GeneratedType</code>
182 * <code>GeneratedTransferObject</code>which are generated from
183 * <code>context</code> data.
184 * @throws IllegalArgumentException
185 * if arg <code>context</code> is null
186 * @throws IllegalStateException
187 * if <code>context</code> contain no modules
190 public List<Type> generateTypes(final SchemaContext context) {
191 checkArgument(context != null, "Schema Context reference cannot be NULL.");
192 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
193 schemaContext = context;
194 typeProvider = new TypeProviderImpl(context);
195 final Set<Module> modules = context.getModules();
196 return generateTypes(context, modules);
200 * Resolves generated types from <code>context</code> schema nodes only for
201 * modules specified in <code>modules</code>
203 * Generated types are created for modules, groupings, types, containers,
204 * lists, choices, augments, rpcs, notification, identities.
207 * schema context which contains data about all schema nodes
210 * set of modules for which schema nodes should be generated
212 * @return list of types (usually <code>GeneratedType</code> or
213 * <code>GeneratedTransferObject</code>) which:
215 * <li>are generated from <code>context</code> schema nodes and</li>
216 * <li>are also part of some of the module in <code>modules</code>
219 * @throws IllegalArgumentException
221 * <li>if arg <code>context</code> is null or</li>
222 * <li>if arg <code>modules</code> is null</li>
224 * @throws IllegalStateException
225 * if <code>context</code> contain no modules
228 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
229 checkArgument(context != null, "Schema Context reference cannot be NULL.");
230 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
231 checkArgument(modules != null, "Set of Modules cannot be NULL.");
233 schemaContext = context;
234 typeProvider = new TypeProviderImpl(context);
235 final Module[] modulesArray = new Module[context.getModules().size()];
236 context.getModules().toArray(modulesArray);
237 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
238 genTypeBuilders = new HashMap<>();
240 for (final Module contextModule : contextModules) {
241 moduleToGenTypes(contextModule, context);
243 for (final Module contextModule : contextModules) {
244 allAugmentsToGenTypes(contextModule);
247 final List<Type> filteredGenTypes = new ArrayList<>();
248 for (final Module m : modules) {
249 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
250 filteredGenTypes.addAll(ctx.getGeneratedTypes());
251 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
252 if (additionalTypes != null) {
253 filteredGenTypes.addAll(additionalTypes);
257 return filteredGenTypes;
260 private void moduleToGenTypes(final Module m, final SchemaContext context) {
261 genCtx.put(m, new ModuleContext());
262 allTypeDefinitionsToGenTypes(m);
263 groupingsToGenTypes(m, m.getGroupings());
264 rpcMethodsToGenType(m);
265 allIdentitiesToGenTypes(m, context);
266 notificationsToGenType(m);
268 if (!m.getChildNodes().isEmpty()) {
269 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
270 genCtx.get(m).addModuleNode(moduleType);
271 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
272 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
277 * Converts all extended type definitions of module to the list of
278 * <code>Type</code> objects.
281 * module from which is obtained set of type definitions
282 * @throws IllegalArgumentException
284 * <li>if module is null</li>
285 * <li>if name of module is null</li>
287 * @throws IllegalStateException
288 * if set of type definitions from module is null
290 private void allTypeDefinitionsToGenTypes(final Module module) {
291 checkArgument(module != null, "Module reference cannot be NULL.");
292 checkArgument(module.getName() != null, "Module name cannot be NULL.");
293 final DataNodeIterator it = new DataNodeIterator(module);
294 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
295 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
297 for (final TypeDefinition<?> typedef : typeDefinitions) {
298 if (typedef != null) {
299 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
302 final ModuleContext ctx = genCtx.get(module);
303 ctx.addTypedefType(typedef.getPath(), type);
304 ctx.addTypeToSchema(type,typedef);
310 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
311 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
312 if (node.isAugmenting() || node.isAddedByUses()) {
315 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
316 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
317 genType.addComment(node.getDescription());
318 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
319 genType.setModuleName(module.getName());
320 genType.setReference(node.getReference());
321 genType.setSchemaPath(node.getPath().getPathFromRoot());
322 if (node instanceof DataNodeContainer) {
323 genCtx.get(module).addChildNodeType(node, genType);
324 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
325 processUsesAugments((DataNodeContainer) node, module);
330 private void containerToGenType(final Module module, final String basePackageName,
331 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
332 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
333 if (genType != null) {
334 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType);
335 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
339 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
340 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
341 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
342 if (genType != null) {
343 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), Types.listTypeFor(genType));
345 final List<String> listKeys = listKeys(node);
346 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
347 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
348 if (genTOBuilder != null) {
349 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
350 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
351 genTOBuilder.addImplementsType(identifierMarker);
352 genType.addImplementsType(identifiableMarker);
355 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
356 if (!schemaNode.isAugmenting()) {
357 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
362 if (genTOBuilder != null) {
363 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
364 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
365 genTOBuilder.setSUID(prop);
368 typeBuildersToGenTypes(module, genType, genTOBuilder);
372 private void processUsesAugments(final DataNodeContainer node, final Module module) {
373 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
374 for (final UsesNode usesNode : node.getUses()) {
375 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
376 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
377 processUsesAugments(augment, module);
383 * Converts all <b>augmentation</b> of the module to the list
384 * <code>Type</code> objects.
387 * module from which is obtained list of all augmentation objects
388 * to iterate over them
389 * @throws IllegalArgumentException
391 * <li>if the module is null</li>
392 * <li>if the name of module is null</li>
394 * @throws IllegalStateException
395 * if set of augmentations from module is null
397 private void allAugmentsToGenTypes(final Module module) {
398 checkArgument(module != null, "Module reference cannot be NULL.");
399 checkArgument(module.getName() != null, "Module name cannot be NULL.");
400 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
402 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
403 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
404 for (final AugmentationSchema augment : augmentations) {
405 augmentationToGenTypes(basePackageName, augment, module);
410 * Returns list of <code>AugmentationSchema</code> objects. The objects are
411 * sorted according to the length of their target path from the shortest to
415 * module from which is obtained list of all augmentation objects
416 * @return list of sorted <code>AugmentationSchema</code> objects obtained
417 * from <code>module</code>
418 * @throws IllegalArgumentException
420 * @throws IllegalStateException
421 * if set of module augmentations is null
423 private List<AugmentationSchema> resolveAugmentations(final Module module) {
424 checkArgument(module != null, "Module reference cannot be NULL.");
425 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
427 final Set<AugmentationSchema> augmentations = module.getAugmentations();
428 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
429 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
431 return sortedAugmentations;
435 * Create GeneratedTypeBuilder object from module argument.
438 * Module object from which builder will be created
439 * @return <code>GeneratedTypeBuilder</code> which is internal
440 * representation of the module
441 * @throws IllegalArgumentException
444 private GeneratedTypeBuilder moduleToDataType(final Module module) {
445 checkArgument(module != null, "Module reference cannot be NULL.");
447 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
448 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
449 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
450 moduleDataTypeBuilder.addComment(module.getDescription());
451 moduleDataTypeBuilder.setDescription(createDescription(module));
452 moduleDataTypeBuilder.setReference(module.getReference());
453 return moduleDataTypeBuilder;
457 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
458 * to the list of <code>Type</code> objects. In addition are to containers
459 * and lists which belong to input or output also part of returning list.
462 * module from which is obtained set of all rpc objects to
464 * @throws IllegalArgumentException
466 * <li>if the module is null</li>
467 * <li>if the name of module is null</li>
469 * @throws IllegalStateException
470 * if set of rpcs from module is null
472 private void rpcMethodsToGenType(final Module module) {
473 checkArgument(module != null, "Module reference cannot be NULL.");
474 checkArgument(module.getName() != null, "Module name cannot be NULL.");
475 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
476 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
477 if (rpcDefinitions.isEmpty()) {
481 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
482 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
483 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
484 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
486 for (final RpcDefinition rpc : rpcDefinitions) {
488 final String rpcName = BindingMapping.getClassName(rpc.getQName());
489 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
490 final String rpcComment = rpc.getDescription();
491 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
492 final ContainerSchemaNode input = rpc.getInput();
493 final ContainerSchemaNode output = rpc.getOutput();
496 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
497 addImplementedInterfaceFromUses(input, inType);
498 inType.addImplementsType(DATA_OBJECT);
499 inType.addImplementsType(augmentable(inType));
500 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
501 genCtx.get(module).addChildNodeType(input, inType);
502 final GeneratedType inTypeInstance = inType.toInstance();
503 method.addParameter(inTypeInstance, "input");
506 Type outTypeInstance = VOID;
507 if (output != null) {
508 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
509 addImplementedInterfaceFromUses(output, outType);
510 outType.addImplementsType(DATA_OBJECT);
511 outType.addImplementsType(augmentable(outType));
512 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
513 genCtx.get(module).addChildNodeType(output, outType);
514 outTypeInstance = outType.toInstance();
517 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
518 method.setComment(rpcComment);
519 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
523 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
527 * Converts all <b>notifications</b> of the module to the list of
528 * <code>Type</code> objects. In addition are to this list added containers
529 * and lists which are part of this notification.
532 * module from which is obtained set of all notification objects
533 * to iterate over them
534 * @throws IllegalArgumentException
536 * <li>if the module equals null</li>
537 * <li>if the name of module equals null</li>
539 * @throws IllegalStateException
540 * if set of notifications from module is null
542 private void notificationsToGenType(final Module module) {
543 checkArgument(module != null, "Module reference cannot be NULL.");
544 checkArgument(module.getName() != null, "Module name cannot be NULL.");
545 final Set<NotificationDefinition> notifications = module.getNotifications();
546 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
547 if (notifications.isEmpty()) {
551 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
552 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
553 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
557 for (final NotificationDefinition notification : notifications) {
558 if (notification != null) {
559 processUsesAugments(notification, module);
561 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
562 notification, BindingTypes.DATA_OBJECT, module);
563 notificationInterface.addImplementsType(NOTIFICATION);
564 genCtx.get(module).addChildNodeType(notification, notificationInterface);
566 // Notification object
567 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
568 notification.getChildNodes());
570 listenerInterface.addMethod("on" + notificationInterface.getName())
571 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
572 .setComment(notification.getDescription()).setReturnType(Types.VOID);
575 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
577 genCtx.get(module).addTopLevelNodeType(listenerInterface);
581 * Converts all <b>identities</b> of the module to the list of
582 * <code>Type</code> objects.
585 * module from which is obtained set of all identity objects to
588 * schema context only used as input parameter for method
589 * {@link identityToGenType}
592 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
593 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
594 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
596 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
597 for (final IdentitySchemaNode identity : schemaIdentities) {
598 identityToGenType(module, basePackageName, identity, context);
604 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
605 * created transport object builder. If identity contains base identity then
606 * reference to base identity is added to superior identity as its extend.
607 * If identity doesn't contain base identity then only reference to abstract
608 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
609 * BaseIdentity} is added
613 * @param basePackageName
614 * string contains the module package name
616 * IdentitySchemaNode which contains data about identity
618 * SchemaContext which is used to get package and name
619 * information about base of identity
622 private void identityToGenType(final Module module, final String basePackageName,
623 final IdentitySchemaNode identity, final SchemaContext context) {
624 if (identity == null) {
627 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
628 final String genTypeName = BindingMapping.getClassName(identity.getQName());
629 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
630 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
631 if (baseIdentity == null) {
632 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
633 BaseIdentity.class.getSimpleName());
634 newType.setExtendsType(gto.toInstance());
636 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
637 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
639 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
640 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
642 newType.setExtendsType(gto);
644 newType.setAbstract(true);
645 newType.addComment(identity.getDescription());
646 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
647 newType.setReference(identity.getReference());
648 newType.setModuleName(module.getName());
649 newType.setSchemaPath(identity.getPath().getPathFromRoot());
651 final QName qname = identity.getQName();
652 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
654 genCtx.get(module).addIdentityType(identity.getQName(), newType);
657 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
659 final StringBuilder sb = new StringBuilder(QNAME_FQCN);
660 sb.append(".cachedReference(");
661 sb.append(QNAME_FQCN);
662 sb.append(".create(");
664 sb.append(name.getNamespace());
666 sb.append(name.getFormattedRevision());
668 sb.append(name.getLocalName());
671 return toBuilder.addConstant(typeForClass(QName.class), constantName, sb.toString());
675 * Converts all <b>groupings</b> of the module to the list of
676 * <code>Type</code> objects. Firstly are groupings sorted according mutual
677 * dependencies. At least dependent (independent) groupings are in the list
678 * saved at first positions. For every grouping the record is added to map
679 * {@link BindingGeneratorImpl#allGroupings allGroupings}
684 * of groupings from which types will be generated
687 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
688 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
689 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
691 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
692 groupingToGenType(basePackageName, grouping, module);
697 * Converts individual grouping to GeneratedType. Firstly generated type
698 * builder is created and every child node of grouping is resolved to the
701 * @param basePackageName
702 * string contains the module package name
704 * GroupingDefinition which contains data about grouping
707 * @return GeneratedType which is generated from grouping (object of type
708 * <code>GroupingDefinition</code>)
710 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
711 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
712 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
713 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
714 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
715 groupingsToGenTypes(module, grouping.getGroupings());
716 processUsesAugments(grouping, module);
720 * Adds enumeration builder created from <code>enumTypeDef</code> to
721 * <code>typeBuilder</code>.
723 * Each <code>enumTypeDef</code> item is added to builder with its name and
727 * EnumTypeDefinition contains enum data
729 * string contains name which will be assigned to enumeration
732 * GeneratedTypeBuilder to which will be enum builder assigned
734 * Module in which type should be generated
735 * @return enumeration builder which contains data from
736 * <code>enumTypeDef</code>
738 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
739 final GeneratedTypeBuilder typeBuilder, Module module) {
740 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
741 && (enumTypeDef.getQName().getLocalName() != null)) {
742 final String enumerationName = BindingMapping.getClassName(enumName);
743 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
744 enumBuilder.setDescription(enumTypeDef.getDescription());
745 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
746 ModuleContext ctx = genCtx.get(module);
747 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
754 * Generates type builder for <code>module</code>.
757 * Module which is source of package name for generated type
760 * string which is added to the module class name representation
762 * @return instance of GeneratedTypeBuilder which represents
763 * <code>module</code>.
764 * @throws IllegalArgumentException
765 * if <code>module</code> is null
767 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
768 checkArgument(module != null, "Module reference cannot be NULL.");
769 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
770 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
772 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
773 moduleBuilder.setDescription(createDescription(module));
774 moduleBuilder.setReference(module.getReference());
775 moduleBuilder.setModuleName(moduleName);
777 return moduleBuilder;
781 * Converts <code>augSchema</code> to list of <code>Type</code> which
782 * contains generated type for augmentation. In addition there are also
783 * generated types for all containers, list and choices which are child of
784 * <code>augSchema</code> node or a generated types for cases are added if
785 * augmented node is choice.
787 * @param augmentPackageName
788 * string with the name of the package to which the augmentation
791 * AugmentationSchema which is contains data about augmentation
792 * (target path, childs...)
795 * @param parentUsesNode
796 * @throws IllegalArgumentException
798 * <li>if <code>augmentPackageName</code> equals null</li>
799 * <li>if <code>augSchema</code> equals null</li>
801 * @throws IllegalStateException
802 * if augment target path is null
804 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
805 final Module module) {
806 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
807 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
808 checkState(augSchema.getTargetPath() != null,
809 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
811 processUsesAugments(augSchema, module);
812 final SchemaPath targetPath = augSchema.getTargetPath();
813 SchemaNode targetSchemaNode = null;
815 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
816 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
817 if (targetSchemaNode instanceof DerivableSchemaNode) {
818 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
820 if (targetSchemaNode == null) {
821 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
822 + " in module " + module.getName());
825 if (targetSchemaNode == null) {
826 throw new IllegalArgumentException("augment target not found: " + targetPath);
829 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
830 if (targetTypeBuilder == null) {
831 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
833 if (targetTypeBuilder == null) {
834 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
837 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
838 final String packageName = augmentPackageName;
839 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
840 targetTypeBuilder.getName());
841 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
844 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
845 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
849 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
850 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
851 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
852 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
853 checkState(augSchema.getTargetPath() != null,
854 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
856 processUsesAugments(augSchema, module);
857 final SchemaPath targetPath = augSchema.getTargetPath();
858 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
859 if (targetSchemaNode == null) {
860 throw new IllegalArgumentException("augment target not found: " + targetPath);
863 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
864 if (targetTypeBuilder == null) {
865 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
867 if (targetTypeBuilder == null) {
868 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
871 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
872 String packageName = augmentPackageName;
873 if (usesNodeParent instanceof SchemaNode) {
874 packageName = packageNameForGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath(),
877 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
880 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
881 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
886 * Convenient method to find node added by uses statement.
890 * @param parentUsesNode
891 * parent of uses node
892 * @return node from its original location in grouping
894 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
895 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
897 if (!(targetGrouping instanceof GroupingDefinition)) {
898 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
901 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
902 SchemaNode result = grouping;
903 for (final QName node : targetPath.getPathFromRoot()) {
904 // finding by local name is valid, grouping cannot contain nodes
905 // with same name and different namespace
906 if (result instanceof DataNodeContainer) {
907 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
908 } else if (result instanceof ChoiceSchemaNode) {
909 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
912 if (result == null) {
916 boolean fromUses = ((DataSchemaNode) result).isAddedByUses();
917 final Iterator<UsesNode> groupingUses = grouping.getUses().iterator();
918 while (groupingUses.hasNext() && fromUses) {
919 result = findOriginalTargetFromGrouping(targetPath, groupingUses.next());
920 if (result != null) {
921 fromUses = ((DataSchemaNode) result).isAddedByUses();
925 // this indicates invalid yang and thus possible bug in code because
926 // invalid yang should be already spotted by parser
927 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
930 return (DataSchemaNode) result;
934 * Returns a generated type builder for an augmentation.
936 * The name of the type builder is equal to the name of augmented node with
937 * serial number as suffix.
941 * @param augmentPackageName
942 * string with contains the package name to which the augment
944 * @param basePackageName
945 * string with the package name to which the augmented node
947 * @param targetTypeRef
950 * augmentation schema which contains data about the child nodes
951 * and uses of augment
952 * @return generated type builder for augment
954 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
955 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
956 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
957 if (augmentBuilders == null) {
958 augmentBuilders = new HashMap<>();
959 genTypeBuilders.put(augmentPackageName, augmentBuilders);
961 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
964 if (augIdentifier != null) {
965 augTypeName = BindingMapping.getClassName(augIdentifier);
967 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
970 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
972 augTypeBuilder.addImplementsType(DATA_OBJECT);
973 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
974 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
976 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
977 augmentBuilders.put(augTypeName, augTypeBuilder);
979 if(!augSchema.getChildNodes().isEmpty()) {
980 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
981 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
984 genCtx.get(module).addAugmentType(augTypeBuilder);
985 return augTypeBuilder;
990 * @param unknownSchemaNodes
991 * @return nodeParameter of UnknownSchemaNode
993 private String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
994 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
995 final QName nodeType = unknownSchemaNode.getNodeType();
996 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
997 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
998 return unknownSchemaNode.getNodeParameter();
1005 * Returns first unique name for the augment generated type builder. The
1006 * generated type builder name for augment consists from name of augmented
1007 * node and serial number of its augmentation.
1010 * map of builders which were created in the package to which the
1011 * augmentation belongs
1012 * @param genTypeName
1013 * string with name of augmented node
1014 * @return string with unique name for augmentation builder
1016 private String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1018 if (builders != null) {
1019 while (builders.containsKey(genTypeName + index)) {
1023 return genTypeName + index;
1027 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1028 * node for which <code>typeBuilder</code> was created.
1030 * The subnodes aren't mapped to the methods if they are part of grouping or
1031 * augment (in this case are already part of them).
1035 * @param basePackageName
1036 * string contains the module package name
1038 * generated type builder which represents any node. The subnodes
1039 * of this node are added to the <code>typeBuilder</code> as
1040 * methods. The subnode can be of type leaf, leaf-list, list,
1041 * container, choice.
1044 * @param schemaNodes
1045 * set of data schema nodes which are the children of the node
1046 * for which <code>typeBuilder</code> was created
1047 * @return generated type builder which is the same builder as input
1048 * parameter. The getter methods (representing child nodes) could be
1051 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1052 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1053 if (schemaNodes != null && parent != null) {
1054 for (final DataSchemaNode schemaNode : schemaNodes) {
1055 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1056 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1064 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1065 * node for which <code>typeBuilder</code> was created.
1069 * @param basePackageName
1070 * string contains the module package name
1071 * @param typeBuilder
1072 * generated type builder which represents any node. The subnodes
1073 * of this node are added to the <code>typeBuilder</code> as
1074 * methods. The subnode can be of type leaf, leaf-list, list,
1075 * container, choice.
1078 * @param schemaNodes
1079 * set of data schema nodes which are the children of the node
1080 * for which <code>typeBuilder</code> was created
1081 * @return generated type builder which is the same object as the input
1082 * parameter <code>typeBuilder</code>. The getter method could be
1085 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1086 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1087 final Iterable<DataSchemaNode> schemaNodes) {
1088 if ((schemaNodes != null) && (typeBuilder != null)) {
1089 for (final DataSchemaNode schemaNode : schemaNodes) {
1090 if (!schemaNode.isAugmenting()) {
1091 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1099 * Adds to <code>typeBuilder</code> a method which is derived from
1100 * <code>schemaNode</code>.
1102 * @param basePackageName
1103 * string with the module package name
1105 * data schema node which is added to <code>typeBuilder</code> as
1107 * @param typeBuilder
1108 * generated type builder to which is <code>schemaNode</code>
1109 * added as a method.
1115 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1116 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1117 if (node != null && typeBuilder != null) {
1118 if (node instanceof LeafSchemaNode) {
1119 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1120 } else if (node instanceof LeafListSchemaNode) {
1121 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1122 } else if (node instanceof ContainerSchemaNode) {
1123 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1124 } else if (node instanceof ListSchemaNode) {
1125 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1126 } else if (node instanceof ChoiceSchemaNode) {
1127 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1129 // TODO: anyxml not yet supported
1130 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1131 typeBuilder.getFullyQualifiedName());
1137 * Converts <code>choiceNode</code> to the list of generated types for
1138 * choice and its cases.
1140 * The package names for choice and for its cases are created as
1141 * concatenation of the module package (<code>basePackageName</code>) and
1142 * names of all parents node.
1146 * @param basePackageName
1147 * string with the module package name
1151 * choice node which is mapped to generated type. Also child
1152 * nodes - cases are mapped to generated types.
1153 * @throws IllegalArgumentException
1155 * <li>if <code>basePackageName</code> is null</li>
1156 * <li>if <code>choiceNode</code> is null</li>
1159 private void choiceToGeneratedType(final Module module, final String basePackageName,
1160 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1161 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1162 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1164 if (!choiceNode.isAddedByUses()) {
1165 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1166 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1167 constructGetter(parent, choiceNode.getQName().getLocalName(), choiceNode.getDescription(),
1169 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1170 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1171 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1176 * Converts <code>caseNodes</code> set to list of corresponding generated
1179 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1180 * created generated type builder. The package names for the builder is
1181 * created as concatenation of the module package (
1182 * <code>basePackageName</code>) and names of all parents nodes of the
1183 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1184 * between every case builder and <i>choice</i> type
1188 * @param basePackageName
1189 * string with the module package name
1190 * @param refChoiceType
1191 * type which represents superior <i>case</i>
1193 * choice case node which is mapped to generated type
1194 * @return list of generated types for <code>caseNodes</code>.
1195 * @throws IllegalArgumentException
1197 * <li>if <code>basePackageName</code> equals null</li>
1198 * <li>if <code>refChoiceType</code> equals null</li>
1199 * <li>if <code>caseNodes</code> equals null</li>
1202 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1203 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1204 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1205 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1206 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1208 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1209 if (caseNodes == null) {
1213 for (final ChoiceCaseNode caseNode : caseNodes) {
1214 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1215 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1216 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1217 caseTypeBuilder.addImplementsType(refChoiceType);
1218 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1219 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1220 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1221 if (caseChildNodes != null) {
1222 final SchemaPath nodeSp = choiceNode.getPath();
1223 final Object parentNode = findDataSchemaNode(schemaContext, nodeSp.getParent());
1226 if (parentNode instanceof AugmentationSchema) {
1227 final AugmentationSchema augSchema = (AugmentationSchema) parentNode;
1228 final SchemaPath targetPath = augSchema.getTargetPath();
1229 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1230 if (targetSchemaNode instanceof DataSchemaNode
1231 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1232 if (targetSchemaNode instanceof DerivableSchemaNode) {
1233 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1235 if (targetSchemaNode == null) {
1236 throw new IllegalStateException(
1237 "Failed to find target node from grouping for augmentation " + augSchema
1238 + " in module " + module.getName());
1241 parent = targetSchemaNode;
1243 final SchemaPath sp = choiceNode.getPath();
1244 parent = findDataSchemaNode(schemaContext, sp.getParent());
1246 Preconditions.checkState(parent != null, "Could not find Choice node parent "+choiceNode.getPath().getParent());
1247 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1248 if (childOfType == null) {
1249 childOfType = findGroupingByPath(parent.getPath());
1251 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1254 processUsesAugments(caseNode, module);
1259 * Generates list of generated types for all the cases of a choice which are
1260 * added to the choice through the augment.
1264 * @param basePackageName
1265 * string contains name of package to which augment belongs. If
1266 * an augmented choice is from an other package (pcg1) than an
1267 * augmenting choice (pcg2) then case's of the augmenting choice
1268 * will belong to pcg2.
1270 * Type which represents target choice
1272 * node which represents target choice
1273 * @param augmentedNodes
1274 * set of choice case nodes for which is checked if are/aren't
1275 * added to choice through augmentation
1276 * @return list of generated types which represents augmented cases of
1277 * choice <code>refChoiceType</code>
1278 * @throws IllegalArgumentException
1280 * <li>if <code>basePackageName</code> is null</li>
1281 * <li>if <code>targetType</code> is null</li>
1282 * <li>if <code>augmentedNodes</code> is null</li>
1285 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1286 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
1287 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1288 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1289 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1291 for (final DataSchemaNode caseNode : augmentedNodes) {
1292 if (caseNode != null) {
1293 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1294 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1295 caseTypeBuilder.addImplementsType(targetType);
1297 SchemaNode parent = null;
1298 final SchemaPath nodeSp = targetNode.getPath();
1299 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1301 GeneratedTypeBuilder childOfType = null;
1302 if (parent instanceof Module) {
1303 childOfType = genCtx.get(parent).getModuleNode();
1304 } else if (parent instanceof ChoiceCaseNode) {
1305 childOfType = findCaseByPath(parent.getPath());
1306 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1307 childOfType = findChildNodeByPath(parent.getPath());
1308 } else if (parent instanceof GroupingDefinition) {
1309 childOfType = findGroupingByPath(parent.getPath());
1312 if (childOfType == null) {
1313 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1316 ChoiceCaseNode node = null;
1317 if (caseNode instanceof ChoiceCaseNode) {
1318 node = (ChoiceCaseNode) caseNode;
1320 node = targetNode.getCaseNodeByName(caseNode.getQName().getLocalName());
1322 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1323 if (childNodes != null) {
1324 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1326 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1327 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1333 * Converts <code>leaf</code> to the getter method which is added to
1334 * <code>typeBuilder</code>.
1336 * @param typeBuilder
1337 * generated type builder to which is added getter method as
1338 * <code>leaf</code> mapping
1340 * leaf schema node which is mapped as getter method which is
1341 * added to <code>typeBuilder</code>
1343 * Module in which type was defined
1344 * @return boolean value
1346 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1348 * <li>true - in other cases</li>
1351 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, Module module) {
1352 Type returnType = null;
1353 if ((leaf != null) && (typeBuilder != null)) {
1354 final String leafName = leaf.getQName().getLocalName();
1355 String leafDesc = leaf.getDescription();
1356 if (leafDesc == null) {
1360 final Module parentModule = findParentModule(schemaContext, leaf);
1361 if (leafName != null && !leaf.isAddedByUses()) {
1362 final TypeDefinition<?> typeDef = leaf.getType();
1364 GeneratedTOBuilder genTOBuilder;
1365 if (typeDef instanceof EnumTypeDefinition) {
1366 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1367 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1368 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1369 typeBuilder,module);
1371 if (enumBuilder != null) {
1372 returnType = enumBuilder.toInstance(typeBuilder);
1374 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1375 } else if (typeDef instanceof UnionType) {
1376 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1377 if (genTOBuilder != null) {
1378 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1380 } else if (typeDef instanceof BitsTypeDefinition) {
1381 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1382 if (genTOBuilder != null) {
1383 returnType = genTOBuilder.toInstance();
1386 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1387 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1389 if (returnType != null) {
1390 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1391 processContextRefExtension(leaf, getter, parentModule);
1398 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1399 final Module module) {
1400 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1401 final QName nodeType = node.getNodeType();
1402 if ("context-reference".equals(nodeType.getLocalName())) {
1403 final String nodeParam = node.getNodeParameter();
1404 IdentitySchemaNode identity = null;
1405 String basePackageName = null;
1406 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1407 final Iterator<String> iterator = splittedElement.iterator();
1408 final int length = Iterables.size(splittedElement);
1410 identity = findIdentityByName(module.getIdentities(), iterator.next());
1411 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1412 } else if (length == 2) {
1413 final String prefix = iterator.next();
1414 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1415 if (dependentModule == null) {
1416 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1419 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1420 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1422 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1425 if (identity == null) {
1426 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1430 final Class<RoutingContext> clazz = RoutingContext.class;
1431 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1432 clazz.getSimpleName());
1433 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1434 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1435 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1440 private IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1441 for (final IdentitySchemaNode id : identities) {
1442 if (id.getQName().getLocalName().equals(name)) {
1449 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1450 for (final ModuleImport imp : imports) {
1451 if (imp.getPrefix().equals(prefix)) {
1452 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1458 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1459 final boolean isReadOnly, final Module module) {
1460 if ((leaf != null) && (toBuilder != null)) {
1461 final String leafName = leaf.getQName().getLocalName();
1462 String leafDesc = leaf.getDescription();
1463 if (leafDesc == null) {
1466 Type returnType = null;
1467 final TypeDefinition<?> typeDef = leaf.getType();
1468 if (typeDef instanceof UnionTypeDefinition) {
1469 // GeneratedType for this type definition should be already
1471 final QName qname = typeDef.getQName();
1472 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1473 qname.getRevision());
1474 final ModuleContext mc = genCtx.get(unionModule);
1475 returnType = mc.getTypedefs().get(typeDef.getPath());
1476 } else if (typeDef instanceof EnumTypeDefinition && BaseTypes.ENUMERATION_QNAME.equals(typeDef.getQName())) {
1477 // Annonymous enumeration (already generated, since it is inherited via uses).
1478 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1479 QName qname = originalLeaf.getQName();
1480 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1481 qname.getRevision());
1482 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1484 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1486 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1492 * Converts <code>leaf</code> schema node to property of generated TO
1496 * generated TO builder to which is <code>leaf</code> added as
1499 * leaf schema node which is added to <code>toBuilder</code> as
1504 * boolean value which says if leaf property is|isn't read only
1505 * @return boolean value
1507 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1508 * name equals null or if leaf is added by <i>uses</i>.</li>
1509 * <li>true - other cases</li>
1512 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1513 final Type returnType, final boolean isReadOnly) {
1514 if (returnType == null) {
1517 final String leafName = leaf.getQName().getLocalName();
1518 final String leafDesc = leaf.getDescription();
1519 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1520 propBuilder.setReadOnly(isReadOnly);
1521 propBuilder.setReturnType(returnType);
1522 propBuilder.setComment(leafDesc);
1523 toBuilder.addEqualsIdentity(propBuilder);
1524 toBuilder.addHashIdentity(propBuilder);
1525 toBuilder.addToStringProperty(propBuilder);
1530 * Converts <code>node</code> leaf list schema node to getter method of
1531 * <code>typeBuilder</code>.
1533 * @param typeBuilder
1534 * generated type builder to which is <code>node</code> added as
1537 * leaf list schema node which is added to
1538 * <code>typeBuilder</code> as getter method
1540 * @return boolean value
1542 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1543 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1544 * <li>false - other cases</li>
1547 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, Module module) {
1548 if ((node != null) && (typeBuilder != null)) {
1549 final QName nodeName = node.getQName();
1551 if (nodeName != null && !node.isAddedByUses()) {
1552 final TypeDefinition<?> typeDef = node.getType();
1553 final Module parentModule = findParentModule(schemaContext, node);
1555 Type returnType = null;
1556 if (typeDef instanceof EnumTypeDefinition) {
1557 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1558 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1559 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1560 typeBuilder,module);
1561 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1562 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1563 } else if (typeDef instanceof UnionType) {
1564 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1565 if (genTOBuilder != null) {
1566 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1568 } else if (typeDef instanceof BitsTypeDefinition) {
1569 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1570 returnType = genTOBuilder.toInstance();
1572 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1573 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1576 final ParameterizedType listType = Types.listTypeFor(returnType);
1577 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1584 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1585 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1586 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1587 genTOBuilder.getName());
1589 returnType.setDescription(typeDef.getDescription());
1590 returnType.setReference(typeDef.getReference());
1591 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1592 returnType.setModuleName(parentModule.getName());
1594 genTOBuilder.setTypedef(true);
1595 genTOBuilder.setIsUnion(true);
1596 ((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1600 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1603 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1604 method.setReturnType(returnType);
1605 method.addParameter(Types.STRING, "defaultValue");
1606 method.setAccessModifier(AccessModifier.PUBLIC);
1607 method.setStatic(true);
1609 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1610 if (types == null) {
1611 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1612 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1614 types.add(unionBuilder.toInstance());
1616 return returnType.toInstance();
1619 private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1621 final String outerCls = Types.getOuterClassName(genTOBuilder);
1622 final StringBuilder name;
1623 if(outerCls != null) {
1624 name = new StringBuilder(outerCls);
1626 name = new StringBuilder();
1628 name.append(genTOBuilder.getName());
1629 name.append("Builder");
1630 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1631 unionBuilder.setIsUnionBuilder(true);
1632 return unionBuilder;
1635 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1636 final Module module) {
1637 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1641 * Instantiates generated type builder with <code>packageName</code> and
1642 * <code>schemaNode</code>.
1644 * The new builder always implements
1645 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1646 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1647 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1649 * If <code>schemaNode</code> is instance of
1650 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1651 * DataNodeContainer} it can also implement nodes which are specified in
1654 * @param packageName
1655 * string with the name of the package to which
1656 * <code>schemaNode</code> belongs.
1658 * schema node for which is created generated type builder
1660 * parent type (can be null)
1661 * @return generated type builder <code>schemaNode</code>
1663 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1664 final Type parent, final Module module) {
1665 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1666 if (parent == null) {
1667 it.addImplementsType(DATA_OBJECT);
1669 it.addImplementsType(BindingTypes.childOf(parent));
1671 if (!(schemaNode instanceof GroupingDefinition)) {
1672 it.addImplementsType(augmentable(it));
1675 if (schemaNode instanceof DataNodeContainer) {
1676 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1677 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1684 * Wraps the calling of the same overloaded method.
1686 * @param packageName
1687 * string with the package name to which returning generated type
1690 * schema node which provide data about the schema node name
1691 * @return generated type builder for <code>schemaNode</code>
1693 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1694 return addRawInterfaceDefinition(packageName, schemaNode, "");
1698 * Returns reference to generated type builder for specified
1699 * <code>schemaNode</code> with <code>packageName</code>.
1701 * Firstly the generated type builder is searched in
1702 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1703 * found it is created and added to <code>genTypeBuilders</code>.
1705 * @param packageName
1706 * string with the package name to which returning generated type
1709 * schema node which provide data about the schema node name
1711 * return type name prefix
1712 * @return generated type builder for <code>schemaNode</code>
1713 * @throws IllegalArgumentException
1715 * <li>if <code>schemaNode</code> is null</li>
1716 * <li>if <code>packageName</code> is null</li>
1717 * <li>if QName of schema node is null</li>
1718 * <li>if schemaNode name is null</li>
1722 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1723 final String prefix) {
1724 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1725 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1726 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1727 final String schemaNodeName = schemaNode.getQName().getLocalName();
1728 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1731 if (prefix == null) {
1732 genTypeName = BindingMapping.getClassName(schemaNodeName);
1734 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1737 // FIXME: Validation of name conflict
1738 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1739 final Module module = findParentModule(schemaContext, schemaNode);
1740 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1741 newType.addComment(schemaNode.getDescription());
1742 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1743 newType.setReference(schemaNode.getReference());
1744 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1745 newType.setModuleName(module.getName());
1747 if (!genTypeBuilders.containsKey(packageName)) {
1748 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1749 builders.put(genTypeName, newType);
1750 genTypeBuilders.put(packageName, builders);
1752 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1753 if (!builders.containsKey(genTypeName)) {
1754 builders.put(genTypeName, newType);
1761 * Creates the name of the getter method name from <code>localName</code>.
1764 * string with the name of the getter method
1767 * @return string with the name of the getter method for
1768 * <code>methodName</code> in JAVA method format
1770 public static String getterMethodName(final String localName, final Type returnType) {
1771 final StringBuilder method = new StringBuilder();
1772 if (BOOLEAN.equals(returnType)) {
1773 method.append("is");
1775 method.append("get");
1777 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1778 method.append(name);
1779 return method.toString();
1783 * Created a method signature builder as part of
1784 * <code>interfaceBuilder</code>.
1786 * The method signature builder is created for the getter method of
1787 * <code>schemaNodeName</code>. Also <code>comment</code> and
1788 * <code>returnType</code> information are added to the builder.
1790 * @param interfaceBuilder
1791 * generated type builder for which the getter method should be
1793 * @param schemaNodeName
1794 * string with schema node name. The name will be the part of the
1795 * getter method name.
1797 * string with comment for the getter method
1799 * type which represents the return type of the getter method
1800 * @return method signature builder which represents the getter method of
1801 * <code>interfaceBuilder</code>
1803 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1804 final String schemaNodeName, final String comment, final Type returnType) {
1805 final MethodSignatureBuilder getMethod = interfaceBuilder
1806 .addMethod(getterMethodName(schemaNodeName, returnType));
1807 getMethod.setComment(comment);
1808 getMethod.setReturnType(returnType);
1813 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1814 * or to <code>genTOBuilder</code> as property.
1816 * @param basePackageName
1817 * string contains the module package name
1819 * data schema node which should be added as getter method to
1820 * <code>typeBuilder</code> or as a property to
1821 * <code>genTOBuilder</code> if is part of the list key
1822 * @param typeBuilder
1823 * generated type builder for the list schema node
1824 * @param genTOBuilder
1825 * generated TO builder for the list keys
1827 * list of string which contains names of the list keys
1830 * @throws IllegalArgumentException
1832 * <li>if <code>schemaNode</code> equals null</li>
1833 * <li>if <code>typeBuilder</code> equals null</li>
1836 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1837 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1838 final Module module) {
1839 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1840 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1842 if (schemaNode instanceof LeafSchemaNode) {
1843 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1844 final String leafName = leaf.getQName().getLocalName();
1845 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1846 if (listKeys.contains(leafName)) {
1848 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1850 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1853 } else if (!schemaNode.isAddedByUses()) {
1854 if (schemaNode instanceof LeafListSchemaNode) {
1855 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1856 } else if (schemaNode instanceof ContainerSchemaNode) {
1857 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1858 } else if (schemaNode instanceof ChoiceSchemaNode) {
1859 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1860 } else if (schemaNode instanceof ListSchemaNode) {
1861 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1866 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1867 final GeneratedTOBuilder genTOBuilder) {
1868 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1870 if (genTOBuilder != null) {
1871 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1872 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
1873 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1878 * Selects the names of the list keys from <code>list</code> and returns
1879 * them as the list of the strings
1882 * of string with names of the list keys
1883 * @return list of string which represents names of the list keys. If the
1884 * <code>list</code> contains no keys then the empty list is
1887 private List<String> listKeys(final ListSchemaNode list) {
1888 final List<String> listKeys = new ArrayList<>();
1890 final List<QName> keyDefinition = list.getKeyDefinition();
1891 if (keyDefinition != null) {
1892 for (final QName keyDef : keyDefinition) {
1893 listKeys.add(keyDef.getLocalName());
1900 * Generates for the <code>list</code> which contains any list keys special
1901 * generated TO builder.
1903 * @param packageName
1904 * string with package name to which the list belongs
1906 * list schema node which is source of data about the list name
1907 * @return generated TO builder which represents the keys of the
1908 * <code>list</code> or null if <code>list</code> is null or list of
1909 * key definitions is null or empty.
1911 private GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1912 GeneratedTOBuilder genTOBuilder = null;
1913 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1914 final String listName = list.getQName().getLocalName() + "Key";
1915 final String genTOName = BindingMapping.getClassName(listName);
1916 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1918 return genTOBuilder;
1922 * Builds generated TO builders for <code>typeDef</code> of type
1923 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
1924 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
1925 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
1926 * enclosing transfer object.
1928 * If more then one generated TO builder is created for enclosing then all
1929 * of the generated TO builders are added to <code>typeBuilder</code> as
1930 * enclosing transfer objects.
1933 * type definition which can be of type <code>UnionType</code> or
1934 * <code>BitsTypeDefinition</code>
1935 * @param typeBuilder
1936 * generated type builder to which is added generated TO created
1937 * from <code>typeDef</code>
1939 * string with name for generated TO builder
1941 * @return generated TO builder for <code>typeDef</code>
1943 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
1944 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1945 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
1946 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
1947 final String packageName = typeBuilder.getFullyQualifiedName();
1948 if (typeDef instanceof UnionTypeDefinition) {
1949 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
1950 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
1951 classNameFromLeaf, leaf);
1952 genTOBuilders.addAll(types);
1954 GeneratedTOBuilder resultTOBuilder = null;
1955 if (types.isEmpty()) {
1956 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
1958 resultTOBuilder = types.remove(0);
1959 for (final GeneratedTOBuilder genTOBuilder : types) {
1960 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1963 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1964 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1965 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1966 resultTOBuilder.addHashIdentity(genPropBuilder);
1967 resultTOBuilder.addToStringProperty(genPropBuilder);
1969 } else if (typeDef instanceof BitsTypeDefinition) {
1970 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
1971 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
1973 if (genTOBuilders != null && !genTOBuilders.isEmpty()) {
1974 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1975 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1977 return genTOBuilders.get(0);
1984 * Adds the implemented types to type builder.
1986 * The method passes through the list of <i>uses</i> in
1987 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1988 * generated type from {@link BindingGeneratorImpl#allGroupings
1989 * allGroupings} which is added as <i>implements type</i> to
1990 * <code>builder</code>
1992 * @param dataNodeContainer
1993 * element which contains the list of used YANG groupings
1995 * builder to which are added implemented types according to
1996 * <code>dataNodeContainer</code>
1997 * @return generated type builder with all implemented types
1999 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2000 final GeneratedTypeBuilder builder) {
2001 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2002 if (usesNode.getGroupingPath() != null) {
2003 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2004 if (genType == null) {
2005 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2006 + builder.getName());
2009 builder.addImplementsType(genType);
2011 builder.addComment(genType.getDescription());
2012 builder.setDescription(genType.getDescription());
2013 builder.setModuleName(genType.getModuleName());
2014 builder.setReference(genType.getReference());
2015 builder.setSchemaPath(genType.getSchemaPath());
2022 private boolean isNullOrEmpty(final Collection<?> list) {
2023 return (list == null || list.isEmpty() ? true : false);
2026 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
2027 final StringBuilder sb = new StringBuilder();
2029 if (!isNullOrEmpty(schemaNodes)) {
2030 final SchemaNode node = schemaNodes.iterator().next();
2032 if (node instanceof RpcDefinition) {
2033 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2034 } else if (node instanceof NotificationDefinition) {
2035 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2038 sb.append(NEW_LINE);
2039 sb.append("<br>(Source path: <i>");
2040 sb.append(moduleSourcePath);
2041 sb.append("</i>):");
2042 sb.append(NEW_LINE);
2044 if (verboseClassComments) {
2046 sb.append(NEW_LINE);
2047 sb.append(YangTemplate.generateYangSnipet(schemaNodes));
2048 sb.append("</pre>");
2049 sb.append(NEW_LINE);
2052 return sb.toString();
2055 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2056 final StringBuilder sb = new StringBuilder();
2057 final String formattedDescription = YangTemplate.formatToParagraph(schemaNode.getDescription(), 0);
2059 if (!isNullOrEmpty(formattedDescription)) {
2060 sb.append(formattedDescription);
2061 sb.append(NEW_LINE);
2064 if (verboseClassComments) {
2065 final Module module = findParentModule(schemaContext, schemaNode);
2066 final StringBuilder linkToBuilderClass = new StringBuilder();
2067 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2068 final String className = namespace[namespace.length - 1];
2070 if (hasBuilderClass(schemaNode)) {
2071 linkToBuilderClass.append(className);
2072 linkToBuilderClass.append("Builder");
2076 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2077 sb.append(module.getName());
2079 sb.append(NEW_LINE);
2080 sb.append("<br>(Source path: <i>");
2081 sb.append(module.getModuleSourcePath());
2082 sb.append("</i>):");
2083 sb.append(NEW_LINE);
2085 sb.append(NEW_LINE);
2086 sb.append(YangTemplate.generateYangSnipet(schemaNode));
2087 sb.append("</pre>");
2088 sb.append(NEW_LINE);
2089 sb.append("The schema path to identify an instance is");
2090 sb.append(NEW_LINE);
2092 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2094 sb.append(NEW_LINE);
2096 if (hasBuilderClass(schemaNode)) {
2097 sb.append(NEW_LINE);
2098 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2099 sb.append(NEW_LINE);
2101 sb.append(linkToBuilderClass);
2102 sb.append(NEW_LINE);
2103 if (schemaNode instanceof ListSchemaNode) {
2104 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2105 if (keyDef != null && !keyDef.isEmpty()) {
2107 sb.append(className);
2110 sb.append(NEW_LINE);
2115 return sb.toString();
2118 private boolean hasBuilderClass(final SchemaNode schemaNode) {
2119 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2120 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2126 private boolean isNullOrEmpty(final String string) {
2127 return (string == null || string.isEmpty() ? true : false);
2130 private String createDescription(final Module module) {
2131 final StringBuilder sb = new StringBuilder();
2132 final String formattedDescription = YangTemplate.formatToParagraph(module.getDescription(), 0);
2134 if (!isNullOrEmpty(formattedDescription)) {
2135 sb.append(formattedDescription);
2136 sb.append(NEW_LINE);
2139 if (verboseClassComments) {
2141 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2142 sb.append(module.getName());
2144 sb.append(NEW_LINE);
2145 sb.append("<br>Source path: <i>");
2146 sb.append(module.getModuleSourcePath());
2147 sb.append("</i>):");
2148 sb.append(NEW_LINE);
2150 sb.append(NEW_LINE);
2151 sb.append(YangTemplate.generateYangSnipet(module));
2152 sb.append("</pre>");
2155 return sb.toString();
2158 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2159 for (final ModuleContext ctx : genCtx.values()) {
2160 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2161 if (result != null) {
2168 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2169 for (final ModuleContext ctx : genCtx.values()) {
2170 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2171 if (result != null) {
2178 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2179 for (final ModuleContext ctx : genCtx.values()) {
2180 final GeneratedTypeBuilder result = ctx.getCase(path);
2181 if (result != null) {
2188 public Map<Module, ModuleContext> getModuleContexts() {