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.encodeAngleBrackets;
15 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_OBJECT;
18 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_ROOT;
19 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIABLE;
20 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIER;
21 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.NOTIFICATION;
22 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.augmentable;
23 import static org.opendaylight.yangtools.binding.generator.util.Types.BOOLEAN;
24 import static org.opendaylight.yangtools.binding.generator.util.Types.FUTURE;
25 import static org.opendaylight.yangtools.binding.generator.util.Types.VOID;
26 import static org.opendaylight.yangtools.binding.generator.util.Types.typeForClass;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
29 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
30 import com.google.common.annotations.VisibleForTesting;
31 import com.google.common.base.Optional;
32 import com.google.common.base.Preconditions;
33 import com.google.common.base.Splitter;
34 import com.google.common.base.Strings;
35 import com.google.common.collect.Iterables;
36 import com.google.common.collect.Sets;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.Comparator;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
46 import java.util.regex.Pattern;
47 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
48 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
49 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
50 import org.opendaylight.yangtools.binding.generator.util.Types;
51 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
52 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
53 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
54 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
55 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
56 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
57 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
58 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
59 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
60 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
61 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
62 import org.opendaylight.yangtools.sal.binding.model.api.Type;
63 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
66 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
67 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
68 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
69 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
70 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
71 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
72 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
73 import org.opendaylight.yangtools.yang.binding.BindingMapping;
74 import org.opendaylight.yangtools.yang.binding.DataContainer;
75 import org.opendaylight.yangtools.yang.binding.RpcService;
76 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
77 import org.opendaylight.yangtools.yang.common.QName;
78 import org.opendaylight.yangtools.yang.common.RpcResult;
79 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
80 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
81 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
84 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
87 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.Module;
92 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
93 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
94 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
95 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
96 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
98 import org.opendaylight.yangtools.yang.model.api.Status;
99 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
100 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.UsesNode;
102 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
105 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
106 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
107 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
108 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
109 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
110 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
111 import org.slf4j.Logger;
112 import org.slf4j.LoggerFactory;
114 public class BindingGeneratorImpl implements BindingGenerator {
115 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
116 private static final Splitter COLON_SPLITTER = Splitter.on(':');
117 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
118 private static final char NEW_LINE = '\n';
121 * Comparator based on augment target path.
123 private static final Comparator<AugmentationSchema> AUGMENT_COMP = (o1, o2) -> {
124 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
125 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
127 while (thisIt.hasNext()) {
128 if (!otherIt.hasNext()) {
132 final int comp = thisIt.next().compareTo(otherIt.next());
138 return otherIt.hasNext() ? -1 : 0;
142 * Constant with the concrete name of identifier.
144 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
147 * Constant with the concrete name of namespace.
149 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
151 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
153 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
156 * When set to true, generated classes will include javadoc comments which
157 * are useful for users.
159 private final boolean verboseClassComments;
162 * Outer key represents the package name. Outer value represents map of all
163 * builders in the same package. Inner key represents the schema node name
164 * (in JAVA class/interface name format). Inner value represents instance of
165 * builder for schema node specified in key part.
167 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
170 * Provide methods for converting YANG types to JAVA types.
172 private TypeProvider typeProvider;
175 * Holds reference to schema context to resolve data of augmented element
176 * when creating augmentation builder
178 private SchemaContext schemaContext;
181 * Create a new binding generator.
183 * @param verboseClassComments generate verbose comments
185 public BindingGeneratorImpl(final boolean verboseClassComments) {
186 this.verboseClassComments = verboseClassComments;
190 * Resolves generated types from <code>context</code> schema nodes of all
193 * Generated types are created for modules, groupings, types, containers,
194 * lists, choices, augments, rpcs, notification, identities.
197 * schema context which contains data about all schema nodes
199 * @return list of types (usually <code>GeneratedType</code>
200 * <code>GeneratedTransferObject</code>which are generated from
201 * <code>context</code> data.
202 * @throws IllegalArgumentException
203 * if arg <code>context</code> is null
204 * @throws IllegalStateException
205 * if <code>context</code> contain no modules
208 public List<Type> generateTypes(final SchemaContext context) {
209 checkArgument(context != null, "Schema Context reference cannot be NULL.");
210 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
211 schemaContext = context;
212 typeProvider = new TypeProviderImpl(context);
213 final Set<Module> modules = context.getModules();
214 return generateTypes(context, modules);
218 * Resolves generated types from <code>context</code> schema nodes only for
219 * modules specified in <code>modules</code>
221 * Generated types are created for modules, groupings, types, containers,
222 * lists, choices, augments, rpcs, notification, identities.
225 * schema context which contains data about all schema nodes
228 * set of modules for which schema nodes should be generated
230 * @return list of types (usually <code>GeneratedType</code> or
231 * <code>GeneratedTransferObject</code>) which:
233 * <li>are generated from <code>context</code> schema nodes and</li>
234 * <li>are also part of some of the module in <code>modules</code>
237 * @throws IllegalArgumentException
239 * <li>if arg <code>context</code> is null or</li>
240 * <li>if arg <code>modules</code> is null</li>
242 * @throws IllegalStateException
243 * if <code>context</code> contain no modules
246 public List<Type> generateTypes(final SchemaContext context, final Set<Module> modules) {
247 checkArgument(context != null, "Schema Context reference cannot be NULL.");
248 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
249 checkArgument(modules != null, "Set of Modules cannot be NULL.");
251 schemaContext = context;
252 typeProvider = new TypeProviderImpl(context);
253 final Module[] modulesArray = new Module[context.getModules().size()];
254 context.getModules().toArray(modulesArray);
255 final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
256 genTypeBuilders = new HashMap<>();
258 for (final Module contextModule : contextModules) {
259 moduleToGenTypes(contextModule, context);
261 for (final Module contextModule : contextModules) {
262 allAugmentsToGenTypes(contextModule);
265 final List<Type> filteredGenTypes = new ArrayList<>();
266 for (final Module m : modules) {
267 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
268 filteredGenTypes.addAll(ctx.getGeneratedTypes());
269 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
270 if (additionalTypes != null) {
271 filteredGenTypes.addAll(additionalTypes);
275 return filteredGenTypes;
278 private void moduleToGenTypes(final Module m, final SchemaContext context) {
279 genCtx.put(m, new ModuleContext());
280 allTypeDefinitionsToGenTypes(m);
281 groupingsToGenTypes(m, m.getGroupings());
282 rpcMethodsToGenType(m);
283 allIdentitiesToGenTypes(m, context);
284 notificationsToGenType(m);
286 if (!m.getChildNodes().isEmpty()) {
287 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
288 genCtx.get(m).addModuleNode(moduleType);
289 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
290 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
295 * Converts all extended type definitions of module to the list of
296 * <code>Type</code> objects.
299 * module from which is obtained set of type definitions
300 * @throws IllegalArgumentException
302 * <li>if module is null</li>
303 * <li>if name of module is null</li>
305 * @throws IllegalStateException
306 * if set of type definitions from module is null
308 private void allTypeDefinitionsToGenTypes(final Module module) {
309 checkArgument(module != null, "Module reference cannot be NULL.");
310 checkArgument(module.getName() != null, "Module name cannot be NULL.");
311 final DataNodeIterator it = new DataNodeIterator(module);
312 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
313 checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
315 for (final TypeDefinition<?> typedef : typeDefinitions) {
316 if (typedef != null) {
317 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
320 final ModuleContext ctx = genCtx.get(module);
321 ctx.addTypedefType(typedef.getPath(), type);
322 ctx.addTypeToSchema(type,typedef);
328 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
329 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
330 if (node.isAugmenting() || node.isAddedByUses()) {
333 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
334 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
335 genType.addComment(node.getDescription());
336 annotateDeprecatedIfNecessary(node.getStatus(), genType);
337 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
338 genType.setModuleName(module.getName());
339 genType.setReference(node.getReference());
340 genType.setSchemaPath(node.getPath().getPathFromRoot());
341 if (node instanceof DataNodeContainer) {
342 genCtx.get(module).addChildNodeType(node, genType);
343 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
344 processUsesAugments((DataNodeContainer) node, module);
349 private void containerToGenType(final Module module, final String basePackageName,
350 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
351 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
352 if (genType != null) {
353 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType, node.getStatus());
354 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
358 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
359 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
360 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
361 if (genType != null) {
362 constructGetter(parent, node.getQName().getLocalName(), node.getDescription(),
363 Types.listTypeFor(genType), node.getStatus());
365 final List<String> listKeys = listKeys(node);
366 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
367 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
368 if (genTOBuilder != null) {
369 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
370 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
371 genTOBuilder.addImplementsType(identifierMarker);
372 genType.addImplementsType(identifiableMarker);
375 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
376 if (!schemaNode.isAugmenting()) {
377 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
382 if (genTOBuilder != null) {
383 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
384 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
385 genTOBuilder.setSUID(prop);
388 typeBuildersToGenTypes(module, genType, genTOBuilder);
392 private void processUsesAugments(final DataNodeContainer node, final Module module) {
393 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
394 for (final UsesNode usesNode : node.getUses()) {
395 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
396 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
397 processUsesAugments(augment, module);
403 * Converts all <b>augmentation</b> of the module to the list
404 * <code>Type</code> objects.
407 * module from which is obtained list of all augmentation objects
408 * to iterate over them
409 * @throws IllegalArgumentException
411 * <li>if the module is null</li>
412 * <li>if the name of module is null</li>
414 * @throws IllegalStateException
415 * if set of augmentations from module is null
417 private void allAugmentsToGenTypes(final Module module) {
418 checkArgument(module != null, "Module reference cannot be NULL.");
419 checkArgument(module.getName() != null, "Module name cannot be NULL.");
420 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
422 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
423 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
424 for (final AugmentationSchema augment : augmentations) {
425 augmentationToGenTypes(basePackageName, augment, module);
430 * Returns list of <code>AugmentationSchema</code> objects. The objects are
431 * sorted according to the length of their target path from the shortest to
435 * module from which is obtained list of all augmentation objects
436 * @return list of sorted <code>AugmentationSchema</code> objects obtained
437 * from <code>module</code>
438 * @throws IllegalArgumentException
440 * @throws IllegalStateException
441 * if set of module augmentations is null
443 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
444 checkArgument(module != null, "Module reference cannot be NULL.");
445 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
447 final Set<AugmentationSchema> augmentations = module.getAugmentations();
448 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
449 Collections.sort(sortedAugmentations, AUGMENT_COMP);
451 return sortedAugmentations;
455 * Create GeneratedTypeBuilder object from module argument.
458 * Module object from which builder will be created
459 * @return <code>GeneratedTypeBuilder</code> which is internal
460 * representation of the module
461 * @throws IllegalArgumentException
464 private GeneratedTypeBuilder moduleToDataType(final Module module) {
465 checkArgument(module != null, "Module reference cannot be NULL.");
467 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
468 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
469 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
470 moduleDataTypeBuilder.addComment(module.getDescription());
471 moduleDataTypeBuilder.setDescription(createDescription(module));
472 moduleDataTypeBuilder.setReference(module.getReference());
473 return moduleDataTypeBuilder;
477 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
478 * to the list of <code>Type</code> objects. In addition are to containers
479 * and lists which belong to input or output also part of returning list.
482 * module from which is obtained set of all rpc objects to
484 * @throws IllegalArgumentException
486 * <li>if the module is null</li>
487 * <li>if the name of module is null</li>
489 * @throws IllegalStateException
490 * if set of rpcs from module is null
492 private void rpcMethodsToGenType(final Module module) {
493 checkArgument(module != null, "Module reference cannot be NULL.");
494 checkArgument(module.getName() != null, "Module name cannot be NULL.");
495 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
496 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
497 if (rpcDefinitions.isEmpty()) {
501 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
502 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
503 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
504 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName()));
506 for (final RpcDefinition rpc : rpcDefinitions) {
508 final String rpcName = BindingMapping.getClassName(rpc.getQName());
509 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
510 final String rpcComment = encodeAngleBrackets(rpc.getDescription());
511 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
512 final ContainerSchemaNode input = rpc.getInput();
513 final ContainerSchemaNode output = rpc.getOutput();
516 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
517 addImplementedInterfaceFromUses(input, inType);
518 inType.addImplementsType(DATA_OBJECT);
519 inType.addImplementsType(augmentable(inType));
520 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
521 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
522 genCtx.get(module).addChildNodeType(input, inType);
523 final GeneratedType inTypeInstance = inType.toInstance();
524 method.addParameter(inTypeInstance, "input");
527 Type outTypeInstance = VOID;
528 if (output != null) {
529 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
530 addImplementedInterfaceFromUses(output, outType);
531 outType.addImplementsType(DATA_OBJECT);
532 outType.addImplementsType(augmentable(outType));
533 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
534 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
535 genCtx.get(module).addChildNodeType(output, outType);
536 outTypeInstance = outType.toInstance();
539 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
540 method.setComment(rpcComment);
541 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
545 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
549 * Converts all <b>notifications</b> of the module to the list of
550 * <code>Type</code> objects. In addition are to this list added containers
551 * and lists which are part of this notification.
554 * module from which is obtained set of all notification objects
555 * to iterate over them
556 * @throws IllegalArgumentException
558 * <li>if the module equals null</li>
559 * <li>if the name of module equals null</li>
561 * @throws IllegalStateException
562 * if set of notifications from module is null
564 private void notificationsToGenType(final Module module) {
565 checkArgument(module != null, "Module reference cannot be NULL.");
566 checkArgument(module.getName() != null, "Module name cannot be NULL.");
567 final Set<NotificationDefinition> notifications = module.getNotifications();
568 checkState(notifications != null, "Set of notification from module " + module.getName() + " cannot be NULL.");
569 if (notifications.isEmpty()) {
573 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
574 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
575 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
579 for (final NotificationDefinition notification : notifications) {
580 if (notification != null) {
581 processUsesAugments(notification, module);
583 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
584 notification, null, module);
585 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
586 notificationInterface.addImplementsType(NOTIFICATION);
587 genCtx.get(module).addChildNodeType(notification, notificationInterface);
589 // Notification object
590 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
591 notification.getChildNodes());
593 listenerInterface.addMethod("on" + notificationInterface.getName())
594 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
595 .setComment(encodeAngleBrackets(notification.getDescription())).setReturnType(Types.VOID);
598 listenerInterface.setDescription(createDescription(notifications, module.getName()));
600 genCtx.get(module).addTopLevelNodeType(listenerInterface);
604 * Converts all <b>identities</b> of the module to the list of
605 * <code>Type</code> objects.
608 * module from which is obtained set of all identity objects to
611 * schema context only used as input parameter for method
612 * {@link identityToGenType}
615 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
616 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
617 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
619 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
620 for (final IdentitySchemaNode identity : schemaIdentities) {
621 identityToGenType(module, basePackageName, identity, context);
627 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
628 * created transport object builder. If identity contains base identity then
629 * reference to base identity is added to superior identity as its extend.
630 * If identity doesn't contain base identity then only reference to abstract
631 * class {@link org.opendaylight.yangtools.yang.model.api.BaseIdentity
632 * BaseIdentity} is added
636 * @param basePackageName
637 * string contains the module package name
639 * IdentitySchemaNode which contains data about identity
641 * SchemaContext which is used to get package and name
642 * information about base of identity
645 private void identityToGenType(final Module module, final String basePackageName,
646 final IdentitySchemaNode identity, final SchemaContext context) {
647 if (identity == null) {
650 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
651 final String genTypeName = BindingMapping.getClassName(identity.getQName());
652 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
653 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
654 if (baseIdentity == null) {
655 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
656 BaseIdentity.class.getSimpleName());
657 newType.setExtendsType(gto.toInstance());
659 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
660 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
662 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
663 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
665 newType.setExtendsType(gto);
667 newType.setAbstract(true);
668 newType.addComment(identity.getDescription());
669 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
670 newType.setReference(identity.getReference());
671 newType.setModuleName(module.getName());
672 newType.setSchemaPath(identity.getPath().getPathFromRoot());
674 final QName qname = identity.getQName();
675 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
677 genCtx.get(module).addIdentityType(identity.getQName(), newType);
680 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
682 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
686 * Converts all <b>groupings</b> of the module to the list of
687 * <code>Type</code> objects. Firstly are groupings sorted according mutual
688 * dependencies. At least dependent (independent) groupings are in the list
689 * saved at first positions. For every grouping the record is added to map
690 * {@link BindingGeneratorImpl#allGroupings allGroupings}
695 * of groupings from which types will be generated
698 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
699 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
700 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
702 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
703 groupingToGenType(basePackageName, grouping, module);
708 * Converts individual grouping to GeneratedType. Firstly generated type
709 * builder is created and every child node of grouping is resolved to the
712 * @param basePackageName
713 * string contains the module package name
715 * GroupingDefinition which contains data about grouping
718 * @return GeneratedType which is generated from grouping (object of type
719 * <code>GroupingDefinition</code>)
721 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
722 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
723 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
724 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
725 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
726 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
727 groupingsToGenTypes(module, grouping.getGroupings());
728 processUsesAugments(grouping, module);
732 * Adds enumeration builder created from <code>enumTypeDef</code> to
733 * <code>typeBuilder</code>.
735 * Each <code>enumTypeDef</code> item is added to builder with its name and
739 * EnumTypeDefinition contains enum data
741 * string contains name which will be assigned to enumeration
744 * GeneratedTypeBuilder to which will be enum builder assigned
746 * Module in which type should be generated
747 * @return enumeration builder which contains data from
748 * <code>enumTypeDef</code>
750 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
751 final GeneratedTypeBuilder typeBuilder, final Module module) {
752 if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
753 && (enumTypeDef.getQName().getLocalName() != null)) {
754 final String enumerationName = BindingMapping.getClassName(enumName);
755 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
756 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
757 enumBuilder.setDescription(enumTypedefDescription);
758 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
759 ModuleContext ctx = genCtx.get(module);
760 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
767 * Generates type builder for <code>module</code>.
770 * Module which is source of package name for generated type
773 * string which is added to the module class name representation
775 * @return instance of GeneratedTypeBuilder which represents
776 * <code>module</code>.
777 * @throws IllegalArgumentException
778 * if <code>module</code> is null
780 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
781 checkArgument(module != null, "Module reference cannot be NULL.");
782 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
783 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
785 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
786 moduleBuilder.setDescription(createDescription(module));
787 moduleBuilder.setReference(module.getReference());
788 moduleBuilder.setModuleName(moduleName);
790 return moduleBuilder;
794 * Converts <code>augSchema</code> to list of <code>Type</code> which
795 * contains generated type for augmentation. In addition there are also
796 * generated types for all containers, list and choices which are child of
797 * <code>augSchema</code> node or a generated types for cases are added if
798 * augmented node is choice.
800 * @param augmentPackageName
801 * string with the name of the package to which the augmentation
804 * AugmentationSchema which is contains data about augmentation
805 * (target path, childs...)
808 * @param parentUsesNode
809 * @throws IllegalArgumentException
811 * <li>if <code>augmentPackageName</code> equals null</li>
812 * <li>if <code>augSchema</code> equals null</li>
814 * @throws IllegalStateException
815 * if augment target path is null
817 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
818 final Module module) {
819 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
820 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
821 checkState(augSchema.getTargetPath() != null,
822 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
824 processUsesAugments(augSchema, module);
825 final SchemaPath targetPath = augSchema.getTargetPath();
826 SchemaNode targetSchemaNode = null;
828 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
829 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
830 if (targetSchemaNode instanceof DerivableSchemaNode) {
831 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
833 if (targetSchemaNode == null) {
834 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
835 + " in module " + module.getName());
838 if (targetSchemaNode == null) {
839 throw new IllegalArgumentException("augment target not found: " + targetPath);
842 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
843 if (targetTypeBuilder == null) {
844 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
846 if (targetTypeBuilder == null) {
847 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
850 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
851 final String packageName = augmentPackageName;
852 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
853 targetTypeBuilder.getName());
854 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
857 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
858 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
862 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
863 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
864 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
865 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
866 checkState(augSchema.getTargetPath() != null,
867 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
869 processUsesAugments(augSchema, module);
870 final SchemaPath targetPath = augSchema.getTargetPath();
871 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
872 if (targetSchemaNode == null) {
873 throw new IllegalArgumentException("augment target not found: " + targetPath);
876 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
877 if (targetTypeBuilder == null) {
878 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
880 if (targetTypeBuilder == null) {
881 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
884 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
885 String packageName = augmentPackageName;
886 if (usesNodeParent instanceof SchemaNode) {
887 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
889 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
892 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
893 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
898 * Convenient method to find node added by uses statement.
902 * @param parentUsesNode
903 * parent of uses node
904 * @return node from its original location in grouping
906 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
907 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
909 if (!(targetGrouping instanceof GroupingDefinition)) {
910 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
913 final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
914 SchemaNode result = grouping;
915 for (final QName node : targetPath.getPathFromRoot()) {
916 // finding by local name is valid, grouping cannot contain nodes
917 // with same name and different namespace
918 if (result instanceof DataNodeContainer) {
919 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
920 } else if (result instanceof ChoiceSchemaNode) {
921 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
924 if (result == null) {
928 if (result instanceof DerivableSchemaNode) {
929 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
930 Optional<? extends SchemaNode> originalNode = castedResult
932 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
933 result = originalNode.get();
937 if (result instanceof DataSchemaNode) {
938 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
939 if (resultDataSchemaNode.isAddedByUses()) {
940 // The original node is required, but we have only the copy of
941 // the original node.
942 // Maybe this indicates a bug in Yang parser.
943 throw new IllegalStateException(
944 "Failed to generate code for augment in "
947 return resultDataSchemaNode;
950 throw new IllegalStateException(
951 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
957 * Returns a generated type builder for an augmentation.
959 * The name of the type builder is equal to the name of augmented node with
960 * serial number as suffix.
964 * @param augmentPackageName
965 * string with contains the package name to which the augment
967 * @param basePackageName
968 * string with the package name to which the augmented node
970 * @param targetTypeRef
973 * augmentation schema which contains data about the child nodes
974 * and uses of augment
975 * @return generated type builder for augment
977 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
978 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
979 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
980 if (augmentBuilders == null) {
981 augmentBuilders = new HashMap<>();
982 genTypeBuilders.put(augmentPackageName, augmentBuilders);
984 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
987 if (augIdentifier != null) {
988 augTypeName = BindingMapping.getClassName(augIdentifier);
990 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
993 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
995 augTypeBuilder.addImplementsType(DATA_OBJECT);
996 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
997 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
998 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1000 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
1001 augmentBuilders.put(augTypeName, augTypeBuilder);
1003 if(!augSchema.getChildNodes().isEmpty()) {
1004 genCtx.get(module).addTargetToAugmentation(targetTypeRef, augTypeBuilder);
1005 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1008 genCtx.get(module).addAugmentType(augTypeBuilder);
1009 return augTypeBuilder;
1014 * @param unknownSchemaNodes
1015 * @return nodeParameter of UnknownSchemaNode
1017 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1018 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1019 final QName nodeType = unknownSchemaNode.getNodeType();
1020 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1021 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1022 return unknownSchemaNode.getNodeParameter();
1029 * Returns first unique name for the augment generated type builder. The
1030 * generated type builder name for augment consists from name of augmented
1031 * node and serial number of its augmentation.
1034 * map of builders which were created in the package to which the
1035 * augmentation belongs
1036 * @param genTypeName
1037 * string with name of augmented node
1038 * @return string with unique name for augmentation builder
1040 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1042 if (builders != null) {
1043 while (builders.containsKey(genTypeName + index)) {
1047 return genTypeName + index;
1051 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1052 * node for which <code>typeBuilder</code> was created.
1054 * The subnodes aren't mapped to the methods if they are part of grouping or
1055 * augment (in this case are already part of them).
1059 * @param basePackageName
1060 * string contains the module package name
1062 * generated type builder which represents any node. The subnodes
1063 * of this node are added to the <code>typeBuilder</code> as
1064 * methods. The subnode can be of type leaf, leaf-list, list,
1065 * container, choice.
1068 * @param schemaNodes
1069 * set of data schema nodes which are the children of the node
1070 * for which <code>typeBuilder</code> was created
1071 * @return generated type builder which is the same builder as input
1072 * parameter. The getter methods (representing child nodes) could be
1075 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1076 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1077 if (schemaNodes != null && parent != null) {
1078 for (final DataSchemaNode schemaNode : schemaNodes) {
1079 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1080 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1088 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1089 * node for which <code>typeBuilder</code> was created.
1093 * @param basePackageName
1094 * string contains the module package name
1095 * @param typeBuilder
1096 * generated type builder which represents any node. The subnodes
1097 * of this node are added to the <code>typeBuilder</code> as
1098 * methods. The subnode can be of type leaf, leaf-list, list,
1099 * container, choice.
1102 * @param schemaNodes
1103 * set of data schema nodes which are the children of the node
1104 * for which <code>typeBuilder</code> was created
1105 * @return generated type builder which is the same object as the input
1106 * parameter <code>typeBuilder</code>. The getter method could be
1109 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1110 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1111 final Iterable<DataSchemaNode> schemaNodes) {
1112 if ((schemaNodes != null) && (typeBuilder != null)) {
1113 for (final DataSchemaNode schemaNode : schemaNodes) {
1114 if (!schemaNode.isAugmenting()) {
1115 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1123 * Adds to <code>typeBuilder</code> a method which is derived from
1124 * <code>schemaNode</code>.
1126 * @param basePackageName
1127 * string with the module package name
1129 * data schema node which is added to <code>typeBuilder</code> as
1131 * @param typeBuilder
1132 * generated type builder to which is <code>schemaNode</code>
1133 * added as a method.
1139 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1140 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1141 if (node != null && typeBuilder != null) {
1142 if (node instanceof LeafSchemaNode) {
1143 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1144 } else if (node instanceof LeafListSchemaNode) {
1145 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1146 } else if (node instanceof ContainerSchemaNode) {
1147 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1148 } else if (node instanceof ListSchemaNode) {
1149 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1150 } else if (node instanceof ChoiceSchemaNode) {
1151 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1153 // TODO: anyxml not yet supported
1154 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1155 typeBuilder.getFullyQualifiedName());
1161 * Converts <code>choiceNode</code> to the list of generated types for
1162 * choice and its cases.
1164 * The package names for choice and for its cases are created as
1165 * concatenation of the module package (<code>basePackageName</code>) and
1166 * names of all parents node.
1170 * @param basePackageName
1171 * string with the module package name
1175 * choice node which is mapped to generated type. Also child
1176 * nodes - cases are mapped to generated types.
1177 * @throws IllegalArgumentException
1179 * <li>if <code>basePackageName</code> is null</li>
1180 * <li>if <code>choiceNode</code> is null</li>
1183 private void choiceToGeneratedType(final Module module, final String basePackageName,
1184 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1185 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1186 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1188 if (!choiceNode.isAddedByUses()) {
1189 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1190 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1191 constructGetter(parent, choiceNode.getQName().getLocalName(),
1192 choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
1193 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1194 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1195 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1196 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1201 * Converts <code>caseNodes</code> set to list of corresponding generated
1204 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1205 * created generated type builder. The package names for the builder is
1206 * created as concatenation of the module package (
1207 * <code>basePackageName</code>) and names of all parents nodes of the
1208 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1209 * between every case builder and <i>choice</i> type
1213 * @param basePackageName
1214 * string with the module package name
1215 * @param refChoiceType
1216 * type which represents superior <i>case</i>
1218 * choice case node which is mapped to generated type
1219 * @return list of generated types for <code>caseNodes</code>.
1220 * @throws IllegalArgumentException
1222 * <li>if <code>basePackageName</code> equals null</li>
1223 * <li>if <code>refChoiceType</code> equals null</li>
1224 * <li>if <code>caseNodes</code> equals null</li>
1227 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1228 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1229 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1230 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1231 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1233 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1234 if (caseNodes == null) {
1238 for (final ChoiceCaseNode caseNode : caseNodes) {
1239 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1240 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1241 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1242 caseTypeBuilder.addImplementsType(refChoiceType);
1243 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1244 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1245 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1246 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1247 if (caseChildNodes != null) {
1248 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1250 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1251 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1253 if (parent instanceof AugmentationSchema) {
1254 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1255 final SchemaPath targetPath = augSchema.getTargetPath();
1256 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1257 if (targetSchemaNode instanceof DataSchemaNode
1258 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1259 if (targetSchemaNode instanceof DerivableSchemaNode) {
1260 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1262 if (targetSchemaNode == null) {
1263 throw new IllegalStateException(
1264 "Failed to find target node from grouping for augmentation " + augSchema
1265 + " in module " + module.getName());
1268 parent = targetSchemaNode;
1271 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1272 choiceNodeParentPath);
1273 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1274 if (childOfType == null) {
1275 childOfType = findGroupingByPath(parent.getPath());
1277 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1279 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1284 processUsesAugments(caseNode, module);
1289 * Generates list of generated types for all the cases of a choice which are
1290 * added to the choice through the augment.
1294 * @param basePackageName
1295 * string contains name of package to which augment belongs. If
1296 * an augmented choice is from an other package (pcg1) than an
1297 * augmenting choice (pcg2) then case's of the augmenting choice
1298 * will belong to pcg2.
1300 * Type which represents target choice
1302 * node which represents target choice
1303 * @param augmentedNodes
1304 * set of choice case nodes for which is checked if are/aren't
1305 * added to choice through augmentation
1306 * @return list of generated types which represents augmented cases of
1307 * choice <code>refChoiceType</code>
1308 * @throws IllegalArgumentException
1310 * <li>if <code>basePackageName</code> is null</li>
1311 * <li>if <code>targetType</code> is null</li>
1312 * <li>if <code>augmentedNodes</code> is null</li>
1315 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1316 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1317 final DataNodeContainer usesNodeParent) {
1318 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1319 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1320 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1322 for (final DataSchemaNode caseNode : augmentedNodes) {
1323 if (caseNode != null) {
1324 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1325 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1326 caseTypeBuilder.addImplementsType(targetType);
1328 SchemaNode parent = null;
1329 final SchemaPath nodeSp = targetNode.getPath();
1330 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1332 GeneratedTypeBuilder childOfType = null;
1333 if (parent instanceof Module) {
1334 childOfType = genCtx.get(parent).getModuleNode();
1335 } else if (parent instanceof ChoiceCaseNode) {
1336 childOfType = findCaseByPath(parent.getPath());
1337 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1338 childOfType = findChildNodeByPath(parent.getPath());
1339 } else if (parent instanceof GroupingDefinition) {
1340 childOfType = findGroupingByPath(parent.getPath());
1343 if (childOfType == null) {
1344 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1347 ChoiceCaseNode node = null;
1348 final String caseLocalName = caseNode.getQName().getLocalName();
1349 if (caseNode instanceof ChoiceCaseNode) {
1350 node = (ChoiceCaseNode) caseNode;
1351 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
1352 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1353 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1354 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1355 ().getLocalName())) {
1356 node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
1361 node = targetNode.getCaseNodeByName(caseLocalName);
1363 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1364 if (childNodes != null) {
1365 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1367 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1368 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1373 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1374 // Deal with old parser, clearing out references to typedefs
1375 if (type instanceof ExtendedType) {
1379 // New parser with encapsulated type
1380 if (leaf.getPath().equals(type.getPath())) {
1384 // Embedded type definition with new parser. Also takes care of the old parser with bits
1385 if (leaf.getPath().equals(type.getPath().getParent())) {
1393 * Converts <code>leaf</code> to the getter method which is added to
1394 * <code>typeBuilder</code>.
1396 * @param typeBuilder
1397 * generated type builder to which is added getter method as
1398 * <code>leaf</code> mapping
1400 * leaf schema node which is mapped as getter method which is
1401 * added to <code>typeBuilder</code>
1403 * Module in which type was defined
1404 * @return boolean value
1406 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1408 * <li>true - in other cases</li>
1411 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1412 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1416 final String leafName = leaf.getQName().getLocalName();
1417 if (leafName == null) {
1421 final Module parentModule = findParentModule(schemaContext, leaf);
1422 Type returnType = null;
1424 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1425 if (isInnerType(leaf, typeDef)) {
1426 if (typeDef instanceof EnumTypeDefinition) {
1427 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1428 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1429 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1430 typeBuilder, module);
1432 if (enumBuilder != null) {
1433 returnType = enumBuilder.toInstance(typeBuilder);
1435 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1436 } else if (typeDef instanceof UnionTypeDefinition) {
1437 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1438 if (genTOBuilder != null) {
1439 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1441 } else if (typeDef instanceof BitsTypeDefinition) {
1442 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1443 if (genTOBuilder != null) {
1444 returnType = genTOBuilder.toInstance();
1447 // It is constrained version of already declared type (inner declared type exists,
1448 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1449 // In order to get proper class we need to look up closest derived type
1450 // and apply restrictions from leaf type
1451 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1452 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1456 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1457 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1460 if (returnType == null) {
1464 String leafDesc = leaf.getDescription();
1465 if (leafDesc == null) {
1469 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType, leaf.getStatus());
1470 processContextRefExtension(leaf, getter, parentModule);
1474 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1475 if (typeDef instanceof ExtendedType) {
1476 // Legacy behaviour returning ExtendedType is enough
1479 // Returns DerivedType in case of new parser.
1480 final TypeDefinition<?> baseType = typeDef.getBaseType();
1481 return (baseType != null && baseType.getBaseType() != null) ? baseType : typeDef;
1484 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1485 final Module module) {
1486 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1487 final QName nodeType = node.getNodeType();
1488 if ("context-reference".equals(nodeType.getLocalName())) {
1489 final String nodeParam = node.getNodeParameter();
1490 IdentitySchemaNode identity = null;
1491 String basePackageName = null;
1492 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1493 final Iterator<String> iterator = splittedElement.iterator();
1494 final int length = Iterables.size(splittedElement);
1496 identity = findIdentityByName(module.getIdentities(), iterator.next());
1497 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1498 } else if (length == 2) {
1499 final String prefix = iterator.next();
1500 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1501 if (dependentModule == null) {
1502 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1505 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1506 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1508 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1511 if (identity == null) {
1512 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1516 final Class<RoutingContext> clazz = RoutingContext.class;
1517 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1518 clazz.getSimpleName());
1519 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1520 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1521 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1526 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1527 for (final IdentitySchemaNode id : identities) {
1528 if (id.getQName().getLocalName().equals(name)) {
1535 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1536 for (final ModuleImport imp : imports) {
1537 if (imp.getPrefix().equals(prefix)) {
1538 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1544 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1545 final boolean isReadOnly, final Module module) {
1546 if ((leaf != null) && (toBuilder != null)) {
1547 String leafDesc = leaf.getDescription();
1548 if (leafDesc == null) {
1551 Type returnType = null;
1552 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1553 if (typeDef instanceof UnionTypeDefinition) {
1554 // GeneratedType for this type definition should be already
1556 final QName qname = typeDef.getQName();
1557 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1558 qname.getRevision());
1559 final ModuleContext mc = genCtx.get(unionModule);
1560 returnType = mc.getTypedefs().get(typeDef.getPath());
1561 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1562 // Annonymous enumeration (already generated, since it is inherited via uses).
1563 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1564 QName qname = originalLeaf.getQName();
1565 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1566 qname.getRevision());
1567 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1569 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1571 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1577 * Converts <code>leaf</code> schema node to property of generated TO
1581 * generated TO builder to which is <code>leaf</code> added as
1584 * leaf schema node which is added to <code>toBuilder</code> as
1589 * boolean value which says if leaf property is|isn't read only
1590 * @return boolean value
1592 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1593 * name equals null or if leaf is added by <i>uses</i>.</li>
1594 * <li>true - other cases</li>
1597 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1598 final Type returnType, final boolean isReadOnly) {
1599 if (returnType == null) {
1602 final String leafName = leaf.getQName().getLocalName();
1603 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
1604 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1605 propBuilder.setReadOnly(isReadOnly);
1606 propBuilder.setReturnType(returnType);
1607 propBuilder.setComment(leafDesc);
1608 toBuilder.addEqualsIdentity(propBuilder);
1609 toBuilder.addHashIdentity(propBuilder);
1610 toBuilder.addToStringProperty(propBuilder);
1615 * Converts <code>node</code> leaf list schema node to getter method of
1616 * <code>typeBuilder</code>.
1618 * @param typeBuilder
1619 * generated type builder to which is <code>node</code> added as
1622 * leaf list schema node which is added to
1623 * <code>typeBuilder</code> as getter method
1625 * @return boolean value
1627 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1628 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1629 * <li>false - other cases</li>
1632 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1633 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1637 final QName nodeName = node.getQName();
1638 if (nodeName == null) {
1642 final TypeDefinition<?> typeDef = node.getType();
1643 final Module parentModule = findParentModule(schemaContext, node);
1645 Type returnType = null;
1646 if (typeDef.getBaseType() == null) {
1647 if (typeDef instanceof EnumTypeDefinition) {
1648 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1649 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1650 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1651 typeBuilder,module);
1652 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1653 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1654 } else if (typeDef instanceof UnionTypeDefinition) {
1655 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1656 if (genTOBuilder != null) {
1657 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1659 } else if (typeDef instanceof BitsTypeDefinition) {
1660 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1661 returnType = genTOBuilder.toInstance();
1663 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1664 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1667 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1668 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1671 final ParameterizedType listType = Types.listTypeFor(returnType);
1672 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
1676 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1677 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1678 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1679 genTOBuilder.getName());
1680 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1682 returnType.setDescription(typedefDescription);
1683 returnType.setReference(typeDef.getReference());
1684 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1685 returnType.setModuleName(parentModule.getName());
1687 genTOBuilder.setTypedef(true);
1688 genTOBuilder.setIsUnion(true);
1689 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1693 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1696 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1697 method.setReturnType(returnType);
1698 method.addParameter(Types.STRING, "defaultValue");
1699 method.setAccessModifier(AccessModifier.PUBLIC);
1700 method.setStatic(true);
1702 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1703 if (types == null) {
1704 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1705 Sets.<Type> newHashSet(unionBuilder.toInstance()));
1707 types.add(unionBuilder.toInstance());
1709 return returnType.toInstance();
1712 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1713 final String outerCls = Types.getOuterClassName(genTOBuilder);
1714 final StringBuilder name;
1715 if (outerCls != null) {
1716 name = new StringBuilder(outerCls);
1718 name = new StringBuilder();
1720 name.append(genTOBuilder.getName());
1721 name.append("Builder");
1722 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1723 unionBuilder.setIsUnionBuilder(true);
1724 return unionBuilder;
1727 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1728 final Module module) {
1729 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1733 * Instantiates generated type builder with <code>packageName</code> and
1734 * <code>schemaNode</code>.
1736 * The new builder always implements
1737 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1738 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1739 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1741 * If <code>schemaNode</code> is instance of
1742 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1743 * DataNodeContainer} it can also implement nodes which are specified in
1746 * @param packageName
1747 * string with the name of the package to which
1748 * <code>schemaNode</code> belongs.
1750 * schema node for which is created generated type builder
1752 * parent type (can be null)
1753 * @return generated type builder <code>schemaNode</code>
1755 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1756 final Type parent, final Module module) {
1757 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1758 if (parent == null) {
1759 it.addImplementsType(DATA_OBJECT);
1761 it.addImplementsType(BindingTypes.childOf(parent));
1763 if (!(schemaNode instanceof GroupingDefinition)) {
1764 it.addImplementsType(augmentable(it));
1767 if (schemaNode instanceof DataNodeContainer) {
1768 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1769 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1776 * Wraps the calling of the same overloaded method.
1778 * @param packageName
1779 * string with the package name to which returning generated type
1782 * schema node which provide data about the schema node name
1783 * @return generated type builder for <code>schemaNode</code>
1785 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1786 return addRawInterfaceDefinition(packageName, schemaNode, "");
1790 * Returns reference to generated type builder for specified
1791 * <code>schemaNode</code> with <code>packageName</code>.
1793 * Firstly the generated type builder is searched in
1794 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1795 * found it is created and added to <code>genTypeBuilders</code>.
1797 * @param packageName
1798 * string with the package name to which returning generated type
1801 * schema node which provide data about the schema node name
1803 * return type name prefix
1804 * @return generated type builder for <code>schemaNode</code>
1805 * @throws IllegalArgumentException
1807 * <li>if <code>schemaNode</code> is null</li>
1808 * <li>if <code>packageName</code> is null</li>
1809 * <li>if QName of schema node is null</li>
1810 * <li>if schemaNode name is null</li>
1814 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1815 final String prefix) {
1816 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1817 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1818 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1819 final String schemaNodeName = schemaNode.getQName().getLocalName();
1820 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1823 if (prefix == null) {
1824 genTypeName = BindingMapping.getClassName(schemaNodeName);
1826 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1829 // FIXME: Validation of name conflict
1830 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1831 final Module module = findParentModule(schemaContext, schemaNode);
1832 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1833 newType.addComment(schemaNode.getDescription());
1834 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1835 newType.setReference(schemaNode.getReference());
1836 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1837 newType.setModuleName(module.getName());
1839 if (!genTypeBuilders.containsKey(packageName)) {
1840 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1841 builders.put(genTypeName, newType);
1842 genTypeBuilders.put(packageName, builders);
1844 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1845 if (!builders.containsKey(genTypeName)) {
1846 builders.put(genTypeName, newType);
1853 * Creates the name of the getter method name from <code>localName</code>.
1856 * string with the name of the getter method
1859 * @return string with the name of the getter method for
1860 * <code>methodName</code> in JAVA method format
1862 public static String getterMethodName(final String localName, final Type returnType) {
1863 final StringBuilder method = new StringBuilder();
1864 if (BOOLEAN.equals(returnType)) {
1865 method.append("is");
1867 method.append("get");
1869 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1870 method.append(name);
1871 return method.toString();
1875 * Created a method signature builder as part of
1876 * <code>interfaceBuilder</code>.
1878 * The method signature builder is created for the getter method of
1879 * <code>schemaNodeName</code>. Also <code>comment</code> and
1880 * <code>returnType</code> information are added to the builder.
1882 * @param interfaceBuilder
1883 * generated type builder for which the getter method should be
1885 * @param schemaNodeName
1886 * string with schema node name. The name will be the part of the
1887 * getter method name.
1889 * string with comment for the getter method
1891 * type which represents the return type of the getter method
1893 * status from yang file, for deprecated annotation
1894 * @return method signature builder which represents the getter method of
1895 * <code>interfaceBuilder</code>
1897 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1898 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1899 final MethodSignatureBuilder getMethod = interfaceBuilder
1900 .addMethod(getterMethodName(schemaNodeName, returnType));
1901 if (status == Status.DEPRECATED) {
1902 getMethod.addAnnotation("", "Deprecated");
1904 getMethod.setComment(encodeAngleBrackets(comment));
1905 getMethod.setReturnType(returnType);
1910 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1911 * or to <code>genTOBuilder</code> as property.
1913 * @param basePackageName
1914 * string contains the module package name
1916 * data schema node which should be added as getter method to
1917 * <code>typeBuilder</code> or as a property to
1918 * <code>genTOBuilder</code> if is part of the list key
1919 * @param typeBuilder
1920 * generated type builder for the list schema node
1921 * @param genTOBuilder
1922 * generated TO builder for the list keys
1924 * list of string which contains names of the list keys
1927 * @throws IllegalArgumentException
1929 * <li>if <code>schemaNode</code> equals null</li>
1930 * <li>if <code>typeBuilder</code> equals null</li>
1933 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1934 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1935 final Module module) {
1936 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1937 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1939 if (schemaNode instanceof LeafSchemaNode) {
1940 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1941 final String leafName = leaf.getQName().getLocalName();
1942 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1943 if (listKeys.contains(leafName)) {
1945 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1947 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1950 } else if (!schemaNode.isAddedByUses()) {
1951 if (schemaNode instanceof LeafListSchemaNode) {
1952 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1953 } else if (schemaNode instanceof ContainerSchemaNode) {
1954 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1955 } else if (schemaNode instanceof ChoiceSchemaNode) {
1956 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1957 } else if (schemaNode instanceof ListSchemaNode) {
1958 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1963 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1964 final GeneratedTOBuilder genTOBuilder) {
1965 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1967 if (genTOBuilder != null) {
1968 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1969 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1970 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1975 * Selects the names of the list keys from <code>list</code> and returns
1976 * them as the list of the strings
1979 * of string with names of the list keys
1980 * @return list of string which represents names of the list keys. If the
1981 * <code>list</code> contains no keys then the empty list is
1984 private static List<String> listKeys(final ListSchemaNode list) {
1985 final List<String> listKeys = new ArrayList<>();
1987 final List<QName> keyDefinition = list.getKeyDefinition();
1988 if (keyDefinition != null) {
1989 for (final QName keyDef : keyDefinition) {
1990 listKeys.add(keyDef.getLocalName());
1997 * Generates for the <code>list</code> which contains any list keys special
1998 * generated TO builder.
2000 * @param packageName
2001 * string with package name to which the list belongs
2003 * list schema node which is source of data about the list name
2004 * @return generated TO builder which represents the keys of the
2005 * <code>list</code> or null if <code>list</code> is null or list of
2006 * key definitions is null or empty.
2008 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
2009 GeneratedTOBuilder genTOBuilder = null;
2010 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
2011 final String listName = list.getQName().getLocalName() + "Key";
2012 final String genTOName = BindingMapping.getClassName(listName);
2013 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
2015 return genTOBuilder;
2019 * Builds generated TO builders for <code>typeDef</code> of type
2020 * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
2021 * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
2022 * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
2023 * enclosing transfer object.
2025 * If more then one generated TO builder is created for enclosing then all
2026 * of the generated TO builders are added to <code>typeBuilder</code> as
2027 * enclosing transfer objects.
2030 * type definition which can be of type <code>UnionType</code> or
2031 * <code>BitsTypeDefinition</code>
2032 * @param typeBuilder
2033 * generated type builder to which is added generated TO created
2034 * from <code>typeDef</code>
2036 * string with name for generated TO builder
2038 * @return generated TO builder for <code>typeDef</code>
2040 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2041 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2042 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2043 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2044 final String packageName = typeBuilder.getFullyQualifiedName();
2045 if (typeDef instanceof UnionTypeDefinition) {
2046 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2047 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
2048 classNameFromLeaf, leaf);
2049 genTOBuilders.addAll(types);
2051 GeneratedTOBuilder resultTOBuilder = null;
2052 if (types.isEmpty()) {
2053 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2055 resultTOBuilder = types.remove(0);
2056 for (final GeneratedTOBuilder genTOBuilder : types) {
2057 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2060 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2061 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2062 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2063 resultTOBuilder.addHashIdentity(genPropBuilder);
2064 resultTOBuilder.addToStringProperty(genPropBuilder);
2066 } else if (typeDef instanceof BitsTypeDefinition) {
2067 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
2068 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2070 if (!genTOBuilders.isEmpty()) {
2071 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2072 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2074 return genTOBuilders.get(0);
2081 * Adds the implemented types to type builder.
2083 * The method passes through the list of <i>uses</i> in
2084 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2085 * generated type from {@link BindingGeneratorImpl#allGroupings
2086 * allGroupings} which is added as <i>implements type</i> to
2087 * <code>builder</code>
2089 * @param dataNodeContainer
2090 * element which contains the list of used YANG groupings
2092 * builder to which are added implemented types according to
2093 * <code>dataNodeContainer</code>
2094 * @return generated type builder with all implemented types
2096 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2097 final GeneratedTypeBuilder builder) {
2098 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2099 if (usesNode.getGroupingPath() != null) {
2100 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2101 if (genType == null) {
2102 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2103 + builder.getName());
2106 builder.addImplementsType(genType);
2108 builder.addComment(genType.getDescription());
2109 builder.setDescription(genType.getDescription());
2110 builder.setModuleName(genType.getModuleName());
2111 builder.setReference(genType.getReference());
2112 builder.setSchemaPath(genType.getSchemaPath());
2119 private static boolean isNullOrEmpty(final Collection<?> list) {
2120 return list == null || list.isEmpty();
2123 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2124 final StringBuilder sb = new StringBuilder();
2126 if (!isNullOrEmpty(schemaNodes)) {
2127 final SchemaNode node = schemaNodes.iterator().next();
2129 if (node instanceof RpcDefinition) {
2130 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2131 } else if (node instanceof NotificationDefinition) {
2132 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2135 sb.append(NEW_LINE);
2137 if (verboseClassComments) {
2139 sb.append(NEW_LINE);
2140 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2141 sb.append("</pre>");
2142 sb.append(NEW_LINE);
2145 return replaceAllIllegalChars(sb);
2148 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2149 final StringBuilder sb = new StringBuilder();
2150 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
2151 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2153 if (!Strings.isNullOrEmpty(formattedDescription)) {
2154 sb.append(formattedDescription);
2155 sb.append(NEW_LINE);
2158 if (verboseClassComments) {
2159 final Module module = findParentModule(schemaContext, schemaNode);
2160 final StringBuilder linkToBuilderClass = new StringBuilder();
2161 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2162 final String className = namespace[namespace.length - 1];
2164 if (hasBuilderClass(schemaNode)) {
2165 linkToBuilderClass.append(className);
2166 linkToBuilderClass.append("Builder");
2170 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2171 sb.append(module.getName());
2173 sb.append(NEW_LINE);
2175 sb.append(NEW_LINE);
2176 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2177 sb.append("</pre>");
2178 sb.append(NEW_LINE);
2179 sb.append("The schema path to identify an instance is");
2180 sb.append(NEW_LINE);
2182 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2184 sb.append(NEW_LINE);
2186 if (hasBuilderClass(schemaNode)) {
2187 sb.append(NEW_LINE);
2188 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2189 sb.append(NEW_LINE);
2191 sb.append(linkToBuilderClass);
2192 sb.append(NEW_LINE);
2193 if (schemaNode instanceof ListSchemaNode) {
2194 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2195 if (keyDef != null && !keyDef.isEmpty()) {
2197 sb.append(className);
2200 sb.append(NEW_LINE);
2205 return replaceAllIllegalChars(sb);
2208 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2209 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2210 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2216 private String createDescription(final Module module) {
2217 final StringBuilder sb = new StringBuilder();
2218 final String moduleDescription = encodeAngleBrackets(module.getDescription());
2219 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2221 if (!Strings.isNullOrEmpty(formattedDescription)) {
2222 sb.append(formattedDescription);
2223 sb.append(NEW_LINE);
2226 if (verboseClassComments) {
2228 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2229 sb.append(module.getName());
2231 sb.append(NEW_LINE);
2233 sb.append(NEW_LINE);
2234 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2235 sb.append("</pre>");
2238 return replaceAllIllegalChars(sb);
2241 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2242 for (final ModuleContext ctx : genCtx.values()) {
2243 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2244 if (result != null) {
2251 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2252 for (final ModuleContext ctx : genCtx.values()) {
2253 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2254 if (result != null) {
2261 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2262 for (final ModuleContext ctx : genCtx.values()) {
2263 final GeneratedTypeBuilder result = ctx.getCase(path);
2264 if (result != null) {
2271 public Map<Module, ModuleContext> getModuleContexts() {
2276 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2277 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2278 return ret.isEmpty() ? "" : ret;
2281 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2282 if (status == Status.DEPRECATED) {
2283 builder.addAnnotation("", "Deprecated");