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;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
43 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
44 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
45 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
46 import org.opendaylight.yangtools.binding.generator.util.Types;
47 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
48 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
49 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
50 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
51 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
52 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
53 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
54 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
55 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
56 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
57 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
58 import org.opendaylight.yangtools.sal.binding.model.api.Type;
59 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
60 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
61 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
62 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
66 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
67 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
68 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
69 import org.opendaylight.yangtools.yang.binding.BindingMapping;
70 import org.opendaylight.yangtools.yang.binding.DataContainer;
71 import org.opendaylight.yangtools.yang.binding.RpcService;
72 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
73 import org.opendaylight.yangtools.yang.common.QName;
74 import org.opendaylight.yangtools.yang.common.RpcResult;
75 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
76 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
77 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
78 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
80 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
83 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.Module;
88 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
89 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
90 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
91 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
92 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
94 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
95 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.UsesNode;
97 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
98 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
99 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
100 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
101 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
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';
115 * Constant with the concrete name of identifier.
117 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
120 * Constant with the concrete name of namespace.
122 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
124 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
127 * When set to true, generated classes will include javadoc comments which
128 * are useful for users.
130 private final boolean verboseClassComments;
133 * Outer key represents the package name. Outer value represents map of all
134 * builders in the same package. Inner key represents the schema node name
135 * (in JAVA class/interface name format). Inner value represents instance of
136 * builder for schema node specified in key part.
138 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
141 * Provide methods for converting YANG types to JAVA types.
143 private TypeProvider typeProvider;
146 * Holds reference to schema context to resolve data of augmented element
147 * when creating augmentation builder
149 private SchemaContext schemaContext;
152 * Create a new binding generator with verboe comments.
154 * @deprecated Use {@link #BindingGeneratorImpl(boolean)} instead.
157 public BindingGeneratorImpl() {
162 * Create a new binding generator.
164 * @param verboseClassComments generate verbose comments
166 public BindingGeneratorImpl(final boolean verboseClassComments) {
167 this.verboseClassComments = verboseClassComments;
171 * Resolves generated types from <code>context</code> schema nodes of all
174 * Generated types are created for modules, groupings, types, containers,
175 * lists, choices, augments, rpcs, notification, identities.
178 * schema context which contains data about all schema nodes
180 * @return list of types (usually <code>GeneratedType</code>
181 * <code>GeneratedTransferObject</code>which are generated from
182 * <code>context</code> data.
183 * @throws IllegalArgumentException
184 * if arg <code>context</code> is null
185 * @throws IllegalStateException
186 * if <code>context</code> contain no modules
189 public List<Type> generateTypes(final SchemaContext context) {
190 checkArgument(context != null, "Schema Context reference cannot be NULL.");
191 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
192 schemaContext = context;
193 typeProvider = new TypeProviderImpl(context);
194 final Set<Module> modules = context.getModules();
195 return generateTypes(context, modules);
199 * Resolves generated types from <code>context</code> schema nodes only for
200 * modules specified in <code>modules</code>
202 * Generated types are created for modules, groupings, types, containers,
203 * lists, choices, augments, rpcs, notification, identities.
206 * schema context which contains data about all schema nodes
209 * set of modules for which schema nodes should be generated
211 * @return list of types (usually <code>GeneratedType</code> or
212 * <code>GeneratedTransferObject</code>) which:
214 * <li>are generated from <code>context</code> schema nodes and</li>
215 * <li>are also part of some of the module in <code>modules</code>
218 * @throws IllegalArgumentException
220 * <li>if arg <code>context</code> is null or</li>
221 * <li>if arg <code>modules</code> is null</li>
223 * @throws IllegalStateException
224 * if <code>context</code> contain no modules
227 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
228 checkArgument(context != null, "Schema Context reference cannot be NULL.");
229 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
230 checkArgument(modules != null, "Set of Modules cannot be NULL.");
232 schemaContext = context;
233 typeProvider = new TypeProviderImpl(context);
234 Module[] modulesArray = new Module[context.getModules().size()];
235 context.getModules().toArray(modulesArray);
236 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
237 genTypeBuilders = new HashMap<>();
239 for (Module contextModule : contextModules) {
240 moduleToGenTypes(contextModule, context);
242 for (Module contextModule : contextModules) {
243 allAugmentsToGenTypes(contextModule);
246 final List<Type> filteredGenTypes = new ArrayList<>();
247 for (Module m : modules) {
248 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
249 filteredGenTypes.addAll(ctx.getGeneratedTypes());
250 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
251 if (additionalTypes != null) {
252 filteredGenTypes.addAll(additionalTypes);
256 return filteredGenTypes;
259 private void moduleToGenTypes(final Module m, final SchemaContext context) {
260 genCtx.put(m, new ModuleContext());
261 allTypeDefinitionsToGenTypes(m);
262 groupingsToGenTypes(m, m.getGroupings());
263 rpcMethodsToGenType(m);
264 allIdentitiesToGenTypes(m, context);
265 notificationsToGenType(m);
267 if (!m.getChildNodes().isEmpty()) {
268 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
269 genCtx.get(m).addModuleNode(moduleType);
270 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
271 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
276 * Converts all extended type definitions of module to the list of
277 * <code>Type</code> objects.
280 * module from which is obtained set of type definitions
281 * @throws IllegalArgumentException
283 * <li>if module is null</li>
284 * <li>if name of module is null</li>
286 * @throws IllegalStateException
287 * if set of type definitions from module is null
289 private void allTypeDefinitionsToGenTypes(final Module module) {
290 checkArgument(module != null, "Module reference cannot be NULL.");
291 checkArgument(module.getName() != null, "Module name cannot be NULL.");
292 final DataNodeIterator it = new DataNodeIterator(module);
293 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
294 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
296 for (TypeDefinition<?> typedef : typeDefinitions) {
297 if (typedef != null) {
298 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
301 genCtx.get(module).addTypedefType(typedef.getPath(), type);
307 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
308 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
309 if (node.isAugmenting() || node.isAddedByUses()) {
312 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
313 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf);
314 genType.addComment(node.getDescription());
315 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
316 genType.setModuleName(module.getName());
317 genType.setReference(node.getReference());
318 genType.setSchemaPath(node.getPath().getPathFromRoot());
319 if (node instanceof DataNodeContainer) {
320 genCtx.get(module).addChildNodeType(node, genType);
321 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
322 processUsesAugments((DataNodeContainer) node, module);
327 private void containerToGenType(final Module module, final String basePackageName,
328 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
329 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
330 if (genType != null) {
331 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType);
332 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
336 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
337 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
338 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
339 if (genType != null) {
340 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), Types.listTypeFor(genType));
342 final List<String> listKeys = listKeys(node);
343 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
344 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
345 if (genTOBuilder != null) {
346 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
347 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
348 genTOBuilder.addImplementsType(identifierMarker);
349 genType.addImplementsType(identifiableMarker);
352 for (DataSchemaNode schemaNode : node.getChildNodes()) {
353 if (!schemaNode.isAugmenting()) {
354 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
359 if (genTOBuilder != null) {
360 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
361 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
362 genTOBuilder.setSUID(prop);
365 typeBuildersToGenTypes(module, genType, genTOBuilder);
369 private void processUsesAugments(final DataNodeContainer node, final Module module) {
370 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
371 for (UsesNode usesNode : node.getUses()) {
372 for (AugmentationSchema augment : usesNode.getAugmentations()) {
373 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
374 processUsesAugments(augment, module);
380 * Converts all <b>augmentation</b> of the module to the list
381 * <code>Type</code> objects.
384 * module from which is obtained list of all augmentation objects
385 * to iterate over them
386 * @throws IllegalArgumentException
388 * <li>if the module is null</li>
389 * <li>if the name of module is null</li>
391 * @throws IllegalStateException
392 * if set of augmentations from module is null
394 private void allAugmentsToGenTypes(final Module module) {
395 checkArgument(module != null, "Module reference cannot be NULL.");
396 checkArgument(module.getName() != null, "Module name cannot be NULL.");
397 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
399 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
400 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
401 for (AugmentationSchema augment : augmentations) {
402 augmentationToGenTypes(basePackageName, augment, module);
407 * Returns list of <code>AugmentationSchema</code> objects. The objects are
408 * sorted according to the length of their target path from the shortest to
412 * module from which is obtained list of all augmentation objects
413 * @return list of sorted <code>AugmentationSchema</code> objects obtained
414 * from <code>module</code>
415 * @throws IllegalArgumentException
417 * @throws IllegalStateException
418 * if set of module augmentations is null
420 private List<AugmentationSchema> resolveAugmentations(final Module module) {
421 checkArgument(module != null, "Module reference cannot be NULL.");
422 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
424 final Set<AugmentationSchema> augmentations = module.getAugmentations();
425 List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
426 Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
428 return sortedAugmentations;
432 * Create GeneratedTypeBuilder object from module argument.
435 * Module object from which builder will be created
436 * @return <code>GeneratedTypeBuilder</code> which is internal
437 * representation of the module
438 * @throws IllegalArgumentException
441 private GeneratedTypeBuilder moduleToDataType(final Module module) {
442 checkArgument(module != null, "Module reference cannot be NULL.");
444 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
445 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
446 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
447 moduleDataTypeBuilder.addComment(module.getDescription());
448 moduleDataTypeBuilder.setDescription(createDescription(module));
449 moduleDataTypeBuilder.setReference(module.getReference());
450 return moduleDataTypeBuilder;
454 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
455 * to the list of <code>Type</code> objects. In addition are to containers
456 * and lists which belong to input or output also part of returning list.
459 * module from which is obtained set of all rpc objects to
461 * @throws IllegalArgumentException
463 * <li>if the module is null</li>
464 * <li>if the name of module is null</li>
466 * @throws IllegalStateException
467 * if set of rpcs from module is null
469 private void rpcMethodsToGenType(final Module module) {
470 checkArgument(module != null, "Module reference cannot be NULL.");
471 checkArgument(module.getName() != null, "Module name cannot be NULL.");
472 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
473 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
474 if (rpcDefinitions.isEmpty()) {
478 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
479 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
480 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
481 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
483 for (RpcDefinition rpc : rpcDefinitions) {
485 final String rpcName = BindingMapping.getClassName(rpc.getQName());
486 final String rpcMethodName = parseToValidParamName(rpcName);
487 final String rpcComment = rpc.getDescription();
488 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
489 final ContainerSchemaNode input = rpc.getInput();
490 final ContainerSchemaNode output = rpc.getOutput();
493 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
494 addImplementedInterfaceFromUses(input, inType);
495 inType.addImplementsType(DATA_OBJECT);
496 inType.addImplementsType(augmentable(inType));
497 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
498 genCtx.get(module).addChildNodeType(input, inType);
499 final GeneratedType inTypeInstance = inType.toInstance();
500 method.addParameter(inTypeInstance, "input");
503 Type outTypeInstance = VOID;
504 if (output != null) {
505 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
506 addImplementedInterfaceFromUses(output, outType);
507 outType.addImplementsType(DATA_OBJECT);
508 outType.addImplementsType(augmentable(outType));
509 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
510 genCtx.get(module).addChildNodeType(output, outType);
511 outTypeInstance = outType.toInstance();
514 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
515 method.setComment(rpcComment);
516 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
520 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
524 * Converts all <b>notifications</b> of the module to the list of
525 * <code>Type</code> objects. In addition are to this list added containers
526 * and lists which are part of this notification.
529 * module from which is obtained set of all notification objects
530 * to iterate over them
531 * @throws IllegalArgumentException
533 * <li>if the module equals null</li>
534 * <li>if the name of module equals null</li>
536 * @throws IllegalStateException
537 * if set of notifications from module is null
539 private void notificationsToGenType(final Module module) {
540 checkArgument(module != null, "Module reference cannot be NULL.");
541 checkArgument(module.getName() != null, "Module name cannot be NULL.");
542 final Set<NotificationDefinition> notifications = module.getNotifications();
543 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
544 if (notifications.isEmpty()) {
548 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
549 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
550 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
554 for (NotificationDefinition notification : notifications) {
555 if (notification != null) {
556 processUsesAugments(notification, module);
558 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
559 notification, BindingTypes.DATA_OBJECT);
560 notificationInterface.addImplementsType(NOTIFICATION);
561 genCtx.get(module).addChildNodeType(notification, notificationInterface);
563 // Notification object
564 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
565 notification.getChildNodes());
567 listenerInterface.addMethod("on" + notificationInterface.getName())
568 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
569 .setComment(notification.getDescription()).setReturnType(Types.VOID);
572 listenerInterface.setDescription(createDescription(notifications, module.getName(), module.getModuleSourcePath()));
574 genCtx.get(module).addTopLevelNodeType(listenerInterface);
578 * Converts all <b>identities</b> of the module to the list of
579 * <code>Type</code> objects.
582 * module from which is obtained set of all identity objects to
585 * schema context only used as input parameter for method
586 * {@link identityToGenType}
589 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
590 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
591 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
593 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
594 for (IdentitySchemaNode identity : schemaIdentities) {
595 identityToGenType(module, basePackageName, identity, context);
601 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
602 * created transport object builder. If identity contains base identity then
603 * reference to base identity is added to superior identity as its extend.
604 * If identity doesn't contain base identity then only reference to abstract
605 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
606 * BaseIdentity} is added
610 * @param basePackageName
611 * string contains the module package name
613 * IdentitySchemaNode which contains data about identity
615 * SchemaContext which is used to get package and name
616 * information about base of identity
619 private void identityToGenType(final Module module, final String basePackageName,
620 final IdentitySchemaNode identity, final SchemaContext context) {
621 if (identity == null) {
624 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
625 final String genTypeName = BindingMapping.getClassName(identity.getQName());
626 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
627 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
628 if (baseIdentity == null) {
629 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
630 BaseIdentity.class.getSimpleName());
631 newType.setExtendsType(gto.toInstance());
633 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
634 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
636 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
637 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
639 newType.setExtendsType(gto);
641 newType.setAbstract(true);
642 newType.addComment(identity.getDescription());
643 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
644 newType.setReference(identity.getReference());
645 newType.setModuleName(module.getName());
646 newType.setSchemaPath(identity.getPath().getPathFromRoot());
648 final QName qname = identity.getQName();
649 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
651 genCtx.get(module).addIdentityType(identity.getQName(), newType);
654 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
656 StringBuilder sb = new StringBuilder("org.opendaylight.yangtools.yang.common.QName");
657 sb.append(".create(");
659 sb.append(name.getNamespace());
661 sb.append(name.getFormattedRevision());
663 sb.append(name.getLocalName());
666 return toBuilder.addConstant(typeForClass(QName.class), constantName, sb.toString());
670 * Converts all <b>groupings</b> of the module to the list of
671 * <code>Type</code> objects. Firstly are groupings sorted according mutual
672 * dependencies. At least dependent (independent) groupings are in the list
673 * saved at first positions. For every grouping the record is added to map
674 * {@link BindingGeneratorImpl#allGroupings allGroupings}
679 * of groupings from which types will be generated
682 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
683 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
684 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
686 for (GroupingDefinition grouping : groupingsSortedByDependencies) {
687 groupingToGenType(basePackageName, grouping, module);
692 * Converts individual grouping to GeneratedType. Firstly generated type
693 * builder is created and every child node of grouping is resolved to the
696 * @param basePackageName
697 * string contains the module package name
699 * GroupingDefinition which contains data about grouping
702 * @return GeneratedType which is generated from grouping (object of type
703 * <code>GroupingDefinition</code>)
705 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
706 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
707 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping);
708 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
709 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
710 groupingsToGenTypes(module, grouping.getGroupings());
711 processUsesAugments(grouping, module);
715 * Adds enumeration builder created from <code>enumTypeDef</code> to
716 * <code>typeBuilder</code>.
718 * Each <code>enumTypeDef</code> item is added to builder with its name and
722 * EnumTypeDefinition contains enum data
724 * string contains name which will be assigned to enumeration
727 * GeneratedTypeBuilder to which will be enum builder assigned
728 * @return enumeration builder which contains data from
729 * <code>enumTypeDef</code>
731 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
732 final GeneratedTypeBuilder typeBuilder) {
733 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
734 && (enumTypeDef.getQName().getLocalName() != null)) {
735 final String enumerationName = BindingMapping.getClassName(enumName);
736 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
737 enumBuilder.setDescription(enumTypeDef.getDescription());
738 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
745 * Generates type builder for <code>module</code>.
748 * Module which is source of package name for generated type
751 * string which is added to the module class name representation
753 * @return instance of GeneratedTypeBuilder which represents
754 * <code>module</code>.
755 * @throws IllegalArgumentException
756 * if <code>module</code> is null
758 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
759 checkArgument(module != null, "Module reference cannot be NULL.");
760 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
761 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
763 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
764 moduleBuilder.setDescription(createDescription(module));
765 moduleBuilder.setReference(module.getReference());
766 moduleBuilder.setModuleName(moduleName);
768 return moduleBuilder;
772 * Converts <code>augSchema</code> to list of <code>Type</code> which
773 * contains generated type for augmentation. In addition there are also
774 * generated types for all containers, list and choices which are child of
775 * <code>augSchema</code> node or a generated types for cases are added if
776 * augmented node is choice.
778 * @param augmentPackageName
779 * string with the name of the package to which the augmentation
782 * AugmentationSchema which is contains data about augmentation
783 * (target path, childs...)
786 * @param parentUsesNode
787 * @throws IllegalArgumentException
789 * <li>if <code>augmentPackageName</code> equals null</li>
790 * <li>if <code>augSchema</code> equals null</li>
792 * @throws IllegalStateException
793 * if augment target path is null
795 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
796 final Module module) {
797 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
798 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
799 checkState(augSchema.getTargetPath() != null,
800 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
802 processUsesAugments(augSchema, module);
803 final SchemaPath targetPath = augSchema.getTargetPath();
804 SchemaNode targetSchemaNode = null;
806 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
807 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
808 if (targetSchemaNode instanceof DerivableSchemaNode) {
809 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
811 if (targetSchemaNode == null) {
812 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
813 + " in module " + module.getName());
816 if (targetSchemaNode == null) {
817 throw new IllegalArgumentException("augment target not found: " + targetPath);
820 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
821 if (targetTypeBuilder == null) {
822 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
824 if (targetTypeBuilder == null) {
825 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
828 if (!(targetSchemaNode instanceof ChoiceNode)) {
829 String packageName = augmentPackageName;
830 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
831 targetTypeBuilder.getName());
832 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
835 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
836 (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
840 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
841 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
842 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
843 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
844 checkState(augSchema.getTargetPath() != null,
845 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
847 processUsesAugments(augSchema, module);
848 final SchemaPath targetPath = augSchema.getTargetPath();
849 SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
850 if (targetSchemaNode == null) {
851 throw new IllegalArgumentException("augment target not found: " + targetPath);
854 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
855 if (targetTypeBuilder == null) {
856 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
858 if (targetTypeBuilder == null) {
859 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
862 if (!(targetSchemaNode instanceof ChoiceNode)) {
863 String packageName = augmentPackageName;
864 if (usesNodeParent instanceof SchemaNode) {
865 packageName = packageNameForGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath(),
868 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
871 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
872 (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
877 * Convenient method to find node added by uses statement.
881 * @param parentUsesNode
882 * parent of uses node
883 * @return node from its original location in grouping
885 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
886 SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
888 if (!(targetGrouping instanceof GroupingDefinition)) {
889 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
892 GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
893 SchemaNode result = grouping;
894 for (QName node : targetPath.getPathFromRoot()) {
895 // finding by local name is valid, grouping cannot contain nodes
896 // with same name and different namespace
897 if (result instanceof DataNodeContainer) {
898 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
899 } else if (result instanceof ChoiceNode) {
900 result = ((ChoiceNode) result).getCaseNodeByName(node.getLocalName());
903 if (result == null) {
907 boolean fromUses = ((DataSchemaNode) result).isAddedByUses();
908 Iterator<UsesNode> groupingUses = grouping.getUses().iterator();
909 while (groupingUses.hasNext() && fromUses) {
910 result = findOriginalTargetFromGrouping(targetPath, groupingUses.next());
911 if (result != null) {
912 fromUses = ((DataSchemaNode) result).isAddedByUses();
916 // this indicates invalid yang and thus possible bug in code because
917 // invalid yang should be already spotted by parser
918 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
921 return (DataSchemaNode) result;
925 * Returns a generated type builder for an augmentation.
927 * The name of the type builder is equal to the name of augmented node with
928 * serial number as suffix.
932 * @param augmentPackageName
933 * string with contains the package name to which the augment
935 * @param basePackageName
936 * string with the package name to which the augmented node
938 * @param targetTypeRef
941 * augmentation schema which contains data about the child nodes
942 * and uses of augment
943 * @return generated type builder for augment
945 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
946 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
947 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
948 if (augmentBuilders == null) {
949 augmentBuilders = new HashMap<>();
950 genTypeBuilders.put(augmentPackageName, augmentBuilders);
952 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
955 if (augIdentifier != null) {
956 augTypeName = BindingMapping.getClassName(augIdentifier);
958 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
961 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
963 augTypeBuilder.addImplementsType(DATA_OBJECT);
964 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
965 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
967 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
968 augmentBuilders.put(augTypeName, augTypeBuilder);
970 if(!augSchema.getChildNodes().isEmpty()) {
971 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
972 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
975 genCtx.get(module).addAugmentType(augTypeBuilder);
976 return augTypeBuilder;
981 * @param unknownSchemaNodes
982 * @return nodeParameter of UnknownSchemaNode
984 private String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
985 for (UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
986 final QName nodeType = unknownSchemaNode.getNodeType();
987 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
988 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
989 return unknownSchemaNode.getNodeParameter();
996 * Returns first unique name for the augment generated type builder. The
997 * generated type builder name for augment consists from name of augmented
998 * node and serial number of its augmentation.
1001 * map of builders which were created in the package to which the
1002 * augmentation belongs
1003 * @param genTypeName
1004 * string with name of augmented node
1005 * @return string with unique name for augmentation builder
1007 private String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1009 if (builders != null) {
1010 while (builders.containsKey(genTypeName + index)) {
1014 return genTypeName + index;
1018 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1019 * node for which <code>typeBuilder</code> was created.
1021 * The subnodes aren't mapped to the methods if they are part of grouping or
1022 * augment (in this case are already part of them).
1026 * @param basePackageName
1027 * string contains the module package name
1029 * generated type builder which represents any node. The subnodes
1030 * of this node are added to the <code>typeBuilder</code> as
1031 * methods. The subnode can be of type leaf, leaf-list, list,
1032 * container, choice.
1035 * @param schemaNodes
1036 * set of data schema nodes which are the children of the node
1037 * for which <code>typeBuilder</code> was created
1038 * @return generated type builder which is the same builder as input
1039 * parameter. The getter methods (representing child nodes) could be
1042 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1043 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1044 if (schemaNodes != null && parent != null) {
1045 for (DataSchemaNode schemaNode : schemaNodes) {
1046 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1047 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1055 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1056 * node for which <code>typeBuilder</code> was created.
1060 * @param basePackageName
1061 * string contains the module package name
1062 * @param typeBuilder
1063 * generated type builder which represents any node. The subnodes
1064 * of this node are added to the <code>typeBuilder</code> as
1065 * methods. The subnode can be of type leaf, leaf-list, list,
1066 * container, choice.
1069 * @param schemaNodes
1070 * set of data schema nodes which are the children of the node
1071 * for which <code>typeBuilder</code> was created
1072 * @return generated type builder which is the same object as the input
1073 * parameter <code>typeBuilder</code>. The getter method could be
1076 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1077 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1078 final Iterable<DataSchemaNode> schemaNodes) {
1079 if ((schemaNodes != null) && (typeBuilder != null)) {
1080 for (DataSchemaNode schemaNode : schemaNodes) {
1081 if (!schemaNode.isAugmenting()) {
1082 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1090 * Adds to <code>typeBuilder</code> a method which is derived from
1091 * <code>schemaNode</code>.
1093 * @param basePackageName
1094 * string with the module package name
1096 * data schema node which is added to <code>typeBuilder</code> as
1098 * @param typeBuilder
1099 * generated type builder to which is <code>schemaNode</code>
1100 * added as a method.
1106 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1107 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1108 if (node != null && typeBuilder != null) {
1109 if (node instanceof LeafSchemaNode) {
1110 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node);
1111 } else if (node instanceof LeafListSchemaNode) {
1112 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node);
1113 } else if (node instanceof ContainerSchemaNode) {
1114 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1115 } else if (node instanceof ListSchemaNode) {
1116 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1117 } else if (node instanceof ChoiceNode) {
1118 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceNode) node);
1120 // TODO: anyxml not yet supported
1121 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1122 typeBuilder.getFullyQualifiedName());
1128 * Converts <code>choiceNode</code> to the list of generated types for
1129 * choice and its cases.
1131 * The package names for choice and for its cases are created as
1132 * concatenation of the module package (<code>basePackageName</code>) and
1133 * names of all parents node.
1137 * @param basePackageName
1138 * string with the module package name
1142 * choice node which is mapped to generated type. Also child
1143 * nodes - cases are mapped to generated types.
1144 * @throws IllegalArgumentException
1146 * <li>if <code>basePackageName</code> is null</li>
1147 * <li>if <code>choiceNode</code> is null</li>
1150 private void choiceToGeneratedType(final Module module, final String basePackageName,
1151 final GeneratedTypeBuilder parent, final ChoiceNode choiceNode) {
1152 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1153 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1155 if (!choiceNode.isAddedByUses()) {
1156 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1157 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1158 constructGetter(parent, choiceNode.getQName().getLocalName(), choiceNode.getDescription(),
1160 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1161 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1162 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1167 * Converts <code>caseNodes</code> set to list of corresponding generated
1170 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1171 * created generated type builder. The package names for the builder is
1172 * created as concatenation of the module package (
1173 * <code>basePackageName</code>) and names of all parents nodes of the
1174 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1175 * between every case builder and <i>choice</i> type
1179 * @param basePackageName
1180 * string with the module package name
1181 * @param refChoiceType
1182 * type which represents superior <i>case</i>
1184 * choice case node which is mapped to generated type
1185 * @return list of generated types for <code>caseNodes</code>.
1186 * @throws IllegalArgumentException
1188 * <li>if <code>basePackageName</code> equals null</li>
1189 * <li>if <code>refChoiceType</code> equals null</li>
1190 * <li>if <code>caseNodes</code> equals null</li>
1193 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1194 final Type refChoiceType, final ChoiceNode choiceNode) {
1195 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1196 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1197 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1199 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1200 if (caseNodes == null) {
1204 for (ChoiceCaseNode caseNode : caseNodes) {
1205 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1206 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1207 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode);
1208 caseTypeBuilder.addImplementsType(refChoiceType);
1209 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1210 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1211 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1212 if (caseChildNodes != null) {
1213 Object parentNode = null;
1214 final SchemaPath nodeSp = choiceNode.getPath();
1215 parentNode = findDataSchemaNode(schemaContext, nodeSp.getParent());
1218 if (parentNode instanceof AugmentationSchema) {
1219 final AugmentationSchema augSchema = (AugmentationSchema) parentNode;
1220 final SchemaPath targetPath = augSchema.getTargetPath();
1221 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1222 if (targetSchemaNode instanceof DataSchemaNode
1223 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1224 if (targetSchemaNode instanceof DerivableSchemaNode) {
1225 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1227 if (targetSchemaNode == null) {
1228 throw new IllegalStateException(
1229 "Failed to find target node from grouping for augmentation " + augSchema
1230 + " in module " + module.getName());
1233 parent = targetSchemaNode;
1235 final SchemaPath sp = choiceNode.getPath();
1236 parent = findDataSchemaNode(schemaContext, sp.getParent());
1238 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1239 if (childOfType == null) {
1240 childOfType = findGroupingByPath(parent.getPath());
1242 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1246 processUsesAugments(caseNode, module);
1251 * Generates list of generated types for all the cases of a choice which are
1252 * added to the choice through the augment.
1256 * @param basePackageName
1257 * string contains name of package to which augment belongs. If
1258 * an augmented choice is from an other package (pcg1) than an
1259 * augmenting choice (pcg2) then case's of the augmenting choice
1260 * will belong to pcg2.
1262 * Type which represents target choice
1264 * node which represents target choice
1265 * @param augmentedNodes
1266 * set of choice case nodes for which is checked if are/aren't
1267 * added to choice through augmentation
1268 * @return list of generated types which represents augmented cases of
1269 * choice <code>refChoiceType</code>
1270 * @throws IllegalArgumentException
1272 * <li>if <code>basePackageName</code> is null</li>
1273 * <li>if <code>targetType</code> is null</li>
1274 * <li>if <code>augmentedNodes</code> is null</li>
1277 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1278 final Type targetType, final ChoiceNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
1279 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1280 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1281 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1283 for (DataSchemaNode caseNode : augmentedNodes) {
1284 if (caseNode != null) {
1285 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1286 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode);
1287 caseTypeBuilder.addImplementsType(targetType);
1289 SchemaNode parent = null;
1290 final SchemaPath nodeSp = targetNode.getPath();
1291 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1293 GeneratedTypeBuilder childOfType = null;
1294 if (parent instanceof Module) {
1295 childOfType = genCtx.get(parent).getModuleNode();
1296 } else if (parent instanceof ChoiceCaseNode) {
1297 childOfType = findCaseByPath(parent.getPath());
1298 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1299 childOfType = findChildNodeByPath(parent.getPath());
1300 } else if (parent instanceof GroupingDefinition) {
1301 childOfType = findGroupingByPath(parent.getPath());
1304 if (childOfType == null) {
1305 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1308 ChoiceCaseNode node = null;
1309 if (caseNode instanceof ChoiceCaseNode) {
1310 node = (ChoiceCaseNode) caseNode;
1312 node = targetNode.getCaseNodeByName(caseNode.getQName().getLocalName());
1314 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1315 if (childNodes != null) {
1316 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1318 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1319 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1325 * Converts <code>leaf</code> to the getter method which is added to
1326 * <code>typeBuilder</code>.
1328 * @param typeBuilder
1329 * generated type builder to which is added getter method as
1330 * <code>leaf</code> mapping
1332 * leaf schema node which is mapped as getter method which is
1333 * added to <code>typeBuilder</code>
1334 * @return boolean value
1336 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1338 * <li>true - in other cases</li>
1341 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf) {
1342 Type returnType = null;
1343 if ((leaf != null) && (typeBuilder != null)) {
1344 final String leafName = leaf.getQName().getLocalName();
1345 String leafDesc = leaf.getDescription();
1346 if (leafDesc == null) {
1350 final Module parentModule = findParentModule(schemaContext, leaf);
1351 if (leafName != null && !leaf.isAddedByUses()) {
1352 final TypeDefinition<?> typeDef = leaf.getType();
1354 GeneratedTOBuilder genTOBuilder;
1355 if (typeDef instanceof EnumTypeDefinition) {
1356 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1357 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1358 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1361 if (enumBuilder != null) {
1362 returnType = enumBuilder.toInstance(typeBuilder);
1364 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1365 } else if (typeDef instanceof UnionType) {
1366 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1367 if (genTOBuilder != null) {
1368 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1370 } else if (typeDef instanceof BitsTypeDefinition) {
1371 genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1372 if (genTOBuilder != null) {
1373 returnType = genTOBuilder.toInstance();
1376 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1377 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1379 if (returnType != null) {
1380 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1381 processContextRefExtension(leaf, getter, parentModule);
1388 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1389 final Module module) {
1390 for (UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1391 final QName nodeType = node.getNodeType();
1392 if ("context-reference".equals(nodeType.getLocalName())) {
1393 final String nodeParam = node.getNodeParameter();
1394 IdentitySchemaNode identity = null;
1395 String basePackageName = null;
1396 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1397 final Iterator<String> iterator = splittedElement.iterator();
1398 final int length = Iterables.size(splittedElement);
1400 identity = findIdentityByName(module.getIdentities(), iterator.next());
1401 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1402 } else if (length == 2) {
1403 String prefix = iterator.next();
1404 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1405 if (dependentModule == null) {
1406 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1409 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1410 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1412 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1415 if (identity == null) {
1416 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1420 final Class<RoutingContext> clazz = RoutingContext.class;
1421 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1422 clazz.getSimpleName());
1423 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1424 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1425 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1430 private IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1431 for (IdentitySchemaNode id : identities) {
1432 if (id.getQName().getLocalName().equals(name)) {
1439 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1440 for (ModuleImport imp : imports) {
1441 if (imp.getPrefix().equals(prefix)) {
1442 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1448 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1449 final boolean isReadOnly, final Module module) {
1450 if ((leaf != null) && (toBuilder != null)) {
1451 final String leafName = leaf.getQName().getLocalName();
1452 String leafDesc = leaf.getDescription();
1453 if (leafDesc == null) {
1457 if (leafName != null) {
1458 Type returnType = null;
1459 final TypeDefinition<?> typeDef = leaf.getType();
1460 if (typeDef instanceof UnionTypeDefinition) {
1461 // GeneratedType for this type definition should be already
1463 QName qname = typeDef.getQName();
1464 Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1465 qname.getRevision());
1466 final ModuleContext mc = genCtx.get(unionModule);
1467 returnType = mc.getTypedefs().get(typeDef.getPath());
1469 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1471 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1478 * Converts <code>leaf</code> schema node to property of generated TO
1482 * generated TO builder to which is <code>leaf</code> added as
1485 * leaf schema node which is added to <code>toBuilder</code> as
1490 * boolean value which says if leaf property is|isn't read only
1491 * @return boolean value
1493 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1494 * name equals null or if leaf is added by <i>uses</i>.</li>
1495 * <li>true - other cases</li>
1498 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1499 final Type returnType, final boolean isReadOnly) {
1500 if (returnType == null) {
1503 final String leafName = leaf.getQName().getLocalName();
1504 final String leafDesc = leaf.getDescription();
1505 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(parseToValidParamName(leafName));
1506 propBuilder.setReadOnly(isReadOnly);
1507 propBuilder.setReturnType(returnType);
1508 propBuilder.setComment(leafDesc);
1509 toBuilder.addEqualsIdentity(propBuilder);
1510 toBuilder.addHashIdentity(propBuilder);
1511 toBuilder.addToStringProperty(propBuilder);
1516 * Converts <code>node</code> leaf list schema node to getter method of
1517 * <code>typeBuilder</code>.
1519 * @param typeBuilder
1520 * generated type builder to which is <code>node</code> added as
1523 * leaf list schema node which is added to
1524 * <code>typeBuilder</code> as getter method
1525 * @return boolean value
1527 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1528 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1529 * <li>false - other cases</li>
1532 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node) {
1533 if ((node != null) && (typeBuilder != null)) {
1534 final QName nodeName = node.getQName();
1536 if (nodeName != null && !node.isAddedByUses()) {
1537 final TypeDefinition<?> typeDef = node.getType();
1538 final Module parentModule = findParentModule(schemaContext, node);
1540 Type returnType = null;
1541 if (typeDef instanceof EnumTypeDefinition) {
1542 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1543 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1544 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1546 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1547 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1548 } else if (typeDef instanceof UnionType) {
1549 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1550 if (genTOBuilder != null) {
1551 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1553 } else if (typeDef instanceof BitsTypeDefinition) {
1554 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1555 returnType = genTOBuilder.toInstance();
1557 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1558 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1561 final ParameterizedType listType = Types.listTypeFor(returnType);
1562 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1569 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1570 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1571 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1572 genTOBuilder.getName());
1574 returnType.setDescription(typeDef.getDescription());
1575 returnType.setReference(typeDef.getReference());
1576 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1577 returnType.setModuleName(parentModule.getName());
1579 genTOBuilder.setTypedef(true);
1580 genTOBuilder.setIsUnion(true);
1581 ((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1584 final GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),
1585 genTOBuilder.getName() + "Builder");
1586 unionBuilder.setIsUnionBuilder(true);
1587 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1588 method.setReturnType(returnType);
1589 method.addParameter(Types.STRING, "defaultValue");
1590 method.setAccessModifier(AccessModifier.PUBLIC);
1591 method.setStatic(true);
1593 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1594 if (types == null) {
1595 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1596 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1598 types.add(unionBuilder.toInstance());
1600 return returnType.toInstance();
1603 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1604 return addDefaultInterfaceDefinition(packageName, schemaNode, null);
1608 * Instantiates generated type builder with <code>packageName</code> and
1609 * <code>schemaNode</code>.
1611 * The new builder always implements
1612 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br />
1613 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1614 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1615 * Augmentable}.<br />
1616 * If <code>schemaNode</code> is instance of
1617 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1618 * DataNodeContainer} it can also implement nodes which are specified in
1621 * @param packageName
1622 * string with the name of the package to which
1623 * <code>schemaNode</code> belongs.
1625 * schema node for which is created generated type builder
1627 * parent type (can be null)
1628 * @return generated type builder <code>schemaNode</code>
1630 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1631 final Type parent) {
1632 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1633 if (parent == null) {
1634 it.addImplementsType(DATA_OBJECT);
1636 it.addImplementsType(BindingTypes.childOf(parent));
1638 if (!(schemaNode instanceof GroupingDefinition)) {
1639 it.addImplementsType(augmentable(it));
1642 if (schemaNode instanceof DataNodeContainer) {
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 resultTOBuilder = types.remove(0);
1923 for (GeneratedTOBuilder genTOBuilder : types) {
1924 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1928 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1929 genPropBuilder.setReturnType(Types.primitiveType("char[]", null));
1930 resultTOBuilder.addEqualsIdentity(genPropBuilder);
1931 resultTOBuilder.addHashIdentity(genPropBuilder);
1932 resultTOBuilder.addToStringProperty(genPropBuilder);
1934 } else if (typeDef instanceof BitsTypeDefinition) {
1935 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
1936 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
1938 if (genTOBuilders != null && !genTOBuilders.isEmpty()) {
1939 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1940 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1942 return genTOBuilders.get(0);
1949 * Adds the implemented types to type builder.
1951 * The method passes through the list of <i>uses</i> in
1952 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1953 * generated type from {@link BindingGeneratorImpl#allGroupings
1954 * allGroupings} which is added as <i>implements type</i> to
1955 * <code>builder</code>
1957 * @param dataNodeContainer
1958 * element which contains the list of used YANG groupings
1960 * builder to which are added implemented types according to
1961 * <code>dataNodeContainer</code>
1962 * @return generated type builder with all implemented types
1964 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1965 final GeneratedTypeBuilder builder) {
1966 for (UsesNode usesNode : dataNodeContainer.getUses()) {
1967 if (usesNode.getGroupingPath() != null) {
1968 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
1969 if (genType == null) {
1970 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1971 + builder.getName());
1974 builder.addImplementsType(genType);
1976 builder.addComment(genType.getDescription());
1977 builder.setDescription(genType.getDescription());
1978 builder.setModuleName(genType.getModuleName());
1979 builder.setReference(genType.getReference());
1980 builder.setSchemaPath(genType.getSchemaPath());
1987 private boolean isNullOrEmpty(final Collection<?> list) {
1988 return (list == null || list.isEmpty() ? true : false);
1991 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
1992 final StringBuilder sb = new StringBuilder();
1994 if (!isNullOrEmpty(schemaNodes)) {
1995 final SchemaNode node = schemaNodes.iterator().next();
1997 if (node instanceof RpcDefinition) {
1998 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
1999 } else if (node instanceof NotificationDefinition) {
2000 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2003 sb.append(NEW_LINE);
2004 sb.append("<br />(Source path: <i>");
2005 sb.append(moduleSourcePath);
2006 sb.append("</i>):");
2007 sb.append(NEW_LINE);
2009 if (verboseClassComments) {
2011 sb.append(NEW_LINE);
2012 sb.append(YangTemplate.generateYangSnipet(schemaNodes));
2013 sb.append("</pre>");
2014 sb.append(NEW_LINE);
2017 return sb.toString();
2020 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2021 final StringBuilder sb = new StringBuilder();
2022 final String formattedDescription = YangTemplate.formatToParagraph(schemaNode.getDescription(), 0);
2024 if (!isNullOrEmpty(formattedDescription)) {
2025 sb.append(formattedDescription);
2026 sb.append(NEW_LINE);
2029 if (verboseClassComments) {
2030 final Module module = findParentModule(schemaContext, schemaNode);
2031 final StringBuilder linkToBuilderClass = new StringBuilder();
2032 final StringBuilder linkToKeyClass = new StringBuilder();
2033 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2034 String className = namespace[namespace.length - 1];
2036 if (hasBuilderClass(schemaNode)) {
2037 linkToBuilderClass.append(className);
2038 linkToBuilderClass.append("Builder");
2040 if (schemaNode instanceof ListSchemaNode) {
2041 linkToKeyClass.append(className);
2042 linkToKeyClass.append("Key");
2047 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2048 sb.append(module.getName());
2050 sb.append(NEW_LINE);
2051 sb.append("<br />(Source path: <i>");
2052 sb.append(module.getModuleSourcePath());
2053 sb.append("</i>):");
2054 sb.append(NEW_LINE);
2056 sb.append(NEW_LINE);
2057 sb.append(YangTemplate.generateYangSnipet(schemaNode));
2058 sb.append("</pre>");
2059 sb.append(NEW_LINE);
2060 sb.append("The schema path to identify an instance is");
2061 sb.append(NEW_LINE);
2063 sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2065 sb.append(NEW_LINE);
2067 if (hasBuilderClass(schemaNode)) {
2068 sb.append(NEW_LINE);
2069 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2070 sb.append(NEW_LINE);
2072 sb.append(linkToBuilderClass);
2073 if (schemaNode instanceof ListSchemaNode) {
2075 sb.append(linkToKeyClass);
2077 sb.append(NEW_LINE);
2081 return sb.toString();
2084 private boolean hasBuilderClass(final SchemaNode schemaNode) {
2085 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2086 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2092 private boolean isNullOrEmpty(final String string) {
2093 return (string == null || string.isEmpty() ? true : false);
2096 private String createDescription(final Module module) {
2097 final StringBuilder sb = new StringBuilder();
2098 final String formattedDescription = YangTemplate.formatToParagraph(module.getDescription(), 0);
2100 if (!isNullOrEmpty(formattedDescription)) {
2101 sb.append(formattedDescription);
2102 sb.append(NEW_LINE);
2105 if (verboseClassComments) {
2107 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2108 sb.append(module.getName());
2110 sb.append(NEW_LINE);
2111 sb.append("<br />Source path: <i>");
2112 sb.append(module.getModuleSourcePath());
2113 sb.append("</i>):");
2114 sb.append(NEW_LINE);
2116 sb.append(NEW_LINE);
2117 sb.append(YangTemplate.generateYangSnipet(module));
2118 sb.append("</pre>");
2121 return sb.toString();
2124 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2125 for (ModuleContext ctx : genCtx.values()) {
2126 GeneratedTypeBuilder result = ctx.getChildNode(path);
2127 if (result != null) {
2134 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2135 for (ModuleContext ctx : genCtx.values()) {
2136 GeneratedTypeBuilder result = ctx.getGrouping(path);
2137 if (result != null) {
2144 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2145 for (ModuleContext ctx : genCtx.values()) {
2146 GeneratedTypeBuilder result = ctx.getCase(path);
2147 if (result != null) {
2154 public Map<Module, ModuleContext> getModuleContexts() {