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 «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 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 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
519 addImplementedInterfaceFromUses(input, inType);
520 inType.addImplementsType(DATA_OBJECT);
521 inType.addImplementsType(augmentable(inType));
522 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
523 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
524 genCtx.get(module).addChildNodeType(input, inType);
525 final GeneratedType inTypeInstance = inType.toInstance();
526 method.addParameter(inTypeInstance, "input");
529 Type outTypeInstance = VOID;
530 //in case of implicit RPC output (StatementSource.CONTEXT),
531 //stay compatible (Future<RpcResult<Void>> return type generated)
532 if (output != null && isExplicitStatement(output)) {
533 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
534 addImplementedInterfaceFromUses(output, outType);
535 outType.addImplementsType(DATA_OBJECT);
536 outType.addImplementsType(augmentable(outType));
537 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
538 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
539 genCtx.get(module).addChildNodeType(output, outType);
540 outTypeInstance = outType.toInstance();
543 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
544 method.setComment(rpcComment);
545 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
549 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
552 private static boolean isExplicitStatement(final ContainerSchemaNode node) {
553 return node instanceof EffectiveStatement
554 && ((EffectiveStatement<?, ?>) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
558 * Converts all <b>notifications</b> of the module to the list of
559 * <code>Type</code> objects. In addition are to this list added containers
560 * and lists which are part of this notification.
563 * module from which is obtained set of all notification objects
564 * to iterate over them
565 * @throws IllegalArgumentException
567 * <li>if the module equals null</li>
568 * <li>if the name of module equals null</li>
570 * @throws IllegalStateException
571 * if set of notifications from module is null
573 private void notificationsToGenType(final Module module) {
574 checkArgument(module != null, "Module reference cannot be NULL.");
575 checkArgument(module.getName() != null, "Module name cannot be NULL.");
576 final Set<NotificationDefinition> notifications = module.getNotifications();
577 if (notifications.isEmpty()) {
581 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
582 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
583 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
587 for (final NotificationDefinition notification : notifications) {
588 if (notification != null) {
589 processUsesAugments(notification, module);
591 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
592 notification, null, module);
593 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
594 notificationInterface.addImplementsType(NOTIFICATION);
595 genCtx.get(module).addChildNodeType(notification, notificationInterface);
597 // Notification object
598 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
599 notification.getChildNodes());
601 listenerInterface.addMethod("on" + notificationInterface.getName())
602 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
603 .setComment(encodeAngleBrackets(notification.getDescription())).setReturnType(Types.VOID);
606 listenerInterface.setDescription(createDescription(notifications, module.getName()));
608 genCtx.get(module).addTopLevelNodeType(listenerInterface);
612 * Converts all <b>identities</b> of the module to the list of
613 * <code>Type</code> objects.
616 * module from which is obtained set of all identity objects to
619 * schema context only used as input parameter for method
620 * {@link BindingGeneratorImpl#identityToGenType}
623 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
624 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
625 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
627 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
628 for (final IdentitySchemaNode identity : schemaIdentities) {
629 identityToGenType(module, basePackageName, identity, context);
635 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
636 * created transport object builder. If identity contains base identity then
637 * reference to base identity is added to superior identity as its extend.
638 * If identity doesn't contain base identity then only reference to abstract
639 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
640 * BaseIdentity} is added
644 * @param basePackageName
645 * string contains the module package name
647 * IdentitySchemaNode which contains data about identity
649 * SchemaContext which is used to get package and name
650 * information about base of identity
653 private void identityToGenType(final Module module, final String basePackageName,
654 final IdentitySchemaNode identity, final SchemaContext context) {
655 if (identity == null) {
658 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
659 final String genTypeName = BindingMapping.getClassName(identity.getQName());
660 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
661 final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
662 if (baseIdentity == null) {
663 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
664 BaseIdentity.class.getSimpleName());
665 newType.setExtendsType(gto.toInstance());
667 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
668 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
670 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
671 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
673 newType.setExtendsType(gto);
675 newType.setAbstract(true);
676 newType.addComment(identity.getDescription());
677 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
678 newType.setReference(identity.getReference());
679 newType.setModuleName(module.getName());
680 newType.setSchemaPath(identity.getPath().getPathFromRoot());
682 final QName qname = identity.getQName();
683 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
685 genCtx.get(module).addIdentityType(identity.getQName(), newType);
688 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
690 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
694 * Converts all <b>groupings</b> of the module to the list of
695 * <code>Type</code> objects. Firstly are groupings sorted according mutual
696 * dependencies. At least dependent (independent) groupings are in the list
697 * saved at first positions. For every grouping the record is added to map
698 * {@link ModuleContext#groupings allGroupings}
703 * collection of groupings from which types will be generated
706 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
707 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
708 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
710 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
711 groupingToGenType(basePackageName, grouping, module);
716 * Converts individual grouping to GeneratedType. Firstly generated type
717 * builder is created and every child node of grouping is resolved to the
720 * @param basePackageName
721 * string contains the module package name
723 * GroupingDefinition which contains data about grouping
727 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
728 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
729 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
730 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
731 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
732 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
733 groupingsToGenTypes(module, grouping.getGroupings());
734 processUsesAugments(grouping, module);
738 * Adds enumeration builder created from <code>enumTypeDef</code> to
739 * <code>typeBuilder</code>.
741 * Each <code>enumTypeDef</code> item is added to builder with its name and
745 * EnumTypeDefinition contains enum data
747 * string contains name which will be assigned to enumeration
750 * GeneratedTypeBuilder to which will be enum builder assigned
752 * Module in which type should be generated
753 * @return enumeration builder which contains data from
754 * <code>enumTypeDef</code>
756 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
757 final GeneratedTypeBuilder typeBuilder, final Module module) {
758 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
759 final String enumerationName = BindingMapping.getClassName(enumName);
760 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
761 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
762 enumBuilder.setDescription(enumTypedefDescription);
763 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
764 ModuleContext ctx = genCtx.get(module);
765 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
772 * Generates type builder for <code>module</code>.
775 * Module which is source of package name for generated type
778 * string which is added to the module class name representation
780 * @return instance of GeneratedTypeBuilder which represents
781 * <code>module</code>.
782 * @throws IllegalArgumentException
783 * if <code>module</code> is null
785 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
786 checkArgument(module != null, "Module reference cannot be NULL.");
787 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
788 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
790 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
791 moduleBuilder.setDescription(createDescription(module));
792 moduleBuilder.setReference(module.getReference());
793 moduleBuilder.setModuleName(moduleName);
795 return moduleBuilder;
799 * Converts <code>augSchema</code> to list of <code>Type</code> which
800 * contains generated type for augmentation. In addition there are also
801 * generated types for all containers, list and choices which are child of
802 * <code>augSchema</code> node or a generated types for cases are added if
803 * augmented node is choice.
805 * @param augmentPackageName
806 * string with the name of the package to which the augmentation
809 * AugmentationSchema which is contains data about augmentation
810 * (target path, childs...)
813 * @throws IllegalArgumentException
815 * <li>if <code>augmentPackageName</code> equals null</li>
816 * <li>if <code>augSchema</code> equals null</li>
818 * @throws IllegalStateException
819 * if augment target path is null
821 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
822 final Module module) {
823 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
824 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
825 checkState(augSchema.getTargetPath() != null,
826 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
828 processUsesAugments(augSchema, module);
829 final SchemaPath targetPath = augSchema.getTargetPath();
830 SchemaNode targetSchemaNode = null;
832 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
833 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
834 if (targetSchemaNode instanceof DerivableSchemaNode) {
835 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
837 if (targetSchemaNode == null) {
838 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
839 + " in module " + module.getName());
842 if (targetSchemaNode == null) {
843 throw new IllegalArgumentException("augment target not found: " + targetPath);
846 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
847 if (targetTypeBuilder == null) {
848 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
850 if (targetTypeBuilder == null) {
851 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
854 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
855 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
856 targetTypeBuilder.getName());
857 addRawAugmentGenTypeDefinition(module, augmentPackageName, augmentPackageName, targetType, augSchema);
860 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
861 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
865 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
866 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
867 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
868 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
869 checkState(augSchema.getTargetPath() != null,
870 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
872 processUsesAugments(augSchema, module);
873 final SchemaPath targetPath = augSchema.getTargetPath();
874 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
875 if (targetSchemaNode == null) {
876 throw new IllegalArgumentException("augment target not found: " + targetPath);
879 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
880 if (targetTypeBuilder == null) {
881 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
883 if (targetTypeBuilder == null) {
884 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
887 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
888 String packageName = augmentPackageName;
889 if (usesNodeParent instanceof SchemaNode) {
890 packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
892 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
895 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
896 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
901 * Convenient method to find node added by uses statement.
905 * @param parentUsesNode
906 * parent of uses node
907 * @return node from its original location in grouping
909 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
910 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
912 if (!(targetGrouping instanceof GroupingDefinition)) {
913 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
916 SchemaNode result = targetGrouping;
917 for (final QName node : targetPath.getPathFromRoot()) {
918 if (result instanceof DataNodeContainer) {
919 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
920 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
921 } else if (result instanceof ChoiceSchemaNode) {
922 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
925 if (result == null) {
929 if (result instanceof DerivableSchemaNode) {
930 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
931 Optional<? extends SchemaNode> originalNode = castedResult
933 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
934 result = originalNode.get();
938 if (result instanceof DataSchemaNode) {
939 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
940 if (resultDataSchemaNode.isAddedByUses()) {
941 // The original node is required, but we have only the copy of
942 // the original node.
943 // Maybe this indicates a bug in Yang parser.
944 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
947 return resultDataSchemaNode;
950 throw new IllegalStateException(
951 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
956 * Returns a generated type builder for an augmentation.
958 * The name of the type builder is equal to the name of augmented node with
959 * serial number as suffix.
963 * @param augmentPackageName
964 * string with contains the package name to which the augment
966 * @param basePackageName
967 * string with the package name to which the augmented node
969 * @param targetTypeRef
972 * augmentation schema which contains data about the child nodes
973 * and uses of augment
974 * @return generated type builder for augment
976 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
977 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
978 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
979 if (augmentBuilders == null) {
980 augmentBuilders = new HashMap<>();
981 genTypeBuilders.put(augmentPackageName, augmentBuilders);
983 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
986 if (augIdentifier != null) {
987 augTypeName = BindingMapping.getClassName(augIdentifier);
989 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
992 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
994 augTypeBuilder.addImplementsType(DATA_OBJECT);
995 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
996 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
997 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
999 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
1000 augmentBuilders.put(augTypeName, augTypeBuilder);
1002 if (!augSchema.getChildNodes().isEmpty()) {
1003 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1006 genCtx.get(module).addAugmentType(augTypeBuilder);
1007 return augTypeBuilder;
1012 * @param unknownSchemaNodes
1013 * @return nodeParameter of UnknownSchemaNode
1015 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1016 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1017 final QName nodeType = unknownSchemaNode.getNodeType();
1018 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1019 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1020 return unknownSchemaNode.getNodeParameter();
1027 * Returns first unique name for the augment generated type builder. The
1028 * generated type builder name for augment consists from name of augmented
1029 * node and serial number of its augmentation.
1032 * map of builders which were created in the package to which the
1033 * augmentation belongs
1034 * @param genTypeName
1035 * string with name of augmented node
1036 * @return string with unique name for augmentation builder
1038 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1040 if (builders != null) {
1041 while (builders.containsKey(genTypeName + index)) {
1045 return genTypeName + index;
1049 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1050 * node for which <code>typeBuilder</code> was created.
1052 * The subnodes aren't mapped to the methods if they are part of grouping or
1053 * augment (in this case are already part of them).
1057 * @param basePackageName
1058 * string contains the module package name
1060 * generated type builder which represents any node. The subnodes
1061 * of this node are added to the <code>typeBuilder</code> as
1062 * methods. The subnode can be of type leaf, leaf-list, list,
1063 * container, choice.
1066 * @param schemaNodes
1067 * set of data schema nodes which are the children of the node
1068 * for which <code>typeBuilder</code> was created
1069 * @return generated type builder which is the same builder as input
1070 * parameter. The getter methods (representing child nodes) could be
1073 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1074 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1075 if (schemaNodes != null && parent != null) {
1076 for (final DataSchemaNode schemaNode : schemaNodes) {
1077 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1078 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1086 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1087 * node for which <code>typeBuilder</code> was created.
1091 * @param basePackageName
1092 * string contains the module package name
1093 * @param typeBuilder
1094 * generated type builder which represents any node. The subnodes
1095 * of this node are added to the <code>typeBuilder</code> as
1096 * methods. The subnode can be of type leaf, leaf-list, list,
1097 * container, choice.
1100 * @param schemaNodes
1101 * set of data schema nodes which are the children of the node
1102 * for which <code>typeBuilder</code> was created
1103 * @return generated type builder which is the same object as the input
1104 * parameter <code>typeBuilder</code>. The getter method could be
1107 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1108 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1109 final Iterable<DataSchemaNode> schemaNodes) {
1110 if (schemaNodes != null && typeBuilder != null) {
1111 for (final DataSchemaNode schemaNode : schemaNodes) {
1112 if (!schemaNode.isAugmenting()) {
1113 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1121 * Adds to <code>typeBuilder</code> a method which is derived from
1122 * <code>schemaNode</code>.
1124 * @param basePackageName
1125 * string with the module package name
1127 * data schema node which is added to <code>typeBuilder</code> as
1129 * @param typeBuilder
1130 * generated type builder to which is <code>schemaNode</code>
1131 * added as a method.
1137 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1138 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1139 if (node != null && typeBuilder != null) {
1140 if (node instanceof LeafSchemaNode) {
1141 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1142 } else if (node instanceof LeafListSchemaNode) {
1143 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1144 } else if (node instanceof ContainerSchemaNode) {
1145 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1146 } else if (node instanceof ListSchemaNode) {
1147 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1148 } else if (node instanceof ChoiceSchemaNode) {
1149 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1151 // TODO: anyxml not yet supported
1152 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1153 typeBuilder.getFullyQualifiedName());
1159 * Converts <code>choiceNode</code> to the list of generated types for
1160 * choice and its cases.
1162 * The package names for choice and for its cases are created as
1163 * concatenation of the module package (<code>basePackageName</code>) and
1164 * names of all parents node.
1168 * @param basePackageName
1169 * string with the module package name
1173 * choice node which is mapped to generated type. Also child
1174 * nodes - cases are mapped to generated types.
1175 * @throws IllegalArgumentException
1177 * <li>if <code>basePackageName</code> is null</li>
1178 * <li>if <code>choiceNode</code> is null</li>
1181 private void choiceToGeneratedType(final Module module, final String basePackageName,
1182 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1183 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1184 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1186 if (!choiceNode.isAddedByUses()) {
1187 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1188 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1189 constructGetter(parent, choiceNode.getQName().getLocalName(),
1190 choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
1191 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1192 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1193 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1194 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1199 * Converts <code>caseNodes</code> set to list of corresponding generated
1202 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1203 * created generated type builder. The package names for the builder is
1204 * created as concatenation of the module package (
1205 * <code>basePackageName</code>) and names of all parents nodes of the
1206 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1207 * between every case builder and <i>choice</i> type
1211 * @param basePackageName
1212 * string with the module package name
1213 * @param refChoiceType
1214 * type which represents superior <i>case</i>
1216 * choice case node which is mapped to generated type
1217 * @throws IllegalArgumentException
1219 * <li>if <code>basePackageName</code> equals null</li>
1220 * <li>if <code>refChoiceType</code> equals null</li>
1221 * <li>if <code>caseNodes</code> equals null</li>
1224 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1225 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1226 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1227 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1228 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1230 final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1231 if (caseNodes == null) {
1235 for (final ChoiceCaseNode caseNode : caseNodes) {
1236 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1237 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1238 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1239 caseTypeBuilder.addImplementsType(refChoiceType);
1240 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1241 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1242 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1243 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1244 if (caseChildNodes != null) {
1245 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1247 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1248 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1250 if (parent instanceof AugmentationSchema) {
1251 final AugmentationSchema augSchema = (AugmentationSchema) parent;
1252 final SchemaPath targetPath = augSchema.getTargetPath();
1253 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1254 if (targetSchemaNode instanceof DataSchemaNode
1255 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1256 if (targetSchemaNode instanceof DerivableSchemaNode) {
1257 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1259 if (targetSchemaNode == null) {
1260 throw new IllegalStateException(
1261 "Failed to find target node from grouping for augmentation " + augSchema
1262 + " in module " + module.getName());
1265 parent = targetSchemaNode;
1268 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1269 choiceNodeParentPath);
1270 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1271 if (childOfType == null) {
1272 childOfType = findGroupingByPath(parent.getPath());
1274 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1276 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1281 processUsesAugments(caseNode, module);
1286 * Generates list of generated types for all the cases of a choice which are
1287 * added to the choice through the augment.
1291 * @param basePackageName
1292 * string contains name of package to which augment belongs. If
1293 * an augmented choice is from an other package (pcg1) than an
1294 * augmenting choice (pcg2) then case's of the augmenting choice
1295 * will belong to pcg2.
1297 * Type which represents target choice
1299 * node which represents target choice
1300 * @param augmentedNodes
1301 * set of choice case nodes for which is checked if are/aren't
1302 * added to choice through augmentation
1303 * @throws IllegalArgumentException
1305 * <li>if <code>basePackageName</code> is null</li>
1306 * <li>if <code>targetType</code> is null</li>
1307 * <li>if <code>augmentedNodes</code> is null</li>
1310 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1311 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1312 final DataNodeContainer usesNodeParent) {
1313 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1314 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1315 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1317 for (final DataSchemaNode caseNode : augmentedNodes) {
1318 if (caseNode != null) {
1319 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1320 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1321 caseTypeBuilder.addImplementsType(targetType);
1324 final SchemaPath nodeSp = targetNode.getPath();
1325 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1327 GeneratedTypeBuilder childOfType = null;
1328 if (parent instanceof Module) {
1329 childOfType = genCtx.get(parent).getModuleNode();
1330 } else if (parent instanceof ChoiceCaseNode) {
1331 childOfType = findCaseByPath(parent.getPath());
1332 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1333 childOfType = findChildNodeByPath(parent.getPath());
1334 } else if (parent instanceof GroupingDefinition) {
1335 childOfType = findGroupingByPath(parent.getPath());
1338 if (childOfType == null) {
1339 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1342 ChoiceCaseNode node = null;
1343 final String caseLocalName = caseNode.getQName().getLocalName();
1344 if (caseNode instanceof ChoiceCaseNode) {
1345 node = (ChoiceCaseNode) caseNode;
1346 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
1347 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1348 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1349 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1350 ().getLocalName())) {
1351 node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
1356 node = targetNode.getCaseNodeByName(caseLocalName);
1358 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1359 if (childNodes != null) {
1360 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1362 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1363 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1368 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1369 // New parser with encapsulated type
1370 if (leaf.getPath().equals(type.getPath())) {
1374 // Embedded type definition with new parser. Also takes care of the old parser with bits
1375 if (leaf.getPath().equals(type.getPath().getParent())) {
1383 * Converts <code>leaf</code> to the getter method which is added to
1384 * <code>typeBuilder</code>.
1386 * @param typeBuilder
1387 * generated type builder to which is added getter method as
1388 * <code>leaf</code> mapping
1390 * leaf schema node which is mapped as getter method which is
1391 * added to <code>typeBuilder</code>
1393 * Module in which type was defined
1394 * @return boolean value
1396 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1398 * <li>true - in other cases</li>
1401 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1402 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1406 final String leafName = leaf.getQName().getLocalName();
1407 if (leafName == null) {
1411 final Module parentModule = findParentModule(schemaContext, leaf);
1412 Type returnType = null;
1414 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1415 if (isInnerType(leaf, typeDef)) {
1416 if (typeDef instanceof EnumTypeDefinition) {
1417 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1418 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1419 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1420 typeBuilder, module);
1421 if (enumBuilder != null) {
1422 returnType = enumBuilder.toInstance(typeBuilder);
1424 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1425 } else if (typeDef instanceof UnionTypeDefinition) {
1426 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1427 if (genTOBuilder != null) {
1428 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1430 } else if (typeDef instanceof BitsTypeDefinition) {
1431 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1432 if (genTOBuilder != null) {
1433 returnType = genTOBuilder.toInstance();
1436 // It is constrained version of already declared type (inner declared type exists,
1437 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1438 // In order to get proper class we need to look up closest derived type
1439 // and apply restrictions from leaf type
1440 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1441 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1445 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1446 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1449 if (returnType == null) {
1453 if (typeDef instanceof EnumTypeDefinition) {
1454 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1457 String leafDesc = leaf.getDescription();
1458 if (leafDesc == null) {
1462 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType, leaf.getStatus());
1463 processContextRefExtension(leaf, getter, parentModule);
1467 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1468 // Returns DerivedType in case of new parser.
1469 final TypeDefinition<?> baseType = typeDef.getBaseType();
1470 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1473 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1474 final Module module) {
1475 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1476 final QName nodeType = node.getNodeType();
1477 if ("context-reference".equals(nodeType.getLocalName())) {
1478 final String nodeParam = node.getNodeParameter();
1479 IdentitySchemaNode identity = null;
1480 String basePackageName = null;
1481 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1482 final Iterator<String> iterator = splittedElement.iterator();
1483 final int length = Iterables.size(splittedElement);
1485 identity = findIdentityByName(module.getIdentities(), iterator.next());
1486 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1487 } else if (length == 2) {
1488 final String prefix = iterator.next();
1489 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1490 if (dependentModule == null) {
1491 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1494 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1495 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1497 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1500 if (identity == null) {
1501 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1505 final Class<RoutingContext> clazz = RoutingContext.class;
1506 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1507 clazz.getSimpleName());
1508 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1509 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1510 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1515 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1516 for (final IdentitySchemaNode id : identities) {
1517 if (id.getQName().getLocalName().equals(name)) {
1524 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1525 for (final ModuleImport imp : imports) {
1526 if (imp.getPrefix().equals(prefix)) {
1527 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1533 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1534 final boolean isReadOnly, final Module module) {
1535 if (leaf != null && toBuilder != null) {
1537 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1538 if (typeDef instanceof UnionTypeDefinition) {
1539 // GeneratedType for this type definition should be already
1541 final QName qname = typeDef.getQName();
1542 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1543 qname.getRevision());
1544 final ModuleContext mc = genCtx.get(unionModule);
1545 returnType = mc.getTypedefs().get(typeDef.getPath());
1546 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1547 // Annonymous enumeration (already generated, since it is inherited via uses).
1548 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1549 QName qname = originalLeaf.getQName();
1550 final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1551 qname.getRevision());
1552 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1554 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1556 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1562 * Converts <code>leaf</code> schema node to property of generated TO
1566 * generated TO builder to which is <code>leaf</code> added as
1569 * leaf schema node which is added to <code>toBuilder</code> as
1574 * boolean value which says if leaf property is|isn't read only
1575 * @return boolean value
1577 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1578 * name equals null or if leaf is added by <i>uses</i>.</li>
1579 * <li>true - other cases</li>
1582 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1583 final Type returnType, final boolean isReadOnly) {
1584 if (returnType == null) {
1587 final String leafName = leaf.getQName().getLocalName();
1588 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
1589 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1590 propBuilder.setReadOnly(isReadOnly);
1591 propBuilder.setReturnType(returnType);
1592 propBuilder.setComment(leafDesc);
1593 toBuilder.addEqualsIdentity(propBuilder);
1594 toBuilder.addHashIdentity(propBuilder);
1595 toBuilder.addToStringProperty(propBuilder);
1600 * Converts <code>node</code> leaf list schema node to getter method of
1601 * <code>typeBuilder</code>.
1603 * @param typeBuilder
1604 * generated type builder to which is <code>node</code> added as
1607 * leaf list schema node which is added to
1608 * <code>typeBuilder</code> as getter method
1609 * @param module module
1610 * @return boolean value
1612 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1613 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1614 * <li>false - other cases</li>
1617 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1618 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1622 final QName nodeName = node.getQName();
1624 final TypeDefinition<?> typeDef = node.getType();
1625 final Module parentModule = findParentModule(schemaContext, node);
1627 Type returnType = null;
1628 if (typeDef.getBaseType() == null) {
1629 if (typeDef instanceof EnumTypeDefinition) {
1630 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1631 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1632 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1633 typeBuilder,module);
1634 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1635 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1636 } else if (typeDef instanceof UnionTypeDefinition) {
1637 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1638 if (genTOBuilder != null) {
1639 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1641 } else if (typeDef instanceof BitsTypeDefinition) {
1642 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1643 returnType = genTOBuilder.toInstance();
1645 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1646 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1649 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1650 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1653 final ParameterizedType listType = Types.listTypeFor(returnType);
1654 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
1658 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1659 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1660 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1661 genTOBuilder.getName());
1662 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1664 returnType.setDescription(typedefDescription);
1665 returnType.setReference(typeDef.getReference());
1666 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1667 returnType.setModuleName(parentModule.getName());
1669 genTOBuilder.setTypedef(true);
1670 genTOBuilder.setIsUnion(true);
1671 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1675 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1678 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1679 method.setReturnType(returnType);
1680 method.addParameter(Types.STRING, "defaultValue");
1681 method.setAccessModifier(AccessModifier.PUBLIC);
1682 method.setStatic(true);
1684 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1685 if (types == null) {
1686 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1687 Sets.newHashSet(unionBuilder.toInstance()));
1689 types.add(unionBuilder.toInstance());
1691 return returnType.toInstance();
1694 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1695 final String outerCls = Types.getOuterClassName(genTOBuilder);
1696 final StringBuilder name;
1697 if (outerCls != null) {
1698 name = new StringBuilder(outerCls);
1700 name = new StringBuilder();
1702 name.append(genTOBuilder.getName());
1703 name.append("Builder");
1704 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1705 unionBuilder.setIsUnionBuilder(true);
1706 return unionBuilder;
1709 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1710 final Module module) {
1711 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1715 * Instantiates generated type builder with <code>packageName</code> and
1716 * <code>schemaNode</code>.
1718 * The new builder always implements
1719 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1720 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1721 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1723 * If <code>schemaNode</code> is instance of
1724 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1725 * DataNodeContainer} it can also implement nodes which are specified in
1728 * @param packageName
1729 * string with the name of the package to which
1730 * <code>schemaNode</code> belongs.
1732 * schema node for which is created generated type builder
1734 * parent type (can be null)
1735 * @return generated type builder <code>schemaNode</code>
1737 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1738 final Type parent, final Module module) {
1739 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1740 if (parent == null) {
1741 it.addImplementsType(DATA_OBJECT);
1743 it.addImplementsType(BindingTypes.childOf(parent));
1745 if (!(schemaNode instanceof GroupingDefinition)) {
1746 it.addImplementsType(augmentable(it));
1749 if (schemaNode instanceof DataNodeContainer) {
1750 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1751 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1758 * Wraps the calling of the same overloaded method.
1760 * @param packageName
1761 * string with the package name to which returning generated type
1764 * schema node which provide data about the schema node name
1765 * @return generated type builder for <code>schemaNode</code>
1767 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1768 return addRawInterfaceDefinition(packageName, schemaNode, "");
1772 * Returns reference to generated type builder for specified
1773 * <code>schemaNode</code> with <code>packageName</code>.
1775 * Firstly the generated type builder is searched in
1776 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1777 * found it is created and added to <code>genTypeBuilders</code>.
1779 * @param packageName
1780 * string with the package name to which returning generated type
1783 * schema node which provide data about the schema node name
1785 * return type name prefix
1786 * @return generated type builder for <code>schemaNode</code>
1787 * @throws IllegalArgumentException
1789 * <li>if <code>schemaNode</code> is null</li>
1790 * <li>if <code>packageName</code> is null</li>
1791 * <li>if QName of schema node is null</li>
1792 * <li>if schemaNode name is null</li>
1796 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1797 final String prefix) {
1798 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1799 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1800 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1801 final String schemaNodeName = schemaNode.getQName().getLocalName();
1802 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1805 if (prefix == null) {
1806 genTypeName = BindingMapping.getClassName(schemaNodeName);
1808 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1811 // FIXME: Validation of name conflict
1812 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1813 final Module module = findParentModule(schemaContext, schemaNode);
1814 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1815 newType.addComment(schemaNode.getDescription());
1816 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1817 newType.setReference(schemaNode.getReference());
1818 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1819 newType.setModuleName(module.getName());
1821 if (!genTypeBuilders.containsKey(packageName)) {
1822 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1823 builders.put(genTypeName, newType);
1824 genTypeBuilders.put(packageName, builders);
1826 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1827 if (!builders.containsKey(genTypeName)) {
1828 builders.put(genTypeName, newType);
1835 * Creates the name of the getter method name from <code>localName</code>.
1838 * string with the name of the getter method
1841 * @return string with the name of the getter method for
1842 * <code>methodName</code> in JAVA method format
1844 public static String getterMethodName(final String localName, final Type returnType) {
1845 final StringBuilder method = new StringBuilder();
1846 if (BOOLEAN.equals(returnType)) {
1847 method.append("is");
1849 method.append("get");
1851 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1852 method.append(name);
1853 return method.toString();
1857 * Created a method signature builder as part of
1858 * <code>interfaceBuilder</code>.
1860 * The method signature builder is created for the getter method of
1861 * <code>schemaNodeName</code>. Also <code>comment</code> and
1862 * <code>returnType</code> information are added to the builder.
1864 * @param interfaceBuilder
1865 * generated type builder for which the getter method should be
1867 * @param schemaNodeName
1868 * string with schema node name. The name will be the part of the
1869 * getter method name.
1871 * string with comment for the getter method
1873 * type which represents the return type of the getter method
1875 * status from yang file, for deprecated annotation
1876 * @return method signature builder which represents the getter method of
1877 * <code>interfaceBuilder</code>
1879 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1880 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1881 final MethodSignatureBuilder getMethod = interfaceBuilder
1882 .addMethod(getterMethodName(schemaNodeName, returnType));
1883 if (status == Status.DEPRECATED) {
1884 getMethod.addAnnotation("", "Deprecated");
1886 getMethod.setComment(encodeAngleBrackets(comment));
1887 getMethod.setReturnType(returnType);
1892 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1893 * or to <code>genTOBuilder</code> as property.
1895 * @param basePackageName
1896 * string contains the module package name
1898 * data schema node which should be added as getter method to
1899 * <code>typeBuilder</code> or as a property to
1900 * <code>genTOBuilder</code> if is part of the list key
1901 * @param typeBuilder
1902 * generated type builder for the list schema node
1903 * @param genTOBuilder
1904 * generated TO builder for the list keys
1906 * list of string which contains names of the list keys
1909 * @throws IllegalArgumentException
1911 * <li>if <code>schemaNode</code> equals null</li>
1912 * <li>if <code>typeBuilder</code> equals null</li>
1915 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1916 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1917 final Module module) {
1918 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1919 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1921 if (schemaNode instanceof LeafSchemaNode) {
1922 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1923 final String leafName = leaf.getQName().getLocalName();
1924 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1925 if (listKeys.contains(leafName)) {
1927 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1929 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1932 } else if (!schemaNode.isAddedByUses()) {
1933 if (schemaNode instanceof LeafListSchemaNode) {
1934 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1935 } else if (schemaNode instanceof ContainerSchemaNode) {
1936 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1937 } else if (schemaNode instanceof ChoiceSchemaNode) {
1938 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1939 } else if (schemaNode instanceof ListSchemaNode) {
1940 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1945 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1946 final GeneratedTOBuilder genTOBuilder) {
1947 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1949 if (genTOBuilder != null) {
1950 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1951 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1952 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1957 * Selects the names of the list keys from <code>list</code> and returns
1958 * them as the list of the strings
1961 * of string with names of the list keys
1962 * @return list of string which represents names of the list keys. If the
1963 * <code>list</code> contains no keys then the empty list is
1966 private static List<String> listKeys(final ListSchemaNode list) {
1967 final List<String> listKeys = new ArrayList<>();
1969 final List<QName> keyDefinition = list.getKeyDefinition();
1970 if (keyDefinition != null) {
1971 for (final QName keyDef : keyDefinition) {
1972 listKeys.add(keyDef.getLocalName());
1979 * Generates for the <code>list</code> which contains any list keys special
1980 * generated TO builder.
1982 * @param packageName
1983 * string with package name to which the list belongs
1985 * list schema node which is source of data about the list name
1986 * @return generated TO builder which represents the keys of the
1987 * <code>list</code> or null if <code>list</code> is null or list of
1988 * key definitions is null or empty.
1990 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1991 GeneratedTOBuilder genTOBuilder = null;
1992 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1993 final String listName = list.getQName().getLocalName() + "Key";
1994 final String genTOName = BindingMapping.getClassName(listName);
1995 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1997 return genTOBuilder;
2001 * Builds generated TO builders for <code>typeDef</code> of type
2002 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
2003 * also added to <code>typeBuilder</code> as enclosing transfer object.
2005 * If more then one generated TO builder is created for enclosing then all
2006 * of the generated TO builders are added to <code>typeBuilder</code> as
2007 * enclosing transfer objects.
2010 * type definition which can be of type <code>UnionType</code> or
2011 * <code>BitsTypeDefinition</code>
2012 * @param typeBuilder
2013 * generated type builder to which is added generated TO created
2014 * from <code>typeDef</code>
2016 * string with name for generated TO builder
2017 * @param parentModule
2019 * @return generated TO builder for <code>typeDef</code>
2021 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2022 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2023 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2024 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2025 final String packageName = typeBuilder.getFullyQualifiedName();
2026 if (typeDef instanceof UnionTypeDefinition) {
2027 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2028 .provideGeneratedTOBuildersForUnionTypeDef(packageName, (UnionTypeDefinition) typeDef,
2029 classNameFromLeaf, leaf);
2030 genTOBuilders.addAll(types);
2032 GeneratedTOBuilder resultTOBuilder;
2033 if (types.isEmpty()) {
2034 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2036 resultTOBuilder = types.remove(0);
2037 for (final GeneratedTOBuilder genTOBuilder : types) {
2038 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2041 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2042 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2043 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2044 resultTOBuilder.addHashIdentity(genPropBuilder);
2045 resultTOBuilder.addToStringProperty(genPropBuilder);
2047 } else if (typeDef instanceof BitsTypeDefinition) {
2048 genTOBuilders.add(((TypeProviderImpl) typeProvider).provideGeneratedTOBuilderForBitsTypeDefinition(
2049 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2051 if (!genTOBuilders.isEmpty()) {
2052 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2053 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2055 return genTOBuilders.get(0);
2062 * Adds the implemented types to type builder.
2064 * The method passes through the list of <i>uses</i> in
2065 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2066 * generated type from {@link ModuleContext#groupings
2067 * allGroupings} which is added as <i>implements type</i> to
2068 * <code>builder</code>
2070 * @param dataNodeContainer
2071 * element which contains the list of used YANG groupings
2073 * builder to which are added implemented types according to
2074 * <code>dataNodeContainer</code>
2075 * @return generated type builder with all implemented types
2077 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2078 final GeneratedTypeBuilder builder) {
2079 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2080 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2081 if (genType == null) {
2082 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2083 + builder.getName());
2086 builder.addImplementsType(genType);
2091 private static boolean isNullOrEmpty(final Collection<?> list) {
2092 return list == null || list.isEmpty();
2095 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2096 final StringBuilder sb = new StringBuilder();
2098 if (!isNullOrEmpty(schemaNodes)) {
2099 final SchemaNode node = schemaNodes.iterator().next();
2101 if (node instanceof RpcDefinition) {
2102 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2103 } else if (node instanceof NotificationDefinition) {
2104 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2107 sb.append(NEW_LINE);
2109 if (verboseClassComments) {
2111 sb.append(NEW_LINE);
2112 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2113 sb.append("</pre>");
2114 sb.append(NEW_LINE);
2117 return replaceAllIllegalChars(sb);
2120 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2121 final StringBuilder sb = new StringBuilder();
2122 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
2123 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2125 if (!Strings.isNullOrEmpty(formattedDescription)) {
2126 sb.append(formattedDescription);
2127 sb.append(NEW_LINE);
2130 if (verboseClassComments) {
2131 final Module module = findParentModule(schemaContext, schemaNode);
2132 final StringBuilder linkToBuilderClass = new StringBuilder();
2133 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2134 final String className = namespace[namespace.length - 1];
2136 if (hasBuilderClass(schemaNode)) {
2137 linkToBuilderClass.append(className);
2138 linkToBuilderClass.append("Builder");
2142 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2143 sb.append(module.getName());
2145 sb.append(NEW_LINE);
2147 sb.append(NEW_LINE);
2148 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2149 sb.append("</pre>");
2150 sb.append(NEW_LINE);
2151 sb.append("The schema path to identify an instance is");
2152 sb.append(NEW_LINE);
2154 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2156 sb.append(NEW_LINE);
2158 if (hasBuilderClass(schemaNode)) {
2159 sb.append(NEW_LINE);
2160 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2161 sb.append(NEW_LINE);
2163 sb.append(linkToBuilderClass);
2164 sb.append(NEW_LINE);
2165 if (schemaNode instanceof ListSchemaNode) {
2166 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2167 if (keyDef != null && !keyDef.isEmpty()) {
2169 sb.append(className);
2172 sb.append(NEW_LINE);
2177 return replaceAllIllegalChars(sb);
2180 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2181 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2182 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2188 private String createDescription(final Module module) {
2189 final StringBuilder sb = new StringBuilder();
2190 final String moduleDescription = encodeAngleBrackets(module.getDescription());
2191 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2193 if (!Strings.isNullOrEmpty(formattedDescription)) {
2194 sb.append(formattedDescription);
2195 sb.append(NEW_LINE);
2198 if (verboseClassComments) {
2200 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2201 sb.append(module.getName());
2203 sb.append(NEW_LINE);
2205 sb.append(NEW_LINE);
2206 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2207 sb.append("</pre>");
2210 return replaceAllIllegalChars(sb);
2213 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2214 for (final ModuleContext ctx : genCtx.values()) {
2215 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2216 if (result != null) {
2223 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2224 for (final ModuleContext ctx : genCtx.values()) {
2225 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2226 if (result != null) {
2233 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2234 for (final ModuleContext ctx : genCtx.values()) {
2235 final GeneratedTypeBuilder result = ctx.getCase(path);
2236 if (result != null) {
2243 public Map<Module, ModuleContext> getModuleContexts() {
2248 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2249 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2250 return ret.isEmpty() ? "" : ret;
2253 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2254 if (status == Status.DEPRECATED) {
2255 builder.addAnnotation("", "Deprecated");