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.mdsal.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.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.encodeAngleBrackets;
15 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIABLE;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.IDENTIFIER;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
23 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
24 import static org.opendaylight.mdsal.binding.model.util.Types.FUTURE;
25 import static org.opendaylight.mdsal.binding.model.util.Types.VOID;
26 import static org.opendaylight.mdsal.binding.model.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;
31 import com.google.common.annotations.VisibleForTesting;
32 import com.google.common.base.Optional;
33 import com.google.common.base.Preconditions;
34 import com.google.common.base.Splitter;
35 import com.google.common.base.Strings;
36 import com.google.common.collect.Iterables;
37 import com.google.common.collect.Sets;
38 import java.util.ArrayList;
39 import java.util.Collection;
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.mdsal.binding.generator.api.BindingGenerator;
48 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
49 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
50 import org.opendaylight.mdsal.binding.model.api.Constant;
51 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
52 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
53 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
54 import org.opendaylight.mdsal.binding.model.api.Restrictions;
55 import org.opendaylight.mdsal.binding.model.api.Type;
56 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
57 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
58 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
59 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
60 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
61 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
62 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
63 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
64 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
65 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
66 import org.opendaylight.mdsal.binding.model.util.Types;
67 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
68 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTOBuilderImpl;
69 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTypeBuilderImpl;
70 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
71 import org.opendaylight.mdsal.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.meta.EffectiveStatement;
103 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
104 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
105 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
106 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
107 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
108 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
109 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
110 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
111 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
115 public class BindingGeneratorImpl implements BindingGenerator {
116 private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
117 private static final Splitter COLON_SPLITTER = Splitter.on(':');
118 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
119 private static final char NEW_LINE = '\n';
122 * Comparator based on augment target path.
124 private static final Comparator<AugmentationSchema> AUGMENT_COMP = (o1, o2) -> {
125 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
126 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
128 while (thisIt.hasNext()) {
129 if (!otherIt.hasNext()) {
133 final int comp = thisIt.next().compareTo(otherIt.next());
139 return otherIt.hasNext() ? -1 : 0;
143 * Constant with the concrete name of identifier.
145 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
148 * Constant with the concrete name of namespace.
150 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
152 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
154 private final Map<Module, ModuleContext> genCtx = new HashMap<>();
157 * When set to true, generated classes will include javadoc comments which
158 * are useful for users.
160 private final boolean verboseClassComments;
163 * Outer key represents the package name. Outer value represents map of all
164 * builders in the same package. Inner key represents the schema node name
165 * (in JAVA class/interface name format). Inner value represents instance of
166 * builder for schema node specified in key part.
168 private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
171 * Provide methods for converting YANG types to JAVA types.
173 private TypeProvider typeProvider;
176 * Holds reference to schema context to resolve data of augmented element
177 * when creating augmentation builder
179 private SchemaContext schemaContext;
182 * Create a new binding generator.
184 * @param verboseClassComments generate verbose comments
186 public BindingGeneratorImpl(final boolean verboseClassComments) {
187 this.verboseClassComments = verboseClassComments;
191 * Resolves generated types from <code>context</code> schema nodes of all
194 * Generated types are created for modules, groupings, types, containers,
195 * lists, choices, augments, rpcs, notification, identities.
198 * schema context which contains data about all schema nodes
200 * @return list of types (usually <code>GeneratedType</code>
201 * <code>GeneratedTransferObject</code>which are generated from
202 * <code>context</code> data.
203 * @throws IllegalArgumentException
204 * if arg <code>context</code> is null
205 * @throws IllegalStateException
206 * if <code>context</code> contain no modules
209 public List<Type> generateTypes(final SchemaContext context) {
210 checkArgument(context != null, "Schema Context reference cannot be NULL.");
211 checkState(context.getModules() != null, "Schema Context does not contain defined modules.");
212 schemaContext = 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 %s cannot be NULL.", module.getName());
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 sortedAugmentations.sort(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();
515 //in case of implicit RPC input (StatementSource.CONTEXT),
516 // stay compatible (no input argument generated)
517 if (input != null && isExplicitStatement(input)) {
518 processUsesAugments(input, module);
519 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
520 addImplementedInterfaceFromUses(input, inType);
521 inType.addImplementsType(DATA_OBJECT);
522 inType.addImplementsType(augmentable(inType));
523 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
524 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
525 genCtx.get(module).addChildNodeType(input, inType);
526 final GeneratedType inTypeInstance = inType.toInstance();
527 method.addParameter(inTypeInstance, "input");
530 Type outTypeInstance = VOID;
531 //in case of implicit RPC output (StatementSource.CONTEXT),
532 //stay compatible (Future<RpcResult<Void>> return type generated)
533 if (output != null && isExplicitStatement(output)) {
534 processUsesAugments(output, module);
535 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
536 addImplementedInterfaceFromUses(output, outType);
537 outType.addImplementsType(DATA_OBJECT);
538 outType.addImplementsType(augmentable(outType));
539 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
540 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
541 genCtx.get(module).addChildNodeType(output, outType);
542 outTypeInstance = outType.toInstance();
545 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
546 method.setComment(rpcComment);
547 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
551 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
554 private static boolean isExplicitStatement(ContainerSchemaNode node) {
555 return node instanceof EffectiveStatement
556 && ((EffectiveStatement) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
560 * Converts all <b>notifications</b> of the module to the list of
561 * <code>Type</code> objects. In addition are to this list added containers
562 * and lists which are part of this notification.
565 * module from which is obtained set of all notification objects
566 * to iterate over them
567 * @throws IllegalArgumentException
569 * <li>if the module equals null</li>
570 * <li>if the name of module equals null</li>
572 * @throws IllegalStateException
573 * if set of notifications from module is null
575 private void notificationsToGenType(final Module module) {
576 checkArgument(module != null, "Module reference cannot be NULL.");
577 checkArgument(module.getName() != null, "Module name cannot be NULL.");
578 final Set<NotificationDefinition> notifications = module.getNotifications();
579 if (notifications.isEmpty()) {
583 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
584 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
585 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
589 for (final NotificationDefinition notification : notifications) {
590 if (notification != null) {
591 processUsesAugments(notification, module);
593 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
594 notification, null, module);
595 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
596 notificationInterface.addImplementsType(NOTIFICATION);
597 genCtx.get(module).addChildNodeType(notification, notificationInterface);
599 // Notification object
600 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
601 notification.getChildNodes());
603 listenerInterface.addMethod("on" + notificationInterface.getName())
604 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
605 .setComment(encodeAngleBrackets(notification.getDescription())).setReturnType(Types.VOID);
608 listenerInterface.setDescription(createDescription(notifications, module.getName()));
610 genCtx.get(module).addTopLevelNodeType(listenerInterface);
614 * Converts all <b>identities</b> of the module to the list of
615 * <code>Type</code> objects.
618 * module from which is obtained set of all identity objects to
621 * schema context only used as input parameter for method
622 * {@link BindingGeneratorImpl#identityToGenType}
625 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
626 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
627 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
629 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
630 for (final IdentitySchemaNode identity : schemaIdentities) {
631 identityToGenType(module, basePackageName, identity, context);
637 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
638 * created transport object builder. If identity contains base identity then
639 * reference to base identity is added to superior identity as its extend.
640 * If identity doesn't contain base identity then only reference to abstract
641 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
642 * BaseIdentity} is added
646 * @param basePackageName
647 * string contains the module package name
649 * IdentitySchemaNode which contains data about identity
651 * SchemaContext which is used to get package and name
652 * information about base of identity
655 private void identityToGenType(final Module module, final String basePackageName,
656 final IdentitySchemaNode identity, final SchemaContext context) {
657 if (identity == null) {
660 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
661 final String genTypeName = BindingMapping.getClassName(identity.getQName());
662 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
663 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
664 if (baseIdentity == null) {
665 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
666 BaseIdentity.class.getSimpleName());
667 newType.setExtendsType(gto.toInstance());
669 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
670 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
672 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
673 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
675 newType.setExtendsType(gto);
677 newType.setAbstract(true);
678 newType.addComment(identity.getDescription());
679 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
680 newType.setReference(identity.getReference());
681 newType.setModuleName(module.getName());
682 newType.setSchemaPath(identity.getPath().getPathFromRoot());
684 final QName qname = identity.getQName();
685 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
687 genCtx.get(module).addIdentityType(identity.getQName(), newType);
690 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
692 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
696 * Converts all <b>groupings</b> of the module to the list of
697 * <code>Type</code> objects. Firstly are groupings sorted according mutual
698 * dependencies. At least dependent (independent) groupings are in the list
699 * saved at first positions. For every grouping the record is added to map
700 * {@link ModuleContext#groupings allGroupings}
705 * collection of groupings from which types will be generated
708 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
709 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
710 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
712 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
713 groupingToGenType(basePackageName, grouping, module);
718 * Converts individual grouping to GeneratedType. Firstly generated type
719 * builder is created and every child node of grouping is resolved to the
722 * @param basePackageName
723 * string contains the module package name
725 * GroupingDefinition which contains data about grouping
728 * @return GeneratedType which is generated from grouping (object of type
729 * <code>GroupingDefinition</code>)
731 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
732 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
733 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
734 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
735 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
736 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
737 groupingsToGenTypes(module, grouping.getGroupings());
738 processUsesAugments(grouping, module);
742 * Adds enumeration builder created from <code>enumTypeDef</code> to
743 * <code>typeBuilder</code>.
745 * Each <code>enumTypeDef</code> item is added to builder with its name and
749 * EnumTypeDefinition contains enum data
751 * string contains name which will be assigned to enumeration
754 * GeneratedTypeBuilder to which will be enum builder assigned
756 * Module in which type should be generated
757 * @return enumeration builder which contains data from
758 * <code>enumTypeDef</code>
760 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
761 final GeneratedTypeBuilder typeBuilder, final Module module) {
762 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
763 final String enumerationName = BindingMapping.getClassName(enumName);
764 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
765 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
766 enumBuilder.setDescription(enumTypedefDescription);
767 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
768 ModuleContext ctx = genCtx.get(module);
769 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
776 * Generates type builder for <code>module</code>.
779 * Module which is source of package name for generated type
782 * string which is added to the module class name representation
784 * @return instance of GeneratedTypeBuilder which represents
785 * <code>module</code>.
786 * @throws IllegalArgumentException
787 * if <code>module</code> is null
789 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
790 checkArgument(module != null, "Module reference cannot be NULL.");
791 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
792 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
794 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
795 moduleBuilder.setDescription(createDescription(module));
796 moduleBuilder.setReference(module.getReference());
797 moduleBuilder.setModuleName(moduleName);
799 return moduleBuilder;
803 * Converts <code>augSchema</code> to list of <code>Type</code> which
804 * contains generated type for augmentation. In addition there are also
805 * generated types for all containers, list and choices which are child of
806 * <code>augSchema</code> node or a generated types for cases are added if
807 * augmented node is choice.
809 * @param augmentPackageName
810 * string with the name of the package to which the augmentation
813 * AugmentationSchema which is contains data about augmentation
814 * (target path, childs...)
817 * @throws IllegalArgumentException
819 * <li>if <code>augmentPackageName</code> equals null</li>
820 * <li>if <code>augSchema</code> equals null</li>
822 * @throws IllegalStateException
823 * if augment target path is null
825 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
826 final Module module) {
827 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
828 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
829 checkState(augSchema.getTargetPath() != null,
830 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
832 processUsesAugments(augSchema, module);
833 final SchemaPath targetPath = augSchema.getTargetPath();
834 SchemaNode targetSchemaNode = null;
836 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
837 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
838 if (targetSchemaNode instanceof DerivableSchemaNode) {
839 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
841 if (targetSchemaNode == null) {
842 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
843 + " in module " + module.getName());
846 if (targetSchemaNode == null) {
847 throw new IllegalArgumentException("augment target not found: " + targetPath);
850 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
851 if (targetTypeBuilder == null) {
852 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
854 if (targetTypeBuilder == null) {
855 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
858 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
859 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
860 targetTypeBuilder.getName());
861 addRawAugmentGenTypeDefinition(module, augmentPackageName, augmentPackageName, targetType, augSchema);
864 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
865 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
869 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
870 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
871 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
872 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
873 checkState(augSchema.getTargetPath() != null,
874 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
876 processUsesAugments(augSchema, module);
877 final SchemaPath targetPath = augSchema.getTargetPath();
878 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
879 if (targetSchemaNode == null) {
880 throw new IllegalArgumentException("augment target not found: " + targetPath);
883 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
884 if (targetTypeBuilder == null) {
885 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
887 if (targetTypeBuilder == null) {
888 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
891 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
892 String packageName = augmentPackageName;
893 if (usesNodeParent instanceof SchemaNode) {
894 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
896 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
899 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
900 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
905 * Convenient method to find node added by uses statement.
909 * @param parentUsesNode
910 * parent of uses node
911 * @return node from its original location in grouping
913 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
914 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
916 if (!(targetGrouping instanceof GroupingDefinition)) {
917 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
920 SchemaNode result = targetGrouping;
921 for (final QName node : targetPath.getPathFromRoot()) {
922 if (result instanceof DataNodeContainer) {
923 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
924 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
925 } else if (result instanceof ChoiceSchemaNode) {
926 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
929 if (result == null) {
933 if (result instanceof DerivableSchemaNode) {
934 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
935 Optional<? extends SchemaNode> originalNode = castedResult
937 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
938 result = originalNode.get();
942 if (result instanceof DataSchemaNode) {
943 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
944 if (resultDataSchemaNode.isAddedByUses()) {
945 // The original node is required, but we have only the copy of
946 // the original node.
947 // Maybe this indicates a bug in Yang parser.
948 throw new IllegalStateException(
949 "Failed to generate code for augment in "
952 return resultDataSchemaNode;
955 throw new IllegalStateException(
956 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
962 * Returns a generated type builder for an augmentation.
964 * The name of the type builder is equal to the name of augmented node with
965 * serial number as suffix.
969 * @param augmentPackageName
970 * string with contains the package name to which the augment
972 * @param basePackageName
973 * string with the package name to which the augmented node
975 * @param targetTypeRef
978 * augmentation schema which contains data about the child nodes
979 * and uses of augment
980 * @return generated type builder for augment
982 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
983 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
984 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
985 if (augmentBuilders == null) {
986 augmentBuilders = new HashMap<>();
987 genTypeBuilders.put(augmentPackageName, augmentBuilders);
989 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
992 if (augIdentifier != null) {
993 augTypeName = BindingMapping.getClassName(augIdentifier);
995 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
998 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
1000 augTypeBuilder.addImplementsType(DATA_OBJECT);
1001 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
1002 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
1003 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1005 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
1006 augmentBuilders.put(augTypeName, augTypeBuilder);
1008 if (!augSchema.getChildNodes().isEmpty()) {
1009 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1012 genCtx.get(module).addAugmentType(augTypeBuilder);
1013 return augTypeBuilder;
1018 * @param unknownSchemaNodes
1019 * @return nodeParameter of UnknownSchemaNode
1021 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1022 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1023 final QName nodeType = unknownSchemaNode.getNodeType();
1024 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1025 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1026 return unknownSchemaNode.getNodeParameter();
1033 * Returns first unique name for the augment generated type builder. The
1034 * generated type builder name for augment consists from name of augmented
1035 * node and serial number of its augmentation.
1038 * map of builders which were created in the package to which the
1039 * augmentation belongs
1040 * @param genTypeName
1041 * string with name of augmented node
1042 * @return string with unique name for augmentation builder
1044 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1046 if (builders != null) {
1047 while (builders.containsKey(genTypeName + index)) {
1051 return genTypeName + index;
1055 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1056 * node for which <code>typeBuilder</code> was created.
1058 * The subnodes aren't mapped to the methods if they are part of grouping or
1059 * augment (in this case are already part of them).
1063 * @param basePackageName
1064 * string contains the module package name
1066 * generated type builder which represents any node. The subnodes
1067 * of this node are added to the <code>typeBuilder</code> as
1068 * methods. The subnode can be of type leaf, leaf-list, list,
1069 * container, choice.
1072 * @param schemaNodes
1073 * set of data schema nodes which are the children of the node
1074 * for which <code>typeBuilder</code> was created
1075 * @return generated type builder which is the same builder as input
1076 * parameter. The getter methods (representing child nodes) could be
1079 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1080 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1081 if (schemaNodes != null && parent != null) {
1082 for (final DataSchemaNode schemaNode : schemaNodes) {
1083 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1084 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1092 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1093 * node for which <code>typeBuilder</code> was created.
1097 * @param basePackageName
1098 * string contains the module package name
1099 * @param typeBuilder
1100 * generated type builder which represents any node. The subnodes
1101 * of this node are added to the <code>typeBuilder</code> as
1102 * methods. The subnode can be of type leaf, leaf-list, list,
1103 * container, choice.
1106 * @param schemaNodes
1107 * set of data schema nodes which are the children of the node
1108 * for which <code>typeBuilder</code> was created
1109 * @return generated type builder which is the same object as the input
1110 * parameter <code>typeBuilder</code>. The getter method could be
1113 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1114 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1115 final Iterable<DataSchemaNode> schemaNodes) {
1116 if ((schemaNodes != null) && (typeBuilder != null)) {
1117 for (final DataSchemaNode schemaNode : schemaNodes) {
1118 if (!schemaNode.isAugmenting()) {
1119 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1127 * Adds to <code>typeBuilder</code> a method which is derived from
1128 * <code>schemaNode</code>.
1130 * @param basePackageName
1131 * string with the module package name
1133 * data schema node which is added to <code>typeBuilder</code> as
1135 * @param typeBuilder
1136 * generated type builder to which is <code>schemaNode</code>
1137 * added as a method.
1143 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1144 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1145 if (node != null && typeBuilder != null) {
1146 if (node instanceof LeafSchemaNode) {
1147 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1148 } else if (node instanceof LeafListSchemaNode) {
1149 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1150 } else if (node instanceof ContainerSchemaNode) {
1151 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1152 } else if (node instanceof ListSchemaNode) {
1153 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1154 } else if (node instanceof ChoiceSchemaNode) {
1155 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1157 // TODO: anyxml not yet supported
1158 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1159 typeBuilder.getFullyQualifiedName());
1165 * Converts <code>choiceNode</code> to the list of generated types for
1166 * choice and its cases.
1168 * The package names for choice and for its cases are created as
1169 * concatenation of the module package (<code>basePackageName</code>) and
1170 * names of all parents node.
1174 * @param basePackageName
1175 * string with the module package name
1179 * choice node which is mapped to generated type. Also child
1180 * nodes - cases are mapped to generated types.
1181 * @throws IllegalArgumentException
1183 * <li>if <code>basePackageName</code> is null</li>
1184 * <li>if <code>choiceNode</code> is null</li>
1187 private void choiceToGeneratedType(final Module module, final String basePackageName,
1188 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1189 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1190 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1192 if (!choiceNode.isAddedByUses()) {
1193 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1194 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1195 constructGetter(parent, choiceNode.getQName().getLocalName(),
1196 choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
1197 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1198 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1199 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1200 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1205 * Converts <code>caseNodes</code> set to list of corresponding generated
1208 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1209 * created generated type builder. The package names for the builder is
1210 * created as concatenation of the module package (
1211 * <code>basePackageName</code>) and names of all parents nodes of the
1212 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1213 * between every case builder and <i>choice</i> type
1217 * @param basePackageName
1218 * string with the module package name
1219 * @param refChoiceType
1220 * type which represents superior <i>case</i>
1222 * choice case node which is mapped to generated type
1223 * @return list of generated types for <code>caseNodes</code>.
1224 * @throws IllegalArgumentException
1226 * <li>if <code>basePackageName</code> equals null</li>
1227 * <li>if <code>refChoiceType</code> equals null</li>
1228 * <li>if <code>caseNodes</code> equals null</li>
1231 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1232 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1233 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1234 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1235 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1237 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1238 if (caseNodes == null) {
1242 for (final ChoiceCaseNode caseNode : caseNodes) {
1243 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1244 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1245 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1246 caseTypeBuilder.addImplementsType(refChoiceType);
1247 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1248 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1249 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1250 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1251 if (caseChildNodes != null) {
1252 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1254 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1255 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1257 if (parent instanceof AugmentationSchema) {
1258 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1259 final SchemaPath targetPath = augSchema.getTargetPath();
1260 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1261 if (targetSchemaNode instanceof DataSchemaNode
1262 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1263 if (targetSchemaNode instanceof DerivableSchemaNode) {
1264 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1266 if (targetSchemaNode == null) {
1267 throw new IllegalStateException(
1268 "Failed to find target node from grouping for augmentation " + augSchema
1269 + " in module " + module.getName());
1272 parent = targetSchemaNode;
1275 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1276 choiceNodeParentPath);
1277 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1278 if (childOfType == null) {
1279 childOfType = findGroupingByPath(parent.getPath());
1281 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1283 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1288 processUsesAugments(caseNode, module);
1293 * Generates list of generated types for all the cases of a choice which are
1294 * added to the choice through the augment.
1298 * @param basePackageName
1299 * string contains name of package to which augment belongs. If
1300 * an augmented choice is from an other package (pcg1) than an
1301 * augmenting choice (pcg2) then case's of the augmenting choice
1302 * will belong to pcg2.
1304 * Type which represents target choice
1306 * node which represents target choice
1307 * @param augmentedNodes
1308 * set of choice case nodes for which is checked if are/aren't
1309 * added to choice through augmentation
1310 * @return list of generated types which represents augmented cases of
1311 * choice <code>refChoiceType</code>
1312 * @throws IllegalArgumentException
1314 * <li>if <code>basePackageName</code> is null</li>
1315 * <li>if <code>targetType</code> is null</li>
1316 * <li>if <code>augmentedNodes</code> is null</li>
1319 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1320 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1321 final DataNodeContainer usesNodeParent) {
1322 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1323 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1324 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1326 for (final DataSchemaNode caseNode : augmentedNodes) {
1327 if (caseNode != null) {
1328 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1329 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1330 caseTypeBuilder.addImplementsType(targetType);
1333 final SchemaPath nodeSp = targetNode.getPath();
1334 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1336 GeneratedTypeBuilder childOfType = null;
1337 if (parent instanceof Module) {
1338 childOfType = genCtx.get(parent).getModuleNode();
1339 } else if (parent instanceof ChoiceCaseNode) {
1340 childOfType = findCaseByPath(parent.getPath());
1341 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1342 childOfType = findChildNodeByPath(parent.getPath());
1343 } else if (parent instanceof GroupingDefinition) {
1344 childOfType = findGroupingByPath(parent.getPath());
1347 if (childOfType == null) {
1348 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1351 ChoiceCaseNode node = null;
1352 final String caseLocalName = caseNode.getQName().getLocalName();
1353 if (caseNode instanceof ChoiceCaseNode) {
1354 node = (ChoiceCaseNode) caseNode;
1355 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
1356 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1357 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1358 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1359 ().getLocalName())) {
1360 node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
1365 node = targetNode.getCaseNodeByName(caseLocalName);
1367 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1368 if (childNodes != null) {
1369 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1371 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1372 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1377 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1378 // New parser with encapsulated type
1379 if (leaf.getPath().equals(type.getPath())) {
1383 // Embedded type definition with new parser. Also takes care of the old parser with bits
1384 if (leaf.getPath().equals(type.getPath().getParent())) {
1392 * Converts <code>leaf</code> to the getter method which is added to
1393 * <code>typeBuilder</code>.
1395 * @param typeBuilder
1396 * generated type builder to which is added getter method as
1397 * <code>leaf</code> mapping
1399 * leaf schema node which is mapped as getter method which is
1400 * added to <code>typeBuilder</code>
1402 * Module in which type was defined
1403 * @return boolean value
1405 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1407 * <li>true - in other cases</li>
1410 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1411 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1415 final String leafName = leaf.getQName().getLocalName();
1416 if (leafName == null) {
1420 final Module parentModule = findParentModule(schemaContext, leaf);
1421 Type returnType = null;
1423 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1424 if (isInnerType(leaf, typeDef)) {
1425 if (typeDef instanceof EnumTypeDefinition) {
1426 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1427 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1428 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1429 typeBuilder, module);
1430 if (enumBuilder != null) {
1431 returnType = enumBuilder.toInstance(typeBuilder);
1433 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1434 } else if (typeDef instanceof UnionTypeDefinition) {
1435 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1436 if (genTOBuilder != null) {
1437 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1438 // Store the inner type within the union so that we can find the reference for it
1439 genCtx.get(module).addInnerTypedefType(typeDef.getPath(), returnType);
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 if (typeDef instanceof EnumTypeDefinition) {
1465 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1468 String leafDesc = leaf.getDescription();
1469 if (leafDesc == null) {
1473 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType, leaf.getStatus());
1474 processContextRefExtension(leaf, getter, parentModule);
1478 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
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) {
1548 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1549 if (typeDef instanceof UnionTypeDefinition) {
1550 // GeneratedType for this type definition should have be already created
1551 final QName qname = typeDef.getQName();
1552 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1553 qname.getRevision());
1554 final ModuleContext mc = genCtx.get(unionModule);
1555 returnType = mc.getTypedefs().get(typeDef.getPath());
1556 if (returnType == null) {
1557 // This may still be an inner type, try to find it
1558 returnType = mc.getInnerType(typeDef.getPath());
1560 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1561 // Annonymous enumeration (already generated, since it is inherited via uses).
1562 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1563 QName qname = originalLeaf.getQName();
1564 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1565 qname.getRevision());
1566 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1568 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1570 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1576 * Converts <code>leaf</code> schema node to property of generated TO
1580 * generated TO builder to which is <code>leaf</code> added as
1583 * leaf schema node which is added to <code>toBuilder</code> as
1588 * boolean value which says if leaf property is|isn't read only
1589 * @return boolean value
1591 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1592 * name equals null or if leaf is added by <i>uses</i>.</li>
1593 * <li>true - other cases</li>
1596 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1597 final Type returnType, final boolean isReadOnly) {
1598 if (returnType == null) {
1601 final String leafName = leaf.getQName().getLocalName();
1602 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
1603 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1604 propBuilder.setReadOnly(isReadOnly);
1605 propBuilder.setReturnType(returnType);
1606 propBuilder.setComment(leafDesc);
1607 toBuilder.addEqualsIdentity(propBuilder);
1608 toBuilder.addHashIdentity(propBuilder);
1609 toBuilder.addToStringProperty(propBuilder);
1614 * Converts <code>node</code> leaf list schema node to getter method of
1615 * <code>typeBuilder</code>.
1617 * @param typeBuilder
1618 * generated type builder to which is <code>node</code> added as
1621 * leaf list schema node which is added to
1622 * <code>typeBuilder</code> as getter method
1623 * @param module module
1624 * @return boolean value
1626 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1627 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1628 * <li>false - other cases</li>
1631 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1632 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1636 final QName nodeName = node.getQName();
1638 final TypeDefinition<?> typeDef = node.getType();
1639 final Module parentModule = findParentModule(schemaContext, node);
1641 Type returnType = null;
1642 if (typeDef.getBaseType() == null) {
1643 if (typeDef instanceof EnumTypeDefinition) {
1644 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1645 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1646 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1647 typeBuilder,module);
1648 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1649 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1650 } else if (typeDef instanceof UnionTypeDefinition) {
1651 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1652 if (genTOBuilder != null) {
1653 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1655 } else if (typeDef instanceof BitsTypeDefinition) {
1656 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1657 returnType = genTOBuilder.toInstance();
1659 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1660 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1663 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1664 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1667 final ParameterizedType listType = Types.listTypeFor(returnType);
1668 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
1672 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1673 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1674 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1675 genTOBuilder.getName());
1676 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1678 returnType.setDescription(typedefDescription);
1679 returnType.setReference(typeDef.getReference());
1680 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1681 returnType.setModuleName(parentModule.getName());
1683 genTOBuilder.setTypedef(true);
1684 genTOBuilder.setIsUnion(true);
1685 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1689 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1692 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1693 method.setReturnType(returnType);
1694 method.addParameter(Types.STRING, "defaultValue");
1695 method.setAccessModifier(AccessModifier.PUBLIC);
1696 method.setStatic(true);
1698 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1699 if (types == null) {
1700 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1701 Sets.newHashSet(unionBuilder.toInstance()));
1703 types.add(unionBuilder.toInstance());
1705 return returnType.toInstance();
1708 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1709 final String outerCls = Types.getOuterClassName(genTOBuilder);
1710 final StringBuilder name;
1711 if (outerCls != null) {
1712 name = new StringBuilder(outerCls);
1714 name = new StringBuilder();
1716 name.append(genTOBuilder.getName());
1717 name.append("Builder");
1718 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1719 unionBuilder.setIsUnionBuilder(true);
1720 return unionBuilder;
1723 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1724 final Module module) {
1725 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1729 * Instantiates generated type builder with <code>packageName</code> and
1730 * <code>schemaNode</code>.
1732 * The new builder always implements
1733 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1734 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1735 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1737 * If <code>schemaNode</code> is instance of
1738 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1739 * DataNodeContainer} it can also implement nodes which are specified in
1742 * @param packageName
1743 * string with the name of the package to which
1744 * <code>schemaNode</code> belongs.
1746 * schema node for which is created generated type builder
1748 * parent type (can be null)
1749 * @return generated type builder <code>schemaNode</code>
1751 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1752 final Type parent, final Module module) {
1753 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1754 if (parent == null) {
1755 it.addImplementsType(DATA_OBJECT);
1757 it.addImplementsType(BindingTypes.childOf(parent));
1759 if (!(schemaNode instanceof GroupingDefinition)) {
1760 it.addImplementsType(augmentable(it));
1763 if (schemaNode instanceof DataNodeContainer) {
1764 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1765 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1772 * Wraps the calling of the same overloaded method.
1774 * @param packageName
1775 * string with the package name to which returning generated type
1778 * schema node which provide data about the schema node name
1779 * @return generated type builder for <code>schemaNode</code>
1781 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1782 return addRawInterfaceDefinition(packageName, schemaNode, "");
1786 * Returns reference to generated type builder for specified
1787 * <code>schemaNode</code> with <code>packageName</code>.
1789 * Firstly the generated type builder is searched in
1790 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1791 * found it is created and added to <code>genTypeBuilders</code>.
1793 * @param packageName
1794 * string with the package name to which returning generated type
1797 * schema node which provide data about the schema node name
1799 * return type name prefix
1800 * @return generated type builder for <code>schemaNode</code>
1801 * @throws IllegalArgumentException
1803 * <li>if <code>schemaNode</code> is null</li>
1804 * <li>if <code>packageName</code> is null</li>
1805 * <li>if QName of schema node is null</li>
1806 * <li>if schemaNode name is null</li>
1810 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1811 final String prefix) {
1812 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1813 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1814 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1815 final String schemaNodeName = schemaNode.getQName().getLocalName();
1816 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1819 if (prefix == null) {
1820 genTypeName = BindingMapping.getClassName(schemaNodeName);
1822 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1825 // FIXME: Validation of name conflict
1826 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1827 final Module module = findParentModule(schemaContext, schemaNode);
1828 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1829 newType.addComment(schemaNode.getDescription());
1830 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1831 newType.setReference(schemaNode.getReference());
1832 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1833 newType.setModuleName(module.getName());
1835 if (!genTypeBuilders.containsKey(packageName)) {
1836 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1837 builders.put(genTypeName, newType);
1838 genTypeBuilders.put(packageName, builders);
1840 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1841 if (!builders.containsKey(genTypeName)) {
1842 builders.put(genTypeName, newType);
1849 * Creates the name of the getter method name from <code>localName</code>.
1852 * string with the name of the getter method
1855 * @return string with the name of the getter method for
1856 * <code>methodName</code> in JAVA method format
1858 public static String getterMethodName(final String localName, final Type returnType) {
1859 final StringBuilder method = new StringBuilder();
1860 if (BOOLEAN.equals(returnType)) {
1861 method.append("is");
1863 method.append("get");
1865 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1866 method.append(name);
1867 return method.toString();
1871 * Created a method signature builder as part of
1872 * <code>interfaceBuilder</code>.
1874 * The method signature builder is created for the getter method of
1875 * <code>schemaNodeName</code>. Also <code>comment</code> and
1876 * <code>returnType</code> information are added to the builder.
1878 * @param interfaceBuilder
1879 * generated type builder for which the getter method should be
1881 * @param schemaNodeName
1882 * string with schema node name. The name will be the part of the
1883 * getter method name.
1885 * string with comment for the getter method
1887 * type which represents the return type of the getter method
1889 * status from yang file, for deprecated annotation
1890 * @return method signature builder which represents the getter method of
1891 * <code>interfaceBuilder</code>
1893 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1894 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1895 final MethodSignatureBuilder getMethod = interfaceBuilder
1896 .addMethod(getterMethodName(schemaNodeName, returnType));
1897 if (status == Status.DEPRECATED) {
1898 getMethod.addAnnotation("", "Deprecated");
1900 getMethod.setComment(encodeAngleBrackets(comment));
1901 getMethod.setReturnType(returnType);
1906 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1907 * or to <code>genTOBuilder</code> as property.
1909 * @param basePackageName
1910 * string contains the module package name
1912 * data schema node which should be added as getter method to
1913 * <code>typeBuilder</code> or as a property to
1914 * <code>genTOBuilder</code> if is part of the list key
1915 * @param typeBuilder
1916 * generated type builder for the list schema node
1917 * @param genTOBuilder
1918 * generated TO builder for the list keys
1920 * list of string which contains names of the list keys
1923 * @throws IllegalArgumentException
1925 * <li>if <code>schemaNode</code> equals null</li>
1926 * <li>if <code>typeBuilder</code> equals null</li>
1929 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1930 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1931 final Module module) {
1932 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1933 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1935 if (schemaNode instanceof LeafSchemaNode) {
1936 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1937 final String leafName = leaf.getQName().getLocalName();
1938 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, module);
1939 if (listKeys.contains(leafName)) {
1941 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1943 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1946 } else if (!schemaNode.isAddedByUses()) {
1947 if (schemaNode instanceof LeafListSchemaNode) {
1948 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1949 } else if (schemaNode instanceof ContainerSchemaNode) {
1950 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1951 } else if (schemaNode instanceof ChoiceSchemaNode) {
1952 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1953 } else if (schemaNode instanceof ListSchemaNode) {
1954 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1959 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1960 final GeneratedTOBuilder genTOBuilder) {
1961 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1963 if (genTOBuilder != null) {
1964 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1965 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1966 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1971 * Selects the names of the list keys from <code>list</code> and returns
1972 * them as the list of the strings
1975 * of string with names of the list keys
1976 * @return list of string which represents names of the list keys. If the
1977 * <code>list</code> contains no keys then the empty list is
1980 private static List<String> listKeys(final ListSchemaNode list) {
1981 final List<String> listKeys = new ArrayList<>();
1983 final List<QName> keyDefinition = list.getKeyDefinition();
1984 if (keyDefinition != null) {
1985 for (final QName keyDef : keyDefinition) {
1986 listKeys.add(keyDef.getLocalName());
1993 * Generates for the <code>list</code> which contains any list keys special
1994 * generated TO builder.
1996 * @param packageName
1997 * string with package name to which the list belongs
1999 * list schema node which is source of data about the list name
2000 * @return generated TO builder which represents the keys of the
2001 * <code>list</code> or null if <code>list</code> is null or list of
2002 * key definitions is null or empty.
2004 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
2005 GeneratedTOBuilder genTOBuilder = null;
2006 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
2007 final String listName = list.getQName().getLocalName() + "Key";
2008 final String genTOName = BindingMapping.getClassName(listName);
2009 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
2011 return genTOBuilder;
2015 * Builds generated TO builders for <code>typeDef</code> of type
2016 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
2017 * also added to <code>typeBuilder</code> as enclosing transfer object.
2019 * If more then one generated TO builder is created for enclosing then all
2020 * of the generated TO builders are added to <code>typeBuilder</code> as
2021 * enclosing transfer objects.
2024 * type definition which can be of type <code>UnionType</code> or
2025 * <code>BitsTypeDefinition</code>
2026 * @param typeBuilder
2027 * generated type builder to which is added generated TO created
2028 * from <code>typeDef</code>
2030 * string with name for generated TO builder
2031 * @param parentModule
2033 * @return generated TO builder for <code>typeDef</code>
2035 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2036 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2037 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2038 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2039 final String packageName = typeBuilder.getFullyQualifiedName();
2040 if (typeDef instanceof UnionTypeDefinition) {
2041 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2042 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
2043 classNameFromLeaf, leaf);
2044 genTOBuilders.addAll(types);
2046 GeneratedTOBuilder resultTOBuilder;
2047 if (types.isEmpty()) {
2048 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2050 resultTOBuilder = types.remove(0);
2051 for (final GeneratedTOBuilder genTOBuilder : types) {
2052 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2055 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2056 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2057 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2058 resultTOBuilder.addHashIdentity(genPropBuilder);
2059 resultTOBuilder.addToStringProperty(genPropBuilder);
2061 } else if (typeDef instanceof BitsTypeDefinition) {
2062 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
2063 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2065 if (!genTOBuilders.isEmpty()) {
2066 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2067 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2069 return genTOBuilders.get(0);
2076 * Adds the implemented types to type builder.
2078 * The method passes through the list of <i>uses</i> in
2079 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2080 * generated type from {@link ModuleContext#groupings
2081 * allGroupings} which is added as <i>implements type</i> to
2082 * <code>builder</code>
2084 * @param dataNodeContainer
2085 * element which contains the list of used YANG groupings
2087 * builder to which are added implemented types according to
2088 * <code>dataNodeContainer</code>
2089 * @return generated type builder with all implemented types
2091 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2092 final GeneratedTypeBuilder builder) {
2093 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2094 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2095 if (genType == null) {
2096 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2097 + builder.getName());
2100 builder.addImplementsType(genType);
2105 private static boolean isNullOrEmpty(final Collection<?> list) {
2106 return list == null || list.isEmpty();
2109 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2110 final StringBuilder sb = new StringBuilder();
2112 if (!isNullOrEmpty(schemaNodes)) {
2113 final SchemaNode node = schemaNodes.iterator().next();
2115 if (node instanceof RpcDefinition) {
2116 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2117 } else if (node instanceof NotificationDefinition) {
2118 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2121 sb.append(NEW_LINE);
2123 if (verboseClassComments) {
2125 sb.append(NEW_LINE);
2126 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2127 sb.append("</pre>");
2128 sb.append(NEW_LINE);
2131 return replaceAllIllegalChars(sb);
2134 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2135 final StringBuilder sb = new StringBuilder();
2136 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
2137 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2139 if (!Strings.isNullOrEmpty(formattedDescription)) {
2140 sb.append(formattedDescription);
2141 sb.append(NEW_LINE);
2144 if (verboseClassComments) {
2145 final Module module = findParentModule(schemaContext, schemaNode);
2146 final StringBuilder linkToBuilderClass = new StringBuilder();
2147 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2148 final String className = namespace[namespace.length - 1];
2150 if (hasBuilderClass(schemaNode)) {
2151 linkToBuilderClass.append(className);
2152 linkToBuilderClass.append("Builder");
2156 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2157 sb.append(module.getName());
2159 sb.append(NEW_LINE);
2161 sb.append(NEW_LINE);
2162 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2163 sb.append("</pre>");
2164 sb.append(NEW_LINE);
2165 sb.append("The schema path to identify an instance is");
2166 sb.append(NEW_LINE);
2168 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2170 sb.append(NEW_LINE);
2172 if (hasBuilderClass(schemaNode)) {
2173 sb.append(NEW_LINE);
2174 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2175 sb.append(NEW_LINE);
2177 sb.append(linkToBuilderClass);
2178 sb.append(NEW_LINE);
2179 if (schemaNode instanceof ListSchemaNode) {
2180 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2181 if (keyDef != null && !keyDef.isEmpty()) {
2183 sb.append(className);
2186 sb.append(NEW_LINE);
2191 return replaceAllIllegalChars(sb);
2194 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2195 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2196 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2202 private String createDescription(final Module module) {
2203 final StringBuilder sb = new StringBuilder();
2204 final String moduleDescription = encodeAngleBrackets(module.getDescription());
2205 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2207 if (!Strings.isNullOrEmpty(formattedDescription)) {
2208 sb.append(formattedDescription);
2209 sb.append(NEW_LINE);
2212 if (verboseClassComments) {
2214 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2215 sb.append(module.getName());
2217 sb.append(NEW_LINE);
2219 sb.append(NEW_LINE);
2220 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2221 sb.append("</pre>");
2224 return replaceAllIllegalChars(sb);
2227 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2228 for (final ModuleContext ctx : genCtx.values()) {
2229 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2230 if (result != null) {
2237 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2238 for (final ModuleContext ctx : genCtx.values()) {
2239 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2240 if (result != null) {
2247 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2248 for (final ModuleContext ctx : genCtx.values()) {
2249 final GeneratedTypeBuilder result = ctx.getCase(path);
2250 if (result != null) {
2257 public Map<Module, ModuleContext> getModuleContexts() {
2262 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2263 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2264 return ret.isEmpty() ? "" : ret;
2267 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2268 if (status == Status.DEPRECATED) {
2269 builder.addAnnotation("", "Deprecated");