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.BindingGeneratorUtil.parseToValidParamName;
16 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_OBJECT;
17 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_ROOT;
18 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIABLE;
19 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIER;
20 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.augmentable;
22 import static org.opendaylight.yangtools.binding.generator.util.Types.BOOLEAN;
23 import static org.opendaylight.yangtools.binding.generator.util.Types.FUTURE;
24 import static org.opendaylight.yangtools.binding.generator.util.Types.VOID;
25 import static org.opendaylight.yangtools.binding.generator.util.Types.typeForClass;
26 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
30 import com.google.common.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.ChoiceNode;
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.DataNodeIterator;
99 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
100 import org.opendaylight.yangtools.yang.model.util.UnionType;
101 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
102 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
103 import org.slf4j.Logger;
104 import org.slf4j.LoggerFactory;
106 public class BindingGeneratorImpl implements BindingGenerator {
107 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
108 private static final Splitter COLON_SPLITTER = Splitter.on(':');
109 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
110 private static final char NEW_LINE = '\n';
113 * Constant with the concrete name of identifier.
115 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
118 * Constant with the concrete name of namespace.
120 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
122 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
125 * When set to true, generated classes will include javadoc comments which
126 * are useful for users.
128 private final boolean verboseClassComments;
131 * Outer key represents the package name. Outer value represents map of all
132 * builders in the same package. Inner key represents the schema node name
133 * (in JAVA class/interface name format). Inner value represents instance of
134 * builder for schema node specified in key part.
136 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
139 * Provide methods for converting YANG types to JAVA types.
141 private TypeProvider typeProvider;
144 * Holds reference to schema context to resolve data of augmented element
145 * when creating augmentation builder
147 private SchemaContext schemaContext;
150 * Create a new binding generator with verboe comments.
152 * @deprecated Use {@link #BindingGeneratorImpl(boolean)} instead.
155 public BindingGeneratorImpl() {
160 * Create a new binding generator.
162 * @param verboseClassComments generate verbose comments
164 public BindingGeneratorImpl(final boolean verboseClassComments) {
165 this.verboseClassComments = verboseClassComments;
169 * Resolves generated types from <code>context</code> schema nodes of all
172 * Generated types are created for modules, groupings, types, containers,
173 * lists, choices, augments, rpcs, notification, identities.
176 * schema context which contains data about all schema nodes
178 * @return list of types (usually <code>GeneratedType</code>
179 * <code>GeneratedTransferObject</code>which are generated from
180 * <code>context</code> data.
181 * @throws IllegalArgumentException
182 * if arg <code>context</code> is null
183 * @throws IllegalStateException
184 * if <code>context</code> contain no modules
187 public List<Type> generateTypes(final SchemaContext context) {
188 checkArgument(context != null, "Schema Context reference cannot be NULL.");
189 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
190 schemaContext = context;
191 typeProvider = new TypeProviderImpl(context);
192 final Set<Module> modules = context.getModules();
193 return generateTypes(context, modules);
197 * Resolves generated types from <code>context</code> schema nodes only for
198 * modules specified in <code>modules</code>
200 * Generated types are created for modules, groupings, types, containers,
201 * lists, choices, augments, rpcs, notification, identities.
204 * schema context which contains data about all schema nodes
207 * set of modules for which schema nodes should be generated
209 * @return list of types (usually <code>GeneratedType</code> or
210 * <code>GeneratedTransferObject</code>) which:
212 * <li>are generated from <code>context</code> schema nodes and</li>
213 * <li>are also part of some of the module in <code>modules</code>
216 * @throws IllegalArgumentException
218 * <li>if arg <code>context</code> is null or</li>
219 * <li>if arg <code>modules</code> is null</li>
221 * @throws IllegalStateException
222 * if <code>context</code> contain no modules
225 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
226 checkArgument(context != null, "Schema Context reference cannot be NULL.");
227 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
228 checkArgument(modules != null, "Set of Modules cannot be NULL.");
230 schemaContext = context;
231 typeProvider = new TypeProviderImpl(context);
232 Module[] modulesArray = new Module[context.getModules().size()];
233 context.getModules().toArray(modulesArray);
234 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
235 genTypeBuilders = new HashMap<>();
237 for (Module contextModule : contextModules) {
238 moduleToGenTypes(contextModule, context);
240 for (Module contextModule : contextModules) {
241 allAugmentsToGenTypes(contextModule);
244 final List<Type> filteredGenTypes = new ArrayList<>();
245 for (Module m : modules) {
246 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
247 filteredGenTypes.addAll(ctx.getGeneratedTypes());
248 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
249 if (additionalTypes != null) {
250 filteredGenTypes.addAll(additionalTypes);
254 return filteredGenTypes;
257 private void moduleToGenTypes(final Module m, final SchemaContext context) {
258 genCtx.put(m, new ModuleContext());
259 allTypeDefinitionsToGenTypes(m);
260 groupingsToGenTypes(m, m.getGroupings());
261 rpcMethodsToGenType(m);
262 allIdentitiesToGenTypes(m, context);
263 notificationsToGenType(m);
265 if (!m.getChildNodes().isEmpty()) {
266 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
267 genCtx.get(m).addModuleNode(moduleType);
268 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
269 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
274 * Converts all extended type definitions of module to the list of
275 * <code>Type</code> objects.
278 * module from which is obtained set of type definitions
279 * @throws IllegalArgumentException
281 * <li>if module is null</li>
282 * <li>if name of module is null</li>
284 * @throws IllegalStateException
285 * if set of type definitions from module is null
287 private void allTypeDefinitionsToGenTypes(final Module module) {
288 checkArgument(module != null, "Module reference cannot be NULL.");
289 checkArgument(module.getName() != null, "Module name cannot be NULL.");
290 final DataNodeIterator it = new DataNodeIterator(module);
291 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
292 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
294 for (TypeDefinition<?> typedef : typeDefinitions) {
295 if (typedef != null) {
296 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
299 genCtx.get(module).addTypedefType(typedef.getPath(), type);
305 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
306 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
307 if (node.isAugmenting() || node.isAddedByUses()) {
310 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
311 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
312 genType.addComment(node.getDescription());
313 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
314 genType.setModuleName(module.getName());
315 genType.setReference(node.getReference());
316 genType.setSchemaPath(node.getPath().getPathFromRoot());
317 if (node instanceof DataNodeContainer) {
318 genCtx.get(module).addChildNodeType(node, genType);
319 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
320 processUsesAugments((DataNodeContainer) node, module);
325 private void containerToGenType(final Module module, final String basePackageName,
326 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
327 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
328 if (genType != null) {
329 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType);
330 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
334 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
335 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
336 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
337 if (genType != null) {
338 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), Types.listTypeFor(genType));
340 final List<String> listKeys = listKeys(node);
341 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
342 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
343 if (genTOBuilder != null) {
344 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
345 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
346 genTOBuilder.addImplementsType(identifierMarker);
347 genType.addImplementsType(identifiableMarker);
350 for (DataSchemaNode schemaNode : node.getChildNodes()) {
351 if (!schemaNode.isAugmenting()) {
352 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
357 if (genTOBuilder != null) {
358 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
359 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
360 genTOBuilder.setSUID(prop);
363 typeBuildersToGenTypes(module, genType, genTOBuilder);
367 private void processUsesAugments(final DataNodeContainer node, final Module module) {
368 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
369 for (UsesNode usesNode : node.getUses()) {
370 for (AugmentationSchema augment : usesNode.getAugmentations()) {
371 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
372 processUsesAugments(augment, module);
378 * Converts all <b>augmentation</b> of the module to the list
379 * <code>Type</code> objects.
382 * module from which is obtained list of all augmentation objects
383 * to iterate over them
384 * @throws IllegalArgumentException
386 * <li>if the module is null</li>
387 * <li>if the name of module is null</li>
389 * @throws IllegalStateException
390 * if set of augmentations from module is null
392 private void allAugmentsToGenTypes(final Module module) {
393 checkArgument(module != null, "Module reference cannot be NULL.");
394 checkArgument(module.getName() != null, "Module name cannot be NULL.");
395 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
397 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
398 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
399 for (AugmentationSchema augment : augmentations) {
400 augmentationToGenTypes(basePackageName, augment, module);
405 * Returns list of <code>AugmentationSchema</code> objects. The objects are
406 * sorted according to the length of their target path from the shortest to
410 * module from which is obtained list of all augmentation objects
411 * @return list of sorted <code>AugmentationSchema</code> objects obtained
412 * from <code>module</code>
413 * @throws IllegalArgumentException
415 * @throws IllegalStateException
416 * if set of module augmentations is null
418 private List<AugmentationSchema> resolveAugmentations(final Module module) {
419 checkArgument(module != null, "Module reference cannot be NULL.");
420 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
422 final Set<AugmentationSchema> augmentations = module.getAugmentations();
423 List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
424 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
426 return sortedAugmentations;
430 * Create GeneratedTypeBuilder object from module argument.
433 * Module object from which builder will be created
434 * @return <code>GeneratedTypeBuilder</code> which is internal
435 * representation of the module
436 * @throws IllegalArgumentException
439 private GeneratedTypeBuilder moduleToDataType(final Module module) {
440 checkArgument(module != null, "Module reference cannot be NULL.");
442 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
443 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
444 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
445 moduleDataTypeBuilder.addComment(module.getDescription());
446 moduleDataTypeBuilder.setDescription(createDescription(module));
447 moduleDataTypeBuilder.setReference(module.getReference());
448 return moduleDataTypeBuilder;
452 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
453 * to the list of <code>Type</code> objects. In addition are to containers
454 * and lists which belong to input or output also part of returning list.
457 * module from which is obtained set of all rpc objects to
459 * @throws IllegalArgumentException
461 * <li>if the module is null</li>
462 * <li>if the name of module is null</li>
464 * @throws IllegalStateException
465 * if set of rpcs from module is null
467 private void rpcMethodsToGenType(final Module module) {
468 checkArgument(module != null, "Module reference cannot be NULL.");
469 checkArgument(module.getName() != null, "Module name cannot be NULL.");
470 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
471 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
472 if (rpcDefinitions.isEmpty()) {
476 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
477 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
478 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
479 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
481 for (RpcDefinition rpc : rpcDefinitions) {
483 final String rpcName = BindingMapping.getClassName(rpc.getQName());
484 final String rpcMethodName = parseToValidParamName(rpcName);
485 final String rpcComment = rpc.getDescription();
486 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
487 final ContainerSchemaNode input = rpc.getInput();
488 final ContainerSchemaNode output = rpc.getOutput();
491 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
492 addImplementedInterfaceFromUses(input, inType);
493 inType.addImplementsType(DATA_OBJECT);
494 inType.addImplementsType(augmentable(inType));
495 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
496 genCtx.get(module).addChildNodeType(input, inType);
497 final GeneratedType inTypeInstance = inType.toInstance();
498 method.addParameter(inTypeInstance, "input");
501 Type outTypeInstance = VOID;
502 if (output != null) {
503 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
504 addImplementedInterfaceFromUses(output, outType);
505 outType.addImplementsType(DATA_OBJECT);
506 outType.addImplementsType(augmentable(outType));
507 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
508 genCtx.get(module).addChildNodeType(output, outType);
509 outTypeInstance = outType.toInstance();
512 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
513 method.setComment(rpcComment);
514 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
518 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
522 * Converts all <b>notifications</b> of the module to the list of
523 * <code>Type</code> objects. In addition are to this list added containers
524 * and lists which are part of this notification.
527 * module from which is obtained set of all notification objects
528 * to iterate over them
529 * @throws IllegalArgumentException
531 * <li>if the module equals null</li>
532 * <li>if the name of module equals null</li>
534 * @throws IllegalStateException
535 * if set of notifications from module is null
537 private void notificationsToGenType(final Module module) {
538 checkArgument(module != null, "Module reference cannot be NULL.");
539 checkArgument(module.getName() != null, "Module name cannot be NULL.");
540 final Set<NotificationDefinition> notifications = module.getNotifications();
541 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
542 if (notifications.isEmpty()) {
546 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
547 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
548 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
552 for (NotificationDefinition notification : notifications) {
553 if (notification != null) {
554 processUsesAugments(notification, module);
556 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
557 notification, BindingTypes.DATA_OBJECT, module);
558 notificationInterface.addImplementsType(NOTIFICATION);
559 genCtx.get(module).addChildNodeType(notification, notificationInterface);
561 // Notification object
562 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
563 notification.getChildNodes());
565 listenerInterface.addMethod("on" + notificationInterface.getName())
566 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
567 .setComment(notification.getDescription()).setReturnType(Types.VOID);
570 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
572 genCtx.get(module).addTopLevelNodeType(listenerInterface);
576 * Converts all <b>identities</b> of the module to the list of
577 * <code>Type</code> objects.
580 * module from which is obtained set of all identity objects to
583 * schema context only used as input parameter for method
584 * {@link identityToGenType}
587 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
588 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
589 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
591 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
592 for (IdentitySchemaNode identity : schemaIdentities) {
593 identityToGenType(module, basePackageName, identity, context);
599 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
600 * created transport object builder. If identity contains base identity then
601 * reference to base identity is added to superior identity as its extend.
602 * If identity doesn't contain base identity then only reference to abstract
603 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
604 * BaseIdentity} is added
608 * @param basePackageName
609 * string contains the module package name
611 * IdentitySchemaNode which contains data about identity
613 * SchemaContext which is used to get package and name
614 * information about base of identity
617 private void identityToGenType(final Module module, final String basePackageName,
618 final IdentitySchemaNode identity, final SchemaContext context) {
619 if (identity == null) {
622 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
623 final String genTypeName = BindingMapping.getClassName(identity.getQName());
624 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
625 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
626 if (baseIdentity == null) {
627 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
628 BaseIdentity.class.getSimpleName());
629 newType.setExtendsType(gto.toInstance());
631 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
632 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
634 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
635 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
637 newType.setExtendsType(gto);
639 newType.setAbstract(true);
640 newType.addComment(identity.getDescription());
641 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
642 newType.setReference(identity.getReference());
643 newType.setModuleName(module.getName());
644 newType.setSchemaPath(identity.getPath().getPathFromRoot());
646 final QName qname = identity.getQName();
647 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
649 genCtx.get(module).addIdentityType(identity.getQName(), newType);
652 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
654 StringBuilder sb = new StringBuilder("org.opendaylight.yangtools.yang.common.QName");
655 sb.append(".create(");
657 sb.append(name.getNamespace());
659 sb.append(name.getFormattedRevision());
661 sb.append(name.getLocalName());
664 return toBuilder.addConstant(typeForClass(QName.class), constantName, sb.toString());
668 * Converts all <b>groupings</b> of the module to the list of
669 * <code>Type</code> objects. Firstly are groupings sorted according mutual
670 * dependencies. At least dependent (independent) groupings are in the list
671 * saved at first positions. For every grouping the record is added to map
672 * {@link BindingGeneratorImpl#allGroupings allGroupings}
677 * of groupings from which types will be generated
680 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
681 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
682 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
684 for (GroupingDefinition grouping : groupingsSortedByDependencies) {
685 groupingToGenType(basePackageName, grouping, module);
690 * Converts individual grouping to GeneratedType. Firstly generated type
691 * builder is created and every child node of grouping is resolved to the
694 * @param basePackageName
695 * string contains the module package name
697 * GroupingDefinition which contains data about grouping
700 * @return GeneratedType which is generated from grouping (object of type
701 * <code>GroupingDefinition</code>)
703 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
704 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
705 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
706 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
707 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
708 groupingsToGenTypes(module, grouping.getGroupings());
709 processUsesAugments(grouping, module);
713 * Adds enumeration builder created from <code>enumTypeDef</code> to
714 * <code>typeBuilder</code>.
716 * Each <code>enumTypeDef</code> item is added to builder with its name and
720 * EnumTypeDefinition contains enum data
722 * string contains name which will be assigned to enumeration
725 * GeneratedTypeBuilder to which will be enum builder assigned
726 * @return enumeration builder which contains data from
727 * <code>enumTypeDef</code>
729 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
730 final GeneratedTypeBuilder typeBuilder) {
731 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
732 && (enumTypeDef.getQName().getLocalName() != null)) {
733 final String enumerationName = BindingMapping.getClassName(enumName);
734 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
735 enumBuilder.setDescription(enumTypeDef.getDescription());
736 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
743 * Generates type builder for <code>module</code>.
746 * Module which is source of package name for generated type
749 * string which is added to the module class name representation
751 * @return instance of GeneratedTypeBuilder which represents
752 * <code>module</code>.
753 * @throws IllegalArgumentException
754 * if <code>module</code> is null
756 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
757 checkArgument(module != null, "Module reference cannot be NULL.");
758 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
759 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
761 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
762 moduleBuilder.setDescription(createDescription(module));
763 moduleBuilder.setReference(module.getReference());
764 moduleBuilder.setModuleName(moduleName);
766 return moduleBuilder;
770 * Converts <code>augSchema</code> to list of <code>Type</code> which
771 * contains generated type for augmentation. In addition there are also
772 * generated types for all containers, list and choices which are child of
773 * <code>augSchema</code> node or a generated types for cases are added if
774 * augmented node is choice.
776 * @param augmentPackageName
777 * string with the name of the package to which the augmentation
780 * AugmentationSchema which is contains data about augmentation
781 * (target path, childs...)
784 * @param parentUsesNode
785 * @throws IllegalArgumentException
787 * <li>if <code>augmentPackageName</code> equals null</li>
788 * <li>if <code>augSchema</code> equals null</li>
790 * @throws IllegalStateException
791 * if augment target path is null
793 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
794 final Module module) {
795 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
796 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
797 checkState(augSchema.getTargetPath() != null,
798 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
800 processUsesAugments(augSchema, module);
801 final SchemaPath targetPath = augSchema.getTargetPath();
802 SchemaNode targetSchemaNode = null;
804 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
805 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
806 if (targetSchemaNode instanceof DerivableSchemaNode) {
807 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
809 if (targetSchemaNode == null) {
810 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
811 + " in module " + module.getName());
814 if (targetSchemaNode == null) {
815 throw new IllegalArgumentException("augment target not found: " + targetPath);
818 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
819 if (targetTypeBuilder == null) {
820 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
822 if (targetTypeBuilder == null) {
823 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
826 if (!(targetSchemaNode instanceof ChoiceNode)) {
827 String packageName = augmentPackageName;
828 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
829 targetTypeBuilder.getName());
830 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
833 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
834 (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
838 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
839 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
840 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
841 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
842 checkState(augSchema.getTargetPath() != null,
843 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
845 processUsesAugments(augSchema, module);
846 final SchemaPath targetPath = augSchema.getTargetPath();
847 SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
848 if (targetSchemaNode == null) {
849 throw new IllegalArgumentException("augment target not found: " + targetPath);
852 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
853 if (targetTypeBuilder == null) {
854 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
856 if (targetTypeBuilder == null) {
857 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
860 if (!(targetSchemaNode instanceof ChoiceNode)) {
861 String packageName = augmentPackageName;
862 if (usesNodeParent instanceof SchemaNode) {
863 packageName = packageNameForGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath(),
866 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
869 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
870 (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
875 * Convenient method to find node added by uses statement.
879 * @param parentUsesNode
880 * parent of uses node
881 * @return node from its original location in grouping
883 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
884 SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
886 if (!(targetGrouping instanceof GroupingDefinition)) {
887 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
890 GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
891 SchemaNode result = grouping;
892 for (QName node : targetPath.getPathFromRoot()) {
893 // finding by local name is valid, grouping cannot contain nodes
894 // with same name and different namespace
895 if (result instanceof DataNodeContainer) {
896 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
897 } else if (result instanceof ChoiceNode) {
898 result = ((ChoiceNode) result).getCaseNodeByName(node.getLocalName());
901 if (result == null) {
905 boolean fromUses = ((DataSchemaNode) result).isAddedByUses();
906 Iterator<UsesNode> groupingUses = grouping.getUses().iterator();
907 while (groupingUses.hasNext() && fromUses) {
908 result = findOriginalTargetFromGrouping(targetPath, groupingUses.next());
909 if (result != null) {
910 fromUses = ((DataSchemaNode) result).isAddedByUses();
914 // this indicates invalid yang and thus possible bug in code because
915 // invalid yang should be already spotted by parser
916 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
919 return (DataSchemaNode) result;
923 * Returns a generated type builder for an augmentation.
925 * The name of the type builder is equal to the name of augmented node with
926 * serial number as suffix.
930 * @param augmentPackageName
931 * string with contains the package name to which the augment
933 * @param basePackageName
934 * string with the package name to which the augmented node
936 * @param targetTypeRef
939 * augmentation schema which contains data about the child nodes
940 * and uses of augment
941 * @return generated type builder for augment
943 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
944 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
945 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
946 if (augmentBuilders == null) {
947 augmentBuilders = new HashMap<>();
948 genTypeBuilders.put(augmentPackageName, augmentBuilders);
950 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
953 if (augIdentifier != null) {
954 augTypeName = BindingMapping.getClassName(augIdentifier);
956 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
959 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
961 augTypeBuilder.addImplementsType(DATA_OBJECT);
962 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
963 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
965 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
966 augmentBuilders.put(augTypeName, augTypeBuilder);
968 if(!augSchema.getChildNodes().isEmpty()) {
969 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
970 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
973 genCtx.get(module).addAugmentType(augTypeBuilder);
974 return augTypeBuilder;
979 * @param unknownSchemaNodes
980 * @return nodeParameter of UnknownSchemaNode
982 private String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
983 for (UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
984 final QName nodeType = unknownSchemaNode.getNodeType();
985 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
986 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
987 return unknownSchemaNode.getNodeParameter();
994 * Returns first unique name for the augment generated type builder. The
995 * generated type builder name for augment consists from name of augmented
996 * node and serial number of its augmentation.
999 * map of builders which were created in the package to which the
1000 * augmentation belongs
1001 * @param genTypeName
1002 * string with name of augmented node
1003 * @return string with unique name for augmentation builder
1005 private String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1007 if (builders != null) {
1008 while (builders.containsKey(genTypeName + index)) {
1012 return genTypeName + index;
1016 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1017 * node for which <code>typeBuilder</code> was created.
1019 * The subnodes aren't mapped to the methods if they are part of grouping or
1020 * augment (in this case are already part of them).
1024 * @param basePackageName
1025 * string contains the module package name
1027 * generated type builder which represents any node. The subnodes
1028 * of this node are added to the <code>typeBuilder</code> as
1029 * methods. The subnode can be of type leaf, leaf-list, list,
1030 * container, choice.
1033 * @param schemaNodes
1034 * set of data schema nodes which are the children of the node
1035 * for which <code>typeBuilder</code> was created
1036 * @return generated type builder which is the same builder as input
1037 * parameter. The getter methods (representing child nodes) could be
1040 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1041 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1042 if (schemaNodes != null && parent != null) {
1043 for (DataSchemaNode schemaNode : schemaNodes) {
1044 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1045 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1053 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1054 * node for which <code>typeBuilder</code> was created.
1058 * @param basePackageName
1059 * string contains the module package name
1060 * @param typeBuilder
1061 * generated type builder which represents any node. The subnodes
1062 * of this node are added to the <code>typeBuilder</code> as
1063 * methods. The subnode can be of type leaf, leaf-list, list,
1064 * container, choice.
1067 * @param schemaNodes
1068 * set of data schema nodes which are the children of the node
1069 * for which <code>typeBuilder</code> was created
1070 * @return generated type builder which is the same object as the input
1071 * parameter <code>typeBuilder</code>. The getter method could be
1074 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1075 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1076 final Iterable<DataSchemaNode> schemaNodes) {
1077 if ((schemaNodes != null) && (typeBuilder != null)) {
1078 for (DataSchemaNode schemaNode : schemaNodes) {
1079 if (!schemaNode.isAugmenting()) {
1080 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1088 * Adds to <code>typeBuilder</code> a method which is derived from
1089 * <code>schemaNode</code>.
1091 * @param basePackageName
1092 * string with the module package name
1094 * data schema node which is added to <code>typeBuilder</code> as
1096 * @param typeBuilder
1097 * generated type builder to which is <code>schemaNode</code>
1098 * added as a method.
1104 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1105 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1106 if (node != null && typeBuilder != null) {
1107 if (node instanceof LeafSchemaNode) {
1108 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node);
1109 } else if (node instanceof LeafListSchemaNode) {
1110 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node);
1111 } else if (node instanceof ContainerSchemaNode) {
1112 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1113 } else if (node instanceof ListSchemaNode) {
1114 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1115 } else if (node instanceof ChoiceNode) {
1116 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceNode) node);
1118 // TODO: anyxml not yet supported
1119 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1120 typeBuilder.getFullyQualifiedName());
1126 * Converts <code>choiceNode</code> to the list of generated types for
1127 * choice and its cases.
1129 * The package names for choice and for its cases are created as
1130 * concatenation of the module package (<code>basePackageName</code>) and
1131 * names of all parents node.
1135 * @param basePackageName
1136 * string with the module package name
1140 * choice node which is mapped to generated type. Also child
1141 * nodes - cases are mapped to generated types.
1142 * @throws IllegalArgumentException
1144 * <li>if <code>basePackageName</code> is null</li>
1145 * <li>if <code>choiceNode</code> is null</li>
1148 private void choiceToGeneratedType(final Module module, final String basePackageName,
1149 final GeneratedTypeBuilder parent, final ChoiceNode choiceNode) {
1150 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1151 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1153 if (!choiceNode.isAddedByUses()) {
1154 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1155 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1156 constructGetter(parent, choiceNode.getQName().getLocalName(), choiceNode.getDescription(),
1158 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1159 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1160 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1165 * Converts <code>caseNodes</code> set to list of corresponding generated
1168 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1169 * created generated type builder. The package names for the builder is
1170 * created as concatenation of the module package (
1171 * <code>basePackageName</code>) and names of all parents nodes of the
1172 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1173 * between every case builder and <i>choice</i> type
1177 * @param basePackageName
1178 * string with the module package name
1179 * @param refChoiceType
1180 * type which represents superior <i>case</i>
1182 * choice case node which is mapped to generated type
1183 * @return list of generated types for <code>caseNodes</code>.
1184 * @throws IllegalArgumentException
1186 * <li>if <code>basePackageName</code> equals null</li>
1187 * <li>if <code>refChoiceType</code> equals null</li>
1188 * <li>if <code>caseNodes</code> equals null</li>
1191 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1192 final Type refChoiceType, final ChoiceNode choiceNode) {
1193 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1194 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1195 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1197 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1198 if (caseNodes == null) {
1202 for (ChoiceCaseNode caseNode : caseNodes) {
1203 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1204 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1205 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1206 caseTypeBuilder.addImplementsType(refChoiceType);
1207 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1208 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1209 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1210 if (caseChildNodes != null) {
1211 Object parentNode = null;
1212 final SchemaPath nodeSp = choiceNode.getPath();
1213 parentNode = findDataSchemaNode(schemaContext, nodeSp.getParent());
1216 if (parentNode instanceof AugmentationSchema) {
1217 final AugmentationSchema augSchema = (AugmentationSchema) parentNode;
1218 final SchemaPath targetPath = augSchema.getTargetPath();
1219 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1220 if (targetSchemaNode instanceof DataSchemaNode
1221 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1222 if (targetSchemaNode instanceof DerivableSchemaNode) {
1223 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1225 if (targetSchemaNode == null) {
1226 throw new IllegalStateException(
1227 "Failed to find target node from grouping for augmentation " + augSchema
1228 + " in module " + module.getName());
1231 parent = targetSchemaNode;
1233 final SchemaPath sp = choiceNode.getPath();
1234 parent = findDataSchemaNode(schemaContext, sp.getParent());
1236 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1237 if (childOfType == null) {
1238 childOfType = findGroupingByPath(parent.getPath());
1240 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1244 processUsesAugments(caseNode, module);
1249 * Generates list of generated types for all the cases of a choice which are
1250 * added to the choice through the augment.
1254 * @param basePackageName
1255 * string contains name of package to which augment belongs. If
1256 * an augmented choice is from an other package (pcg1) than an
1257 * augmenting choice (pcg2) then case's of the augmenting choice
1258 * will belong to pcg2.
1260 * Type which represents target choice
1262 * node which represents target choice
1263 * @param augmentedNodes
1264 * set of choice case nodes for which is checked if are/aren't
1265 * added to choice through augmentation
1266 * @return list of generated types which represents augmented cases of
1267 * choice <code>refChoiceType</code>
1268 * @throws IllegalArgumentException
1270 * <li>if <code>basePackageName</code> is null</li>
1271 * <li>if <code>targetType</code> is null</li>
1272 * <li>if <code>augmentedNodes</code> is null</li>
1275 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1276 final Type targetType, final ChoiceNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
1277 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1278 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1279 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1281 for (DataSchemaNode caseNode : augmentedNodes) {
1282 if (caseNode != null) {
1283 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1284 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1285 caseTypeBuilder.addImplementsType(targetType);
1287 SchemaNode parent = null;
1288 final SchemaPath nodeSp = targetNode.getPath();
1289 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1291 GeneratedTypeBuilder childOfType = null;
1292 if (parent instanceof Module) {
1293 childOfType = genCtx.get(parent).getModuleNode();
1294 } else if (parent instanceof ChoiceCaseNode) {
1295 childOfType = findCaseByPath(parent.getPath());
1296 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1297 childOfType = findChildNodeByPath(parent.getPath());
1298 } else if (parent instanceof GroupingDefinition) {
1299 childOfType = findGroupingByPath(parent.getPath());
1302 if (childOfType == null) {
1303 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1306 ChoiceCaseNode node = null;
1307 if (caseNode instanceof ChoiceCaseNode) {
1308 node = (ChoiceCaseNode) caseNode;
1310 node = targetNode.getCaseNodeByName(caseNode.getQName().getLocalName());
1312 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1313 if (childNodes != null) {
1314 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1316 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1317 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1323 * Converts <code>leaf</code> to the getter method which is added to
1324 * <code>typeBuilder</code>.
1326 * @param typeBuilder
1327 * generated type builder to which is added getter method as
1328 * <code>leaf</code> mapping
1330 * leaf schema node which is mapped as getter method which is
1331 * added to <code>typeBuilder</code>
1332 * @return boolean value
1334 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1336 * <li>true - in other cases</li>
1339 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf) {
1340 Type returnType = null;
1341 if ((leaf != null) && (typeBuilder != null)) {
1342 final String leafName = leaf.getQName().getLocalName();
1343 String leafDesc = leaf.getDescription();
1344 if (leafDesc == null) {
1348 final Module parentModule = findParentModule(schemaContext, leaf);
1349 if (leafName != null && !leaf.isAddedByUses()) {
1350 final TypeDefinition<?> typeDef = leaf.getType();
1352 GeneratedTOBuilder genTOBuilder;
1353 if (typeDef instanceof EnumTypeDefinition) {
1354 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1355 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1356 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1359 if (enumBuilder != null) {
1360 returnType = enumBuilder.toInstance(typeBuilder);
1362 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1363 } else if (typeDef instanceof UnionType) {
1364 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1365 if (genTOBuilder != null) {
1366 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1368 } else if (typeDef instanceof BitsTypeDefinition) {
1369 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1370 if (genTOBuilder != null) {
1371 returnType = genTOBuilder.toInstance();
1374 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1375 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1377 if (returnType != null) {
1378 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1379 processContextRefExtension(leaf, getter, parentModule);
1386 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1387 final Module module) {
1388 for (UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1389 final QName nodeType = node.getNodeType();
1390 if ("context-reference".equals(nodeType.getLocalName())) {
1391 final String nodeParam = node.getNodeParameter();
1392 IdentitySchemaNode identity = null;
1393 String basePackageName = null;
1394 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1395 final Iterator<String> iterator = splittedElement.iterator();
1396 final int length = Iterables.size(splittedElement);
1398 identity = findIdentityByName(module.getIdentities(), iterator.next());
1399 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1400 } else if (length == 2) {
1401 String prefix = iterator.next();
1402 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1403 if (dependentModule == null) {
1404 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1407 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1408 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1410 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1413 if (identity == null) {
1414 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1418 final Class<RoutingContext> clazz = RoutingContext.class;
1419 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1420 clazz.getSimpleName());
1421 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1422 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1423 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1428 private IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1429 for (IdentitySchemaNode id : identities) {
1430 if (id.getQName().getLocalName().equals(name)) {
1437 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1438 for (ModuleImport imp : imports) {
1439 if (imp.getPrefix().equals(prefix)) {
1440 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1446 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1447 final boolean isReadOnly, final Module module) {
1448 if ((leaf != null) && (toBuilder != null)) {
1449 final String leafName = leaf.getQName().getLocalName();
1450 String leafDesc = leaf.getDescription();
1451 if (leafDesc == null) {
1455 if (leafName != null) {
1456 Type returnType = null;
1457 final TypeDefinition<?> typeDef = leaf.getType();
1458 if (typeDef instanceof UnionTypeDefinition) {
1459 // GeneratedType for this type definition should be already
1461 QName qname = typeDef.getQName();
1462 Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1463 qname.getRevision());
1464 final ModuleContext mc = genCtx.get(unionModule);
1465 returnType = mc.getTypedefs().get(typeDef.getPath());
1467 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1469 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1476 * Converts <code>leaf</code> schema node to property of generated TO
1480 * generated TO builder to which is <code>leaf</code> added as
1483 * leaf schema node which is added to <code>toBuilder</code> as
1488 * boolean value which says if leaf property is|isn't read only
1489 * @return boolean value
1491 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1492 * name equals null or if leaf is added by <i>uses</i>.</li>
1493 * <li>true - other cases</li>
1496 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1497 final Type returnType, final boolean isReadOnly) {
1498 if (returnType == null) {
1501 final String leafName = leaf.getQName().getLocalName();
1502 final String leafDesc = leaf.getDescription();
1503 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(parseToValidParamName(leafName));
1504 propBuilder.setReadOnly(isReadOnly);
1505 propBuilder.setReturnType(returnType);
1506 propBuilder.setComment(leafDesc);
1507 toBuilder.addEqualsIdentity(propBuilder);
1508 toBuilder.addHashIdentity(propBuilder);
1509 toBuilder.addToStringProperty(propBuilder);
1514 * Converts <code>node</code> leaf list schema node to getter method of
1515 * <code>typeBuilder</code>.
1517 * @param typeBuilder
1518 * generated type builder to which is <code>node</code> added as
1521 * leaf list schema node which is added to
1522 * <code>typeBuilder</code> as getter method
1523 * @return boolean value
1525 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1526 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1527 * <li>false - other cases</li>
1530 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node) {
1531 if ((node != null) && (typeBuilder != null)) {
1532 final QName nodeName = node.getQName();
1534 if (nodeName != null && !node.isAddedByUses()) {
1535 final TypeDefinition<?> typeDef = node.getType();
1536 final Module parentModule = findParentModule(schemaContext, node);
1538 Type returnType = null;
1539 if (typeDef instanceof EnumTypeDefinition) {
1540 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1541 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1542 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1544 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1545 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1546 } else if (typeDef instanceof UnionType) {
1547 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1548 if (genTOBuilder != null) {
1549 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1551 } else if (typeDef instanceof BitsTypeDefinition) {
1552 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1553 returnType = genTOBuilder.toInstance();
1555 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1556 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1559 final ParameterizedType listType = Types.listTypeFor(returnType);
1560 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1567 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1568 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1569 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1570 genTOBuilder.getName());
1572 returnType.setDescription(typeDef.getDescription());
1573 returnType.setReference(typeDef.getReference());
1574 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1575 returnType.setModuleName(parentModule.getName());
1577 genTOBuilder.setTypedef(true);
1578 genTOBuilder.setIsUnion(true);
1579 ((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1582 final GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),
1583 genTOBuilder.getName() + "Builder");
1584 unionBuilder.setIsUnionBuilder(true);
1585 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1586 method.setReturnType(returnType);
1587 method.addParameter(Types.STRING, "defaultValue");
1588 method.setAccessModifier(AccessModifier.PUBLIC);
1589 method.setStatic(true);
1591 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1592 if (types == null) {
1593 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1594 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1596 types.add(unionBuilder.toInstance());
1598 return returnType.toInstance();
1601 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1602 final Module module) {
1603 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1607 * Instantiates generated type builder with <code>packageName</code> and
1608 * <code>schemaNode</code>.
1610 * The new builder always implements
1611 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br />
1612 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1613 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1614 * Augmentable}.<br />
1615 * If <code>schemaNode</code> is instance of
1616 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1617 * DataNodeContainer} it can also implement nodes which are specified in
1620 * @param packageName
1621 * string with the name of the package to which
1622 * <code>schemaNode</code> belongs.
1624 * schema node for which is created generated type builder
1626 * parent type (can be null)
1627 * @return generated type builder <code>schemaNode</code>
1629 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1630 final Type parent, final Module module) {
1631 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1632 if (parent == null) {
1633 it.addImplementsType(DATA_OBJECT);
1635 it.addImplementsType(BindingTypes.childOf(parent));
1637 if (!(schemaNode instanceof GroupingDefinition)) {
1638 it.addImplementsType(augmentable(it));
1641 if (schemaNode instanceof DataNodeContainer) {
1642 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1643 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1650 * Wraps the calling of the same overloaded method.
1652 * @param packageName
1653 * string with the package name to which returning generated type
1656 * schema node which provide data about the schema node name
1657 * @return generated type builder for <code>schemaNode</code>
1659 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1660 return addRawInterfaceDefinition(packageName, schemaNode, "");
1664 * Returns reference to generated type builder for specified
1665 * <code>schemaNode</code> with <code>packageName</code>.
1667 * Firstly the generated type builder is searched in
1668 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1669 * found it is created and added to <code>genTypeBuilders</code>.
1671 * @param packageName
1672 * string with the package name to which returning generated type
1675 * schema node which provide data about the schema node name
1677 * return type name prefix
1678 * @return generated type builder for <code>schemaNode</code>
1679 * @throws IllegalArgumentException
1681 * <li>if <code>schemaNode</code> is null</li>
1682 * <li>if <code>packageName</code> is null</li>
1683 * <li>if QName of schema node is null</li>
1684 * <li>if schemaNode name is null</li>
1688 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1689 final String prefix) {
1690 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1691 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1692 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1693 final String schemaNodeName = schemaNode.getQName().getLocalName();
1694 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1697 if (prefix == null) {
1698 genTypeName = BindingMapping.getClassName(schemaNodeName);
1700 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1703 // FIXME: Validation of name conflict
1704 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1705 final Module module = findParentModule(schemaContext, schemaNode);
1706 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1707 newType.addComment(schemaNode.getDescription());
1708 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1709 newType.setReference(schemaNode.getReference());
1710 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1711 newType.setModuleName(module.getName());
1713 if (!genTypeBuilders.containsKey(packageName)) {
1714 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1715 builders.put(genTypeName, newType);
1716 genTypeBuilders.put(packageName, builders);
1718 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1719 if (!builders.containsKey(genTypeName)) {
1720 builders.put(genTypeName, newType);
1727 * Creates the name of the getter method name from <code>localName</code>.
1730 * string with the name of the getter method
1733 * @return string with the name of the getter method for
1734 * <code>methodName</code> in JAVA method format
1736 public static String getterMethodName(final String localName, final Type returnType) {
1737 final StringBuilder method = new StringBuilder();
1738 if (BOOLEAN.equals(returnType)) {
1739 method.append("is");
1741 method.append("get");
1743 String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1744 method.append(name);
1745 return method.toString();
1749 * Created a method signature builder as part of
1750 * <code>interfaceBuilder</code>.
1752 * The method signature builder is created for the getter method of
1753 * <code>schemaNodeName</code>. Also <code>comment</code> and
1754 * <code>returnType</code> information are added to the builder.
1756 * @param interfaceBuilder
1757 * generated type builder for which the getter method should be
1759 * @param schemaNodeName
1760 * string with schema node name. The name will be the part of the
1761 * getter method name.
1763 * string with comment for the getter method
1765 * type which represents the return type of the getter method
1766 * @return method signature builder which represents the getter method of
1767 * <code>interfaceBuilder</code>
1769 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1770 final String schemaNodeName, final String comment, final Type returnType) {
1771 final MethodSignatureBuilder getMethod = interfaceBuilder
1772 .addMethod(getterMethodName(schemaNodeName, returnType));
1773 getMethod.setComment(comment);
1774 getMethod.setReturnType(returnType);
1779 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1780 * or to <code>genTOBuilder</code> as property.
1782 * @param basePackageName
1783 * string contains the module package name
1785 * data schema node which should be added as getter method to
1786 * <code>typeBuilder</code> or as a property to
1787 * <code>genTOBuilder</code> if is part of the list key
1788 * @param typeBuilder
1789 * generated type builder for the list schema node
1790 * @param genTOBuilder
1791 * generated TO builder for the list keys
1793 * list of string which contains names of the list keys
1796 * @throws IllegalArgumentException
1798 * <li>if <code>schemaNode</code> equals null</li>
1799 * <li>if <code>typeBuilder</code> equals null</li>
1802 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1803 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1804 final Module module) {
1805 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1806 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1808 if (schemaNode instanceof LeafSchemaNode) {
1809 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1810 final String leafName = leaf.getQName().getLocalName();
1811 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf);
1812 if (listKeys.contains(leafName)) {
1814 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1816 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1819 } else if (!schemaNode.isAddedByUses()) {
1820 if (schemaNode instanceof LeafListSchemaNode) {
1821 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode);
1822 } else if (schemaNode instanceof ContainerSchemaNode) {
1823 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1824 } else if (schemaNode instanceof ChoiceNode) {
1825 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceNode) schemaNode);
1826 } else if (schemaNode instanceof ListSchemaNode) {
1827 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1832 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1833 final GeneratedTOBuilder genTOBuilder) {
1834 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1836 if (genTOBuilder != null) {
1837 GeneratedTransferObject genTO = genTOBuilder.toInstance();
1838 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
1839 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1844 * Selects the names of the list keys from <code>list</code> and returns
1845 * them as the list of the strings
1848 * of string with names of the list keys
1849 * @return list of string which represents names of the list keys. If the
1850 * <code>list</code> contains no keys then the empty list is
1853 private List<String> listKeys(final ListSchemaNode list) {
1854 final List<String> listKeys = new ArrayList<>();
1856 List<QName> keyDefinition = list.getKeyDefinition();
1857 if (keyDefinition != null) {
1858 for (QName keyDef : keyDefinition) {
1859 listKeys.add(keyDef.getLocalName());
1866 * Generates for the <code>list</code> which contains any list keys special
1867 * generated TO builder.
1869 * @param packageName
1870 * string with package name to which the list belongs
1872 * list schema node which is source of data about the list name
1873 * @return generated TO builder which represents the keys of the
1874 * <code>list</code> or null if <code>list</code> is null or list of
1875 * key definitions is null or empty.
1877 private GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1878 GeneratedTOBuilder genTOBuilder = null;
1879 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1880 final String listName = list.getQName().getLocalName() + "Key";
1881 final String genTOName = BindingMapping.getClassName(listName);
1882 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1884 return genTOBuilder;
1888 * Builds generated TO builders for <code>typeDef</code> of type
1889 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
1890 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
1891 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
1892 * enclosing transfer object.
1894 * If more then one generated TO builder is created for enclosing then all
1895 * of the generated TO builders are added to <code>typeBuilder</code> as
1896 * enclosing transfer objects.
1899 * type definition which can be of type <code>UnionType</code> or
1900 * <code>BitsTypeDefinition</code>
1901 * @param typeBuilder
1902 * generated type builder to which is added generated TO created
1903 * from <code>typeDef</code>
1905 * string with name for generated TO builder
1907 * @return generated TO builder for <code>typeDef</code>
1909 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
1910 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1911 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
1912 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
1913 final String packageName = typeBuilder.getFullyQualifiedName();
1914 if (typeDef instanceof UnionTypeDefinition) {
1915 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
1916 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
1917 classNameFromLeaf, leaf);
1918 genTOBuilders.addAll(types);
1920 GeneratedTOBuilder resultTOBuilder = null;
1921 if (types.isEmpty()) {
1922 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
1924 resultTOBuilder = types.remove(0);
1925 for (GeneratedTOBuilder genTOBuilder : types) {
1926 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1929 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1930 genPropBuilder.setReturnType(Types.primitiveType("char[]", null));
1931 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1932 resultTOBuilder.addHashIdentity(genPropBuilder);
1933 resultTOBuilder.addToStringProperty(genPropBuilder);
1935 } else if (typeDef instanceof BitsTypeDefinition) {
1936 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
1937 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
1939 if (genTOBuilders != null && !genTOBuilders.isEmpty()) {
1940 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1941 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1943 return genTOBuilders.get(0);
1950 * Adds the implemented types to type builder.
1952 * The method passes through the list of <i>uses</i> in
1953 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1954 * generated type from {@link BindingGeneratorImpl#allGroupings
1955 * allGroupings} which is added as <i>implements type</i> to
1956 * <code>builder</code>
1958 * @param dataNodeContainer
1959 * element which contains the list of used YANG groupings
1961 * builder to which are added implemented types according to
1962 * <code>dataNodeContainer</code>
1963 * @return generated type builder with all implemented types
1965 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1966 final GeneratedTypeBuilder builder) {
1967 for (UsesNode usesNode : dataNodeContainer.getUses()) {
1968 if (usesNode.getGroupingPath() != null) {
1969 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
1970 if (genType == null) {
1971 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1972 + builder.getName());
1975 builder.addImplementsType(genType);
1977 builder.addComment(genType.getDescription());
1978 builder.setDescription(genType.getDescription());
1979 builder.setModuleName(genType.getModuleName());
1980 builder.setReference(genType.getReference());
1981 builder.setSchemaPath(genType.getSchemaPath());
1988 private boolean isNullOrEmpty(final Collection<?> list) {
1989 return (list == null || list.isEmpty() ? true : false);
1992 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
1993 final StringBuilder sb = new StringBuilder();
1995 if (!isNullOrEmpty(schemaNodes)) {
1996 final SchemaNode node = schemaNodes.iterator().next();
1998 if (node instanceof RpcDefinition) {
1999 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2000 } else if (node instanceof NotificationDefinition) {
2001 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2004 sb.append(NEW_LINE);
2005 sb.append("<br />(Source path: <i>");
2006 sb.append(moduleSourcePath);
2007 sb.append("</i>):");
2008 sb.append(NEW_LINE);
2010 if (verboseClassComments) {
2012 sb.append(NEW_LINE);
2013 sb.append(YangTemplate.generateYangSnipet(schemaNodes));
2014 sb.append("</pre>");
2015 sb.append(NEW_LINE);
2018 return sb.toString();
2021 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2022 final StringBuilder sb = new StringBuilder();
2023 final String formattedDescription = YangTemplate.formatToParagraph(schemaNode.getDescription(), 0);
2025 if (!isNullOrEmpty(formattedDescription)) {
2026 sb.append(formattedDescription);
2027 sb.append(NEW_LINE);
2030 if (verboseClassComments) {
2031 final Module module = findParentModule(schemaContext, schemaNode);
2032 final StringBuilder linkToBuilderClass = new StringBuilder();
2033 final StringBuilder linkToKeyClass = new StringBuilder();
2034 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2035 String className = namespace[namespace.length - 1];
2037 if (hasBuilderClass(schemaNode)) {
2038 linkToBuilderClass.append(className);
2039 linkToBuilderClass.append("Builder");
2041 if (schemaNode instanceof ListSchemaNode) {
2042 linkToKeyClass.append(className);
2043 linkToKeyClass.append("Key");
2048 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2049 sb.append(module.getName());
2051 sb.append(NEW_LINE);
2052 sb.append("<br />(Source path: <i>");
2053 sb.append(module.getModuleSourcePath());
2054 sb.append("</i>):");
2055 sb.append(NEW_LINE);
2057 sb.append(NEW_LINE);
2058 sb.append(YangTemplate.generateYangSnipet(schemaNode));
2059 sb.append("</pre>");
2060 sb.append(NEW_LINE);
2061 sb.append("The schema path to identify an instance is");
2062 sb.append(NEW_LINE);
2064 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2066 sb.append(NEW_LINE);
2068 if (hasBuilderClass(schemaNode)) {
2069 sb.append(NEW_LINE);
2070 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2071 sb.append(NEW_LINE);
2073 sb.append(linkToBuilderClass);
2074 if (schemaNode instanceof ListSchemaNode) {
2076 sb.append(linkToKeyClass);
2078 sb.append(NEW_LINE);
2082 return sb.toString();
2085 private boolean hasBuilderClass(final SchemaNode schemaNode) {
2086 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2087 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2093 private boolean isNullOrEmpty(final String string) {
2094 return (string == null || string.isEmpty() ? true : false);
2097 private String createDescription(final Module module) {
2098 final StringBuilder sb = new StringBuilder();
2099 final String formattedDescription = YangTemplate.formatToParagraph(module.getDescription(), 0);
2101 if (!isNullOrEmpty(formattedDescription)) {
2102 sb.append(formattedDescription);
2103 sb.append(NEW_LINE);
2106 if (verboseClassComments) {
2108 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2109 sb.append(module.getName());
2111 sb.append(NEW_LINE);
2112 sb.append("<br />Source path: <i>");
2113 sb.append(module.getModuleSourcePath());
2114 sb.append("</i>):");
2115 sb.append(NEW_LINE);
2117 sb.append(NEW_LINE);
2118 sb.append(YangTemplate.generateYangSnipet(module));
2119 sb.append("</pre>");
2122 return sb.toString();
2125 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2126 for (ModuleContext ctx : genCtx.values()) {
2127 GeneratedTypeBuilder result = ctx.getChildNode(path);
2128 if (result != null) {
2135 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2136 for (ModuleContext ctx : genCtx.values()) {
2137 GeneratedTypeBuilder result = ctx.getGrouping(path);
2138 if (result != null) {
2145 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2146 for (ModuleContext ctx : genCtx.values()) {
2147 GeneratedTypeBuilder result = ctx.getCase(path);
2148 if (result != null) {
2155 public Map<Module, ModuleContext> getModuleContexts() {