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.Preconditions;
33 import com.google.common.base.Splitter;
34 import com.google.common.base.Strings;
35 import com.google.common.collect.Iterables;
36 import com.google.common.collect.Sets;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.Comparator;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
44 import java.util.Optional;
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.AugmentationSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
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.ModuleDependencySort;
109 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
110 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
111 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
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<AugmentationSchemaNode> 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 List<Module> contextModules = ModuleDependencySort.sort(context.getModules());
254 genTypeBuilders = new HashMap<>();
256 for (final Module contextModule : contextModules) {
257 moduleToGenTypes(contextModule, context);
259 for (final Module contextModule : contextModules) {
260 allAugmentsToGenTypes(contextModule);
263 final List<Type> filteredGenTypes = new ArrayList<>();
264 for (final Module m : modules) {
265 final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
266 filteredGenTypes.addAll(ctx.getGeneratedTypes());
267 final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
268 if (additionalTypes != null) {
269 filteredGenTypes.addAll(additionalTypes);
273 return filteredGenTypes;
276 private void moduleToGenTypes(final Module m, final SchemaContext context) {
277 genCtx.put(m, new ModuleContext());
278 allTypeDefinitionsToGenTypes(m);
279 groupingsToGenTypes(m, m.getGroupings());
280 rpcMethodsToGenType(m);
281 allIdentitiesToGenTypes(m, context);
282 notificationsToGenType(m);
284 if (!m.getChildNodes().isEmpty()) {
285 final GeneratedTypeBuilder moduleType = moduleToDataType(m);
286 genCtx.get(m).addModuleNode(moduleType);
287 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
288 resolveDataSchemaNodes(m, basePackageName, moduleType, moduleType, m.getChildNodes());
293 * Converts all extended type definitions of module to the list of
294 * <code>Type</code> objects.
297 * module from which is obtained set of type definitions
298 * @throws IllegalArgumentException
300 * <li>if module is null</li>
301 * <li>if name of module is null</li>
303 * @throws IllegalStateException
304 * if set of type definitions from module is null
306 private void allTypeDefinitionsToGenTypes(final Module module) {
307 checkArgument(module != null, "Module reference cannot be NULL.");
308 checkArgument(module.getName() != null, "Module name cannot be NULL.");
309 final DataNodeIterator it = new DataNodeIterator(module);
310 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
311 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
313 for (final TypeDefinition<?> typedef : typeDefinitions) {
314 if (typedef != null) {
315 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
318 final ModuleContext ctx = genCtx.get(module);
319 ctx.addTypedefType(typedef.getPath(), type);
320 ctx.addTypeToSchema(type,typedef);
326 private GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName,
327 final GeneratedTypeBuilder childOf, final DataSchemaNode node) {
328 if (node.isAugmenting() || node.isAddedByUses()) {
331 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
332 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
333 genType.addComment(node.getDescription().orElse(null));
334 annotateDeprecatedIfNecessary(node.getStatus(), genType);
335 genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
336 genType.setModuleName(module.getName());
337 genType.setReference(node.getReference().orElse(null));
338 genType.setSchemaPath(node.getPath().getPathFromRoot());
339 if (node instanceof DataNodeContainer) {
340 genCtx.get(module).addChildNodeType(node, genType);
341 groupingsToGenTypes(module, ((DataNodeContainer) node).getGroupings());
342 processUsesAugments((DataNodeContainer) node, module);
347 private void containerToGenType(final Module module, final String basePackageName,
348 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
349 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
350 if (genType != null) {
351 constructGetter(parent, node.getQName().getLocalName(), node.getDescription().orElse(null), genType,
353 resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
357 private void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder parent,
358 final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
359 final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
360 if (genType != null) {
361 constructGetter(parent, node.getQName().getLocalName(), node.getDescription().orElse(null),
362 Types.listTypeFor(genType), node.getStatus());
364 final List<String> listKeys = listKeys(node);
365 final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
366 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node);
367 if (genTOBuilder != null) {
368 final Type identifierMarker = Types.parameterizedTypeFor(IDENTIFIER, genType);
369 final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder);
370 genTOBuilder.addImplementsType(identifierMarker);
371 genType.addImplementsType(identifiableMarker);
374 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
375 if (!schemaNode.isAugmenting()) {
376 addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
381 if (genTOBuilder != null) {
382 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
383 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
384 genTOBuilder.setSUID(prop);
387 typeBuildersToGenTypes(module, genType, genTOBuilder);
391 private void processUsesAugments(final DataNodeContainer node, final Module module) {
392 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
393 for (final UsesNode usesNode : node.getUses()) {
394 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
395 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
396 processUsesAugments(augment, module);
402 * Converts all <b>augmentation</b> of the module to the list
403 * <code>Type</code> objects.
406 * module from which is obtained list of all augmentation objects
407 * to iterate over them
408 * @throws IllegalArgumentException
410 * <li>if the module is null</li>
411 * <li>if the name of module is null</li>
413 * @throws IllegalStateException
414 * if set of augmentations from module is null
416 private void allAugmentsToGenTypes(final Module module) {
417 checkArgument(module != null, "Module reference cannot be NULL.");
418 checkArgument(module.getName() != null, "Module name cannot be NULL.");
419 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
421 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
422 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
423 augmentationToGenTypes(basePackageName, augment, module);
428 * Returns list of <code>AugmentationSchema</code> objects. The objects are
429 * sorted according to the length of their target path from the shortest to
433 * module from which is obtained list of all augmentation objects
434 * @return list of sorted <code>AugmentationSchema</code> objects obtained
435 * from <code>module</code>
436 * @throws IllegalArgumentException
438 * @throws IllegalStateException
439 * if set of module augmentations is null
441 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
442 checkArgument(module != null, "Module reference cannot be NULL.");
443 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
445 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
446 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
447 sortedAugmentations.sort(AUGMENT_COMP);
449 return sortedAugmentations;
453 * Create GeneratedTypeBuilder object from module argument.
456 * Module object from which builder will be created
457 * @return <code>GeneratedTypeBuilder</code> which is internal
458 * representation of the module
459 * @throws IllegalArgumentException
462 private GeneratedTypeBuilder moduleToDataType(final Module module) {
463 checkArgument(module != null, "Module reference cannot be NULL.");
465 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
466 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
467 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
468 moduleDataTypeBuilder.addComment(module.getDescription().orElse(null));
469 moduleDataTypeBuilder.setDescription(createDescription(module));
470 moduleDataTypeBuilder.setReference(module.getReference().orElse(null));
471 return moduleDataTypeBuilder;
475 * Converts all <b>rpcs</b> inputs and outputs substatements of the module
476 * to the list of <code>Type</code> objects. In addition are to containers
477 * and lists which belong to input or output also part of returning list.
480 * module from which is obtained set of all rpc objects to
482 * @throws IllegalArgumentException
484 * <li>if the module is null</li>
485 * <li>if the name of module is null</li>
487 * @throws IllegalStateException
488 * if set of rpcs from module is null
490 private void rpcMethodsToGenType(final Module module) {
491 checkArgument(module != null, "Module reference cannot be NULL.");
492 checkArgument(module.getName() != null, "Module name cannot be NULL.");
493 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
494 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
495 if (rpcDefinitions.isEmpty()) {
499 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
500 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, "Service");
501 interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
502 interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName()));
504 for (final RpcDefinition rpc : rpcDefinitions) {
506 final String rpcName = BindingMapping.getClassName(rpc.getQName());
507 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
508 final String rpcComment = encodeAngleBrackets(rpc.getDescription().orElse(null));
509 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
510 final ContainerSchemaNode input = rpc.getInput();
511 final ContainerSchemaNode output = rpc.getOutput();
513 // Do not refer to annotation class, as it may not be available at runtime
514 method.addAnnotation("javax.annotation", "CheckReturnValue");
516 //in case of implicit RPC input (StatementSource.CONTEXT),
517 // stay compatible (no input argument generated)
518 if (input != null && isExplicitStatement(input)) {
519 processUsesAugments(input, module);
520 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
521 addImplementedInterfaceFromUses(input, inType);
522 inType.addImplementsType(DATA_OBJECT);
523 inType.addImplementsType(augmentable(inType));
524 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
525 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
526 genCtx.get(module).addChildNodeType(input, inType);
527 final GeneratedType inTypeInstance = inType.toInstance();
528 method.addParameter(inTypeInstance, "input");
531 Type outTypeInstance = VOID;
532 //in case of implicit RPC output (StatementSource.CONTEXT),
533 //stay compatible (Future<RpcResult<Void>> return type generated)
534 if (output != null && isExplicitStatement(output)) {
535 processUsesAugments(output, module);
536 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
537 addImplementedInterfaceFromUses(output, outType);
538 outType.addImplementsType(DATA_OBJECT);
539 outType.addImplementsType(augmentable(outType));
540 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
541 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
542 genCtx.get(module).addChildNodeType(output, outType);
543 outTypeInstance = outType.toInstance();
546 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
547 method.setComment(rpcComment);
548 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
552 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
555 private static boolean isExplicitStatement(final ContainerSchemaNode node) {
556 return node instanceof EffectiveStatement
557 && ((EffectiveStatement<?, ?>) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
561 * Converts all <b>notifications</b> of the module to the list of
562 * <code>Type</code> objects. In addition are to this list added containers
563 * and lists which are part of this notification.
566 * module from which is obtained set of all notification objects
567 * to iterate over them
568 * @throws IllegalArgumentException
570 * <li>if the module equals null</li>
571 * <li>if the name of module equals null</li>
573 * @throws IllegalStateException
574 * if set of notifications from module is null
576 private void notificationsToGenType(final Module module) {
577 checkArgument(module != null, "Module reference cannot be NULL.");
578 checkArgument(module.getName() != null, "Module name cannot be NULL.");
579 final Set<NotificationDefinition> notifications = module.getNotifications();
580 if (notifications.isEmpty()) {
584 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
585 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
586 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
590 for (final NotificationDefinition notification : notifications) {
591 if (notification != null) {
592 processUsesAugments(notification, module);
594 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
595 notification, null, module);
596 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
597 notificationInterface.addImplementsType(NOTIFICATION);
598 genCtx.get(module).addChildNodeType(notification, notificationInterface);
600 // Notification object
601 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
602 notification.getChildNodes());
604 listenerInterface.addMethod("on" + notificationInterface.getName())
605 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
606 .setComment(encodeAngleBrackets(notification.getDescription().orElse(null))).setReturnType(Types.VOID);
609 listenerInterface.setDescription(createDescription(notifications, module.getName()));
611 genCtx.get(module).addTopLevelNodeType(listenerInterface);
615 * Converts all <b>identities</b> of the module to the list of
616 * <code>Type</code> objects.
619 * module from which is obtained set of all identity objects to
622 * schema context only used as input parameter for method
623 * {@link BindingGeneratorImpl#identityToGenType}
626 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
627 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
628 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
630 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
631 for (final IdentitySchemaNode identity : schemaIdentities) {
632 identityToGenType(module, basePackageName, identity, context);
638 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
639 * created transport object builder. If identity contains base identity then
640 * reference to base identity is added to superior identity as its extend.
641 * If identity doesn't contain base identity then only reference to abstract
642 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
643 * BaseIdentity} is added
647 * @param basePackageName
648 * string contains the module package name
650 * IdentitySchemaNode which contains data about identity
652 * SchemaContext which is used to get package and name
653 * information about base of identity
656 private void identityToGenType(final Module module, final String basePackageName,
657 final IdentitySchemaNode identity, final SchemaContext context) {
658 if (identity == null) {
661 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
662 final String genTypeName = BindingMapping.getClassName(identity.getQName());
663 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
664 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
665 if (baseIdentities.isEmpty()) {
666 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
667 BaseIdentity.class.getSimpleName());
668 newType.setExtendsType(gto.toInstance());
670 final IdentitySchemaNode baseIdentity = baseIdentities.iterator().next();
671 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
672 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
674 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
675 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
677 newType.setExtendsType(gto);
679 newType.setAbstract(true);
680 newType.addComment(identity.getDescription().orElse(null));
681 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
682 newType.setReference(identity.getReference().orElse(null));
683 newType.setModuleName(module.getName());
684 newType.setSchemaPath(identity.getPath().getPathFromRoot());
686 final QName qname = identity.getQName();
687 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
689 genCtx.get(module).addIdentityType(identity.getQName(), newType);
692 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
694 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
698 * Converts all <b>groupings</b> of the module to the list of
699 * <code>Type</code> objects. Firstly are groupings sorted according mutual
700 * dependencies. At least dependent (independent) groupings are in the list
701 * saved at first positions. For every grouping the record is added to map
702 * {@link ModuleContext#groupings allGroupings}
707 * collection of groupings from which types will be generated
710 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
711 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
712 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
714 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
715 groupingToGenType(basePackageName, grouping, module);
720 * Converts individual grouping to GeneratedType. Firstly generated type
721 * builder is created and every child node of grouping is resolved to the
724 * @param basePackageName
725 * string contains the module package name
727 * GroupingDefinition which contains data about grouping
731 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping,
732 final Module module) {
733 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
734 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
735 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
736 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
737 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
738 groupingsToGenTypes(module, grouping.getGroupings());
739 processUsesAugments(grouping, module);
743 * Adds enumeration builder created from <code>enumTypeDef</code> to
744 * <code>typeBuilder</code>.
746 * Each <code>enumTypeDef</code> item is added to builder with its name and
750 * EnumTypeDefinition contains enum data
752 * string contains name which will be assigned to enumeration
755 * GeneratedTypeBuilder to which will be enum builder assigned
757 * Module in which type should be generated
758 * @return enumeration builder which contains data from
759 * <code>enumTypeDef</code>
761 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
762 final GeneratedTypeBuilder typeBuilder, final Module module) {
763 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
764 final String enumerationName = BindingMapping.getClassName(enumName);
765 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
766 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null));
767 enumBuilder.setDescription(enumTypedefDescription);
768 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
769 ModuleContext ctx = genCtx.get(module);
770 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
777 * Generates type builder for <code>module</code>.
780 * Module which is source of package name for generated type
783 * string which is added to the module class name representation
785 * @return instance of GeneratedTypeBuilder which represents
786 * <code>module</code>.
787 * @throws IllegalArgumentException
788 * if <code>module</code> is null
790 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
791 checkArgument(module != null, "Module reference cannot be NULL.");
792 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
793 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
795 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
796 moduleBuilder.setDescription(createDescription(module));
797 moduleBuilder.setReference(module.getReference().orElse(null));
798 moduleBuilder.setModuleName(moduleName);
800 return moduleBuilder;
804 * Converts <code>augSchema</code> to list of <code>Type</code> which
805 * contains generated type for augmentation. In addition there are also
806 * generated types for all containers, list and choices which are child of
807 * <code>augSchema</code> node or a generated types for cases are added if
808 * augmented node is choice.
810 * @param augmentPackageName
811 * string with the name of the package to which the augmentation
814 * AugmentationSchema which is contains data about augmentation
815 * (target path, childs...)
818 * @throws IllegalArgumentException
820 * <li>if <code>augmentPackageName</code> equals null</li>
821 * <li>if <code>augSchema</code> equals null</li>
823 * @throws IllegalStateException
824 * if augment target path is null
826 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchemaNode augSchema,
827 final Module module) {
828 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
829 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
830 checkState(augSchema.getTargetPath() != null,
831 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
833 processUsesAugments(augSchema, module);
834 final SchemaPath targetPath = augSchema.getTargetPath();
835 SchemaNode targetSchemaNode = null;
837 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
838 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
839 if (targetSchemaNode instanceof DerivableSchemaNode) {
840 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
842 if (targetSchemaNode == null) {
843 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
844 + " in module " + module.getName());
847 if (targetSchemaNode == null) {
848 throw new IllegalArgumentException("augment target not found: " + targetPath);
851 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
852 if (targetTypeBuilder == null) {
853 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
855 if (targetTypeBuilder == null) {
856 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
859 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
860 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
861 targetTypeBuilder.getName());
862 addRawAugmentGenTypeDefinition(module, augmentPackageName, augmentPackageName, targetType, augSchema);
865 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
866 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
870 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchemaNode augSchema,
871 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
872 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
873 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
874 checkState(augSchema.getTargetPath() != null,
875 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
877 processUsesAugments(augSchema, module);
878 final SchemaPath targetPath = augSchema.getTargetPath();
879 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
880 if (targetSchemaNode == null) {
881 throw new IllegalArgumentException("augment target not found: " + targetPath);
884 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
885 if (targetTypeBuilder == null) {
886 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
888 if (targetTypeBuilder == null) {
889 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
892 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
893 String packageName = augmentPackageName;
894 if (usesNodeParent instanceof SchemaNode) {
895 packageName = packageNameForAugmentedGeneratedType(augmentPackageName,
896 ((SchemaNode) usesNodeParent).getPath());
898 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
901 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
902 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
907 * Convenient method to find node added by uses statement.
911 * @param parentUsesNode
912 * parent of uses node
913 * @return node from its original location in grouping
915 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
916 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
918 if (!(targetGrouping instanceof GroupingDefinition)) {
919 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
922 SchemaNode result = targetGrouping;
923 for (final QName node : targetPath.getPathFromRoot()) {
924 if (result instanceof DataNodeContainer) {
925 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
926 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
927 } else if (result instanceof ChoiceSchemaNode) {
928 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
931 if (result == null) {
935 if (result instanceof DerivableSchemaNode) {
936 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
937 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
938 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
939 result = originalNode.get();
943 if (result instanceof DataSchemaNode) {
944 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
945 if (resultDataSchemaNode.isAddedByUses()) {
946 // The original node is required, but we have only the copy of
947 // the original node.
948 // Maybe this indicates a bug in Yang parser.
949 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
952 return resultDataSchemaNode;
955 throw new IllegalStateException(
956 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
961 * Returns a generated type builder for an augmentation.
963 * The name of the type builder is equal to the name of augmented node with
964 * serial number as suffix.
968 * @param augmentPackageName
969 * string with contains the package name to which the augment
971 * @param basePackageName
972 * string with the package name to which the augmented node
974 * @param targetTypeRef
977 * augmentation schema which contains data about the child nodes
978 * and uses of augment
979 * @return generated type builder for augment
981 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
982 final String basePackageName, final Type targetTypeRef, final AugmentationSchemaNode augSchema) {
983 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
984 if (augmentBuilders == null) {
985 augmentBuilders = new HashMap<>();
986 genTypeBuilders.put(augmentPackageName, augmentBuilders);
988 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
991 if (augIdentifier != null) {
992 augTypeName = BindingMapping.getClassName(augIdentifier);
994 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
997 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
999 augTypeBuilder.addImplementsType(DATA_OBJECT);
1000 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
1001 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
1002 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1004 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
1005 augmentBuilders.put(augTypeName, augTypeBuilder);
1007 if (!augSchema.getChildNodes().isEmpty()) {
1008 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1011 genCtx.get(module).addAugmentType(augTypeBuilder);
1012 return augTypeBuilder;
1017 * @param unknownSchemaNodes
1018 * @return nodeParameter of UnknownSchemaNode
1020 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1021 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1022 final QName nodeType = unknownSchemaNode.getNodeType();
1023 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1024 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1025 return unknownSchemaNode.getNodeParameter();
1032 * Returns first unique name for the augment generated type builder. The
1033 * generated type builder name for augment consists from name of augmented
1034 * node and serial number of its augmentation.
1037 * map of builders which were created in the package to which the
1038 * augmentation belongs
1039 * @param genTypeName
1040 * string with name of augmented node
1041 * @return string with unique name for augmentation builder
1043 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1045 if (builders != null) {
1046 while (builders.containsKey(genTypeName + index)) {
1050 return genTypeName + index;
1054 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1055 * node for which <code>typeBuilder</code> was created.
1057 * The subnodes aren't mapped to the methods if they are part of grouping or
1058 * augment (in this case are already part of them).
1062 * @param basePackageName
1063 * string contains the module package name
1065 * generated type builder which represents any node. The subnodes
1066 * of this node are added to the <code>typeBuilder</code> as
1067 * methods. The subnode can be of type leaf, leaf-list, list,
1068 * container, choice.
1071 * @param schemaNodes
1072 * set of data schema nodes which are the children of the node
1073 * for which <code>typeBuilder</code> was created
1074 * @return generated type builder which is the same builder as input
1075 * parameter. The getter methods (representing child nodes) could be
1078 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1079 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1080 if (schemaNodes != null && parent != null) {
1081 for (final DataSchemaNode schemaNode : schemaNodes) {
1082 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1083 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1091 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1092 * node for which <code>typeBuilder</code> was created.
1096 * @param basePackageName
1097 * string contains the module package name
1098 * @param typeBuilder
1099 * generated type builder which represents any node. The subnodes
1100 * of this node are added to the <code>typeBuilder</code> as
1101 * methods. The subnode can be of type leaf, leaf-list, list,
1102 * container, choice.
1105 * @param schemaNodes
1106 * set of data schema nodes which are the children of the node
1107 * for which <code>typeBuilder</code> was created
1108 * @return generated type builder which is the same object as the input
1109 * parameter <code>typeBuilder</code>. The getter method could be
1112 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1113 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1114 final Iterable<DataSchemaNode> schemaNodes) {
1115 if (schemaNodes != null && typeBuilder != null) {
1116 for (final DataSchemaNode schemaNode : schemaNodes) {
1117 if (!schemaNode.isAugmenting()) {
1118 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1126 * Adds to <code>typeBuilder</code> a method which is derived from
1127 * <code>schemaNode</code>.
1129 * @param basePackageName
1130 * string with the module package name
1132 * data schema node which is added to <code>typeBuilder</code> as
1134 * @param typeBuilder
1135 * generated type builder to which is <code>schemaNode</code>
1136 * added as a method.
1142 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1143 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1144 if (node != null && typeBuilder != null) {
1145 if (node instanceof LeafSchemaNode) {
1146 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1147 } else if (node instanceof LeafListSchemaNode) {
1148 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1149 } else if (node instanceof ContainerSchemaNode) {
1150 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1151 } else if (node instanceof ListSchemaNode) {
1152 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1153 } else if (node instanceof ChoiceSchemaNode) {
1154 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1156 // TODO: anyxml not yet supported
1157 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1158 typeBuilder.getFullyQualifiedName());
1164 * Converts <code>choiceNode</code> to the list of generated types for
1165 * choice and its cases.
1167 * The package names for choice and for its cases are created as
1168 * concatenation of the module package (<code>basePackageName</code>) and
1169 * names of all parents node.
1173 * @param basePackageName
1174 * string with the module package name
1178 * choice node which is mapped to generated type. Also child
1179 * nodes - cases are mapped to generated types.
1180 * @throws IllegalArgumentException
1182 * <li>if <code>basePackageName</code> is null</li>
1183 * <li>if <code>choiceNode</code> is null</li>
1186 private void choiceToGeneratedType(final Module module, final String basePackageName,
1187 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1188 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1189 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1191 if (!choiceNode.isAddedByUses()) {
1192 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1193 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1194 constructGetter(parent, choiceNode.getQName().getLocalName(),
1195 choiceNode.getDescription().orElse(null), choiceTypeBuilder, choiceNode.getStatus());
1196 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1197 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1198 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1199 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1204 * Converts <code>caseNodes</code> set to list of corresponding generated
1207 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1208 * created generated type builder. The package names for the builder is
1209 * created as concatenation of the module package (
1210 * <code>basePackageName</code>) and names of all parents nodes of the
1211 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1212 * between every case builder and <i>choice</i> type
1216 * @param basePackageName
1217 * string with the module package name
1218 * @param refChoiceType
1219 * type which represents superior <i>case</i>
1221 * choice case node which is mapped to generated type
1222 * @throws IllegalArgumentException
1224 * <li>if <code>basePackageName</code> equals null</li>
1225 * <li>if <code>refChoiceType</code> equals null</li>
1226 * <li>if <code>caseNodes</code> equals null</li>
1229 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1230 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1231 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1232 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1233 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1235 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1236 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1237 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1238 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode,
1240 caseTypeBuilder.addImplementsType(refChoiceType);
1241 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1242 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1243 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1244 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1245 if (caseChildNodes != null) {
1246 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1248 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1249 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1251 if (parent instanceof AugmentationSchemaNode) {
1252 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1253 final SchemaPath targetPath = augSchema.getTargetPath();
1254 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1255 if (targetSchemaNode instanceof DataSchemaNode
1256 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1257 if (targetSchemaNode instanceof DerivableSchemaNode) {
1258 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1261 if (targetSchemaNode == null) {
1262 throw new IllegalStateException(
1263 "Failed to find target node from grouping for augmentation " + augSchema
1264 + " in module " + module.getName());
1267 parent = targetSchemaNode;
1270 Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1271 choiceNodeParentPath);
1272 GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1273 if (childOfType == null) {
1274 childOfType = findGroupingByPath(parent.getPath());
1276 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1278 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1283 processUsesAugments(caseNode, module);
1288 * Generates list of generated types for all the cases of a choice which are
1289 * added to the choice through the augment.
1293 * @param basePackageName
1294 * string contains name of package to which augment belongs. If
1295 * an augmented choice is from an other package (pcg1) than an
1296 * augmenting choice (pcg2) then case's of the augmenting choice
1297 * will belong to pcg2.
1299 * Type which represents target choice
1301 * node which represents target choice
1302 * @param augmentedNodes
1303 * set of choice case nodes for which is checked if are/aren't
1304 * added to choice through augmentation
1305 * @throws IllegalArgumentException
1307 * <li>if <code>basePackageName</code> is null</li>
1308 * <li>if <code>targetType</code> is null</li>
1309 * <li>if <code>augmentedNodes</code> is null</li>
1312 private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1313 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1314 final DataNodeContainer usesNodeParent) {
1315 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1316 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1317 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1319 for (final DataSchemaNode caseNode : augmentedNodes) {
1320 if (caseNode != null) {
1321 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1322 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1323 caseTypeBuilder.addImplementsType(targetType);
1326 final SchemaPath nodeSp = targetNode.getPath();
1327 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1329 GeneratedTypeBuilder childOfType = null;
1330 if (parent instanceof Module) {
1331 childOfType = genCtx.get(parent).getModuleNode();
1332 } else if (parent instanceof CaseSchemaNode) {
1333 childOfType = findCaseByPath(parent.getPath());
1334 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1335 childOfType = findChildNodeByPath(parent.getPath());
1336 } else if (parent instanceof GroupingDefinition) {
1337 childOfType = findGroupingByPath(parent.getPath());
1340 if (childOfType == null) {
1341 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1344 CaseSchemaNode node = null;
1345 final String caseLocalName = caseNode.getQName().getLocalName();
1346 if (caseNode instanceof CaseSchemaNode) {
1347 node = (CaseSchemaNode) caseNode;
1348 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1349 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1350 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1351 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1352 ().getLocalName())) {
1353 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1358 node = findNamedCase(targetNode, caseLocalName);
1360 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1361 if (childNodes != null) {
1362 resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1364 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1365 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1370 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1371 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1372 return cases.isEmpty() ? null : cases.get(0);
1375 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1376 // New parser with encapsulated type
1377 if (leaf.getPath().equals(type.getPath())) {
1381 // Embedded type definition with new parser. Also takes care of the old parser with bits
1382 if (leaf.getPath().equals(type.getPath().getParent())) {
1390 * Converts <code>leaf</code> to the getter method which is added to
1391 * <code>typeBuilder</code>.
1393 * @param typeBuilder
1394 * generated type builder to which is added getter method as
1395 * <code>leaf</code> mapping
1397 * leaf schema node which is mapped as getter method which is
1398 * added to <code>typeBuilder</code>
1400 * Module in which type was defined
1401 * @return boolean value
1403 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1405 * <li>true - in other cases</li>
1408 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1409 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1413 final String leafName = leaf.getQName().getLocalName();
1414 if (leafName == null) {
1418 final Module parentModule = findParentModule(schemaContext, leaf);
1419 Type returnType = null;
1421 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1422 if (isInnerType(leaf, typeDef)) {
1423 if (typeDef instanceof EnumTypeDefinition) {
1424 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1425 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1426 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1427 typeBuilder, module);
1428 if (enumBuilder != null) {
1429 returnType = enumBuilder.toInstance(typeBuilder);
1431 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1432 } else if (typeDef instanceof UnionTypeDefinition) {
1433 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1434 if (genTOBuilder != null) {
1435 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1436 // Store the inner type within the union so that we can find the reference for it
1437 genCtx.get(module).addInnerTypedefType(typeDef.getPath(), returnType);
1439 } else if (typeDef instanceof BitsTypeDefinition) {
1440 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1441 if (genTOBuilder != null) {
1442 returnType = genTOBuilder.toInstance();
1445 // It is constrained version of already declared type (inner declared type exists,
1446 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1447 // In order to get proper class we need to look up closest derived type
1448 // and apply restrictions from leaf type
1449 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1450 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1454 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1455 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1458 if (returnType == null) {
1462 if (typeDef instanceof EnumTypeDefinition) {
1463 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1466 final String leafDesc = leaf.getDescription().orElse("");
1467 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType,
1469 processContextRefExtension(leaf, getter, parentModule);
1473 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1474 // Returns DerivedType in case of new parser.
1475 final TypeDefinition<?> baseType = typeDef.getBaseType();
1476 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1479 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1480 final Module module) {
1481 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1482 final QName nodeType = node.getNodeType();
1483 if ("context-reference".equals(nodeType.getLocalName())) {
1484 final String nodeParam = node.getNodeParameter();
1485 IdentitySchemaNode identity = null;
1486 String basePackageName = null;
1487 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1488 final Iterator<String> iterator = splittedElement.iterator();
1489 final int length = Iterables.size(splittedElement);
1491 identity = findIdentityByName(module.getIdentities(), iterator.next());
1492 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1493 } else if (length == 2) {
1494 final String prefix = iterator.next();
1495 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1496 if (dependentModule == null) {
1497 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1500 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1501 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1503 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1506 if (identity == null) {
1507 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1511 final Class<RoutingContext> clazz = RoutingContext.class;
1512 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1513 clazz.getSimpleName());
1514 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1515 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1516 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1521 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1522 for (final IdentitySchemaNode id : identities) {
1523 if (id.getQName().getLocalName().equals(name)) {
1530 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1531 for (final ModuleImport imp : imports) {
1532 if (imp.getPrefix().equals(prefix)) {
1533 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1539 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1540 final boolean isReadOnly, final Module module) {
1541 if (leaf != null && toBuilder != null) {
1543 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1544 if (typeDef instanceof UnionTypeDefinition) {
1545 // GeneratedType for this type definition should have be already created
1546 final QName qname = typeDef.getQName();
1547 final Module unionModule = schemaContext.findModule(qname.getModule()).orElse(null);
1548 final ModuleContext mc = genCtx.get(unionModule);
1549 returnType = mc.getTypedefs().get(typeDef.getPath());
1550 if (returnType == null) {
1551 // This may still be an inner type, try to find it
1552 returnType = mc.getInnerType(typeDef.getPath());
1554 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1555 // Annonymous enumeration (already generated, since it is inherited via uses).
1556 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1557 QName qname = originalLeaf.getQName();
1558 final Module enumModule = schemaContext.findModule(qname.getModule()).orElse(null);
1559 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1561 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1563 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1569 * Converts <code>leaf</code> schema node to property of generated TO
1573 * generated TO builder to which is <code>leaf</code> added as
1576 * leaf schema node which is added to <code>toBuilder</code> as
1581 * boolean value which says if leaf property is|isn't read only
1582 * @return boolean value
1584 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1585 * name equals null or if leaf is added by <i>uses</i>.</li>
1586 * <li>true - other cases</li>
1589 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1590 final Type returnType, final boolean isReadOnly) {
1591 if (returnType == null) {
1594 final String leafName = leaf.getQName().getLocalName();
1595 final String leafDesc = encodeAngleBrackets(leaf.getDescription().orElse(null));
1596 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1597 propBuilder.setReadOnly(isReadOnly);
1598 propBuilder.setReturnType(returnType);
1599 propBuilder.setComment(leafDesc);
1600 toBuilder.addEqualsIdentity(propBuilder);
1601 toBuilder.addHashIdentity(propBuilder);
1602 toBuilder.addToStringProperty(propBuilder);
1607 * Converts <code>node</code> leaf list schema node to getter method of
1608 * <code>typeBuilder</code>.
1610 * @param typeBuilder
1611 * generated type builder to which is <code>node</code> added as
1614 * leaf list schema node which is added to
1615 * <code>typeBuilder</code> as getter method
1616 * @param module module
1617 * @return boolean value
1619 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1620 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1621 * <li>false - other cases</li>
1624 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1625 final Module module) {
1626 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1630 final QName nodeName = node.getQName();
1632 final TypeDefinition<?> typeDef = node.getType();
1633 final Module parentModule = findParentModule(schemaContext, node);
1635 Type returnType = null;
1636 if (typeDef.getBaseType() == null) {
1637 if (typeDef instanceof EnumTypeDefinition) {
1638 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1639 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1640 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1641 typeBuilder,module);
1642 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1643 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1644 } else if (typeDef instanceof UnionTypeDefinition) {
1645 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1646 if (genTOBuilder != null) {
1647 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1649 } else if (typeDef instanceof BitsTypeDefinition) {
1650 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1651 returnType = genTOBuilder.toInstance();
1653 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1654 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1657 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1658 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1661 final ParameterizedType listType = Types.listTypeFor(returnType);
1662 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription().orElse(null), listType,
1667 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1668 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1669 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1670 genTOBuilder.getName());
1671 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription().orElse(null));
1673 returnType.setDescription(typedefDescription);
1674 returnType.setReference(typeDef.getReference().orElse(null));
1675 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1676 returnType.setModuleName(parentModule.getName());
1678 genTOBuilder.setTypedef(true);
1679 genTOBuilder.setIsUnion(true);
1680 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1684 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1687 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1688 method.setReturnType(returnType);
1689 method.addParameter(Types.STRING, "defaultValue");
1690 method.setAccessModifier(AccessModifier.PUBLIC);
1691 method.setStatic(true);
1693 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1694 if (types == null) {
1695 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1696 Sets.newHashSet(unionBuilder.toInstance()));
1698 types.add(unionBuilder.toInstance());
1700 return returnType.toInstance();
1703 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1704 final String outerCls = Types.getOuterClassName(genTOBuilder);
1705 final StringBuilder name;
1706 if (outerCls != null) {
1707 name = new StringBuilder(outerCls);
1709 name = new StringBuilder();
1711 name.append(genTOBuilder.getName());
1712 name.append("Builder");
1713 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1714 unionBuilder.setIsUnionBuilder(true);
1715 return unionBuilder;
1718 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1719 final Module module) {
1720 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1724 * Instantiates generated type builder with <code>packageName</code> and
1725 * <code>schemaNode</code>.
1727 * The new builder always implements
1728 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1729 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1730 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1732 * If <code>schemaNode</code> is instance of
1733 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1734 * DataNodeContainer} it can also implement nodes which are specified in
1737 * @param packageName
1738 * string with the name of the package to which
1739 * <code>schemaNode</code> belongs.
1741 * schema node for which is created generated type builder
1743 * parent type (can be null)
1744 * @return generated type builder <code>schemaNode</code>
1746 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1747 final Type parent, final Module module) {
1748 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1749 if (parent == null) {
1750 it.addImplementsType(DATA_OBJECT);
1752 it.addImplementsType(BindingTypes.childOf(parent));
1754 if (!(schemaNode instanceof GroupingDefinition)) {
1755 it.addImplementsType(augmentable(it));
1758 if (schemaNode instanceof DataNodeContainer) {
1759 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1760 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1767 * Wraps the calling of the same overloaded method.
1769 * @param packageName
1770 * string with the package name to which returning generated type
1773 * schema node which provide data about the schema node name
1774 * @return generated type builder for <code>schemaNode</code>
1776 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1777 return addRawInterfaceDefinition(packageName, schemaNode, "");
1781 * Returns reference to generated type builder for specified
1782 * <code>schemaNode</code> with <code>packageName</code>.
1784 * Firstly the generated type builder is searched in
1785 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1786 * found it is created and added to <code>genTypeBuilders</code>.
1788 * @param packageName
1789 * string with the package name to which returning generated type
1792 * schema node which provide data about the schema node name
1794 * return type name prefix
1795 * @return generated type builder for <code>schemaNode</code>
1796 * @throws IllegalArgumentException
1798 * <li>if <code>schemaNode</code> is null</li>
1799 * <li>if <code>packageName</code> is null</li>
1800 * <li>if QName of schema node is null</li>
1801 * <li>if schemaNode name is null</li>
1805 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1806 final String prefix) {
1807 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1808 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1809 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1810 final String schemaNodeName = schemaNode.getQName().getLocalName();
1811 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1814 if (prefix == null) {
1815 genTypeName = BindingMapping.getClassName(schemaNodeName);
1817 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1820 // FIXME: Validation of name conflict
1821 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1822 final Module module = findParentModule(schemaContext, schemaNode);
1823 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1824 newType.addComment(schemaNode.getDescription().orElse(null));
1825 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1826 newType.setReference(schemaNode.getReference().orElse(null));
1827 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1828 newType.setModuleName(module.getName());
1830 if (!genTypeBuilders.containsKey(packageName)) {
1831 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1832 builders.put(genTypeName, newType);
1833 genTypeBuilders.put(packageName, builders);
1835 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1836 if (!builders.containsKey(genTypeName)) {
1837 builders.put(genTypeName, newType);
1844 * Creates the name of the getter method name from <code>localName</code>.
1847 * string with the name of the getter method
1850 * @return string with the name of the getter method for
1851 * <code>methodName</code> in JAVA method format
1853 public static String getterMethodName(final String localName, final Type returnType) {
1854 final StringBuilder method = new StringBuilder();
1855 if (BOOLEAN.equals(returnType)) {
1856 method.append("is");
1858 method.append("get");
1860 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1861 method.append(name);
1862 return method.toString();
1866 * Created a method signature builder as part of
1867 * <code>interfaceBuilder</code>.
1869 * The method signature builder is created for the getter method of
1870 * <code>schemaNodeName</code>. Also <code>comment</code> and
1871 * <code>returnType</code> information are added to the builder.
1873 * @param interfaceBuilder
1874 * generated type builder for which the getter method should be
1876 * @param schemaNodeName
1877 * string with schema node name. The name will be the part of the
1878 * getter method name.
1880 * string with comment for the getter method
1882 * type which represents the return type of the getter method
1884 * status from yang file, for deprecated annotation
1885 * @return method signature builder which represents the getter method of
1886 * <code>interfaceBuilder</code>
1888 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1889 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1890 final MethodSignatureBuilder getMethod = interfaceBuilder
1891 .addMethod(getterMethodName(schemaNodeName, returnType));
1892 if (status == Status.DEPRECATED) {
1893 getMethod.addAnnotation("", "Deprecated");
1895 getMethod.setComment(encodeAngleBrackets(comment));
1896 getMethod.setReturnType(returnType);
1901 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1902 * or to <code>genTOBuilder</code> as property.
1904 * @param basePackageName
1905 * string contains the module package name
1907 * data schema node which should be added as getter method to
1908 * <code>typeBuilder</code> or as a property to
1909 * <code>genTOBuilder</code> if is part of the list key
1910 * @param typeBuilder
1911 * generated type builder for the list schema node
1912 * @param genTOBuilder
1913 * generated TO builder for the list keys
1915 * list of string which contains names of the list keys
1918 * @throws IllegalArgumentException
1920 * <li>if <code>schemaNode</code> equals null</li>
1921 * <li>if <code>typeBuilder</code> equals null</li>
1924 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1925 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1926 final Module module) {
1927 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1928 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1930 if (schemaNode instanceof LeafSchemaNode) {
1931 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1932 final String leafName = leaf.getQName().getLocalName();
1933 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, module);
1934 if (listKeys.contains(leafName)) {
1936 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1938 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1941 } else if (!schemaNode.isAddedByUses()) {
1942 if (schemaNode instanceof LeafListSchemaNode) {
1943 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1944 } else if (schemaNode instanceof ContainerSchemaNode) {
1945 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1946 } else if (schemaNode instanceof ChoiceSchemaNode) {
1947 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1948 } else if (schemaNode instanceof ListSchemaNode) {
1949 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1954 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1955 final GeneratedTOBuilder genTOBuilder) {
1956 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1958 if (genTOBuilder != null) {
1959 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1960 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1961 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1966 * Selects the names of the list keys from <code>list</code> and returns
1967 * them as the list of the strings
1970 * of string with names of the list keys
1971 * @return list of string which represents names of the list keys. If the
1972 * <code>list</code> contains no keys then the empty list is
1975 private static List<String> listKeys(final ListSchemaNode list) {
1976 final List<String> listKeys = new ArrayList<>();
1978 final List<QName> keyDefinition = list.getKeyDefinition();
1979 if (keyDefinition != null) {
1980 for (final QName keyDef : keyDefinition) {
1981 listKeys.add(keyDef.getLocalName());
1988 * Generates for the <code>list</code> which contains any list keys special
1989 * generated TO builder.
1991 * @param packageName
1992 * string with package name to which the list belongs
1994 * list schema node which is source of data about the list name
1995 * @return generated TO builder which represents the keys of the
1996 * <code>list</code> or null if <code>list</code> is null or list of
1997 * key definitions is null or empty.
1999 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
2000 GeneratedTOBuilder genTOBuilder = null;
2001 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
2002 final String listName = list.getQName().getLocalName() + "Key";
2003 final String genTOName = BindingMapping.getClassName(listName);
2004 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
2006 return genTOBuilder;
2010 * Builds generated TO builders for <code>typeDef</code> of type
2011 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
2012 * also added to <code>typeBuilder</code> as enclosing transfer object.
2014 * If more then one generated TO builder is created for enclosing then all
2015 * of the generated TO builders are added to <code>typeBuilder</code> as
2016 * enclosing transfer objects.
2019 * type definition which can be of type <code>UnionType</code> or
2020 * <code>BitsTypeDefinition</code>
2021 * @param typeBuilder
2022 * generated type builder to which is added generated TO created
2023 * from <code>typeDef</code>
2025 * string with name for generated TO builder
2026 * @param parentModule
2028 * @return generated TO builder for <code>typeDef</code>
2030 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2031 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2032 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2033 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2034 final String packageName = typeBuilder.getFullyQualifiedName();
2035 if (typeDef instanceof UnionTypeDefinition) {
2036 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2037 .provideGeneratedTOBuildersForUnionTypeDef(packageName, (UnionTypeDefinition) typeDef,
2038 classNameFromLeaf, leaf);
2039 genTOBuilders.addAll(types);
2041 GeneratedTOBuilder resultTOBuilder;
2042 if (types.isEmpty()) {
2043 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2045 resultTOBuilder = types.remove(0);
2046 for (final GeneratedTOBuilder genTOBuilder : types) {
2047 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2050 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2051 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2052 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2053 resultTOBuilder.addHashIdentity(genPropBuilder);
2054 resultTOBuilder.addToStringProperty(genPropBuilder);
2056 } else if (typeDef instanceof BitsTypeDefinition) {
2057 genTOBuilders.add(((TypeProviderImpl) typeProvider).provideGeneratedTOBuilderForBitsTypeDefinition(
2058 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2060 if (!genTOBuilders.isEmpty()) {
2061 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2062 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2064 return genTOBuilders.get(0);
2071 * Adds the implemented types to type builder.
2073 * The method passes through the list of <i>uses</i> in
2074 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2075 * generated type from {@link ModuleContext#groupings
2076 * allGroupings} which is added as <i>implements type</i> to
2077 * <code>builder</code>
2079 * @param dataNodeContainer
2080 * element which contains the list of used YANG groupings
2082 * builder to which are added implemented types according to
2083 * <code>dataNodeContainer</code>
2084 * @return generated type builder with all implemented types
2086 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2087 final GeneratedTypeBuilder builder) {
2088 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2089 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2090 if (genType == null) {
2091 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2092 + builder.getName());
2095 builder.addImplementsType(genType);
2100 private static boolean isNullOrEmpty(final Collection<?> list) {
2101 return list == null || list.isEmpty();
2104 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2105 final StringBuilder sb = new StringBuilder();
2107 if (!isNullOrEmpty(schemaNodes)) {
2108 final SchemaNode node = schemaNodes.iterator().next();
2110 if (node instanceof RpcDefinition) {
2111 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2112 } else if (node instanceof NotificationDefinition) {
2113 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2116 sb.append(NEW_LINE);
2118 if (verboseClassComments) {
2120 sb.append(NEW_LINE);
2121 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2122 sb.append("</pre>");
2123 sb.append(NEW_LINE);
2126 return replaceAllIllegalChars(sb);
2129 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2130 final StringBuilder sb = new StringBuilder();
2131 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription().orElse(null));
2132 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2134 if (!Strings.isNullOrEmpty(formattedDescription)) {
2135 sb.append(formattedDescription);
2136 sb.append(NEW_LINE);
2139 if (verboseClassComments) {
2140 final Module module = findParentModule(schemaContext, schemaNode);
2141 final StringBuilder linkToBuilderClass = new StringBuilder();
2142 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2143 final String className = namespace[namespace.length - 1];
2145 if (hasBuilderClass(schemaNode)) {
2146 linkToBuilderClass.append(className);
2147 linkToBuilderClass.append("Builder");
2151 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2152 sb.append(module.getName());
2154 sb.append(NEW_LINE);
2156 sb.append(NEW_LINE);
2157 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2158 sb.append("</pre>");
2159 sb.append(NEW_LINE);
2160 sb.append("The schema path to identify an instance is");
2161 sb.append(NEW_LINE);
2163 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2165 sb.append(NEW_LINE);
2167 if (hasBuilderClass(schemaNode)) {
2168 sb.append(NEW_LINE);
2169 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2170 sb.append(NEW_LINE);
2172 sb.append(linkToBuilderClass);
2173 sb.append(NEW_LINE);
2174 if (schemaNode instanceof ListSchemaNode) {
2175 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2176 if (keyDef != null && !keyDef.isEmpty()) {
2178 sb.append(className);
2181 sb.append(NEW_LINE);
2186 return replaceAllIllegalChars(sb);
2189 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2190 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2191 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2197 private String createDescription(final Module module) {
2198 final StringBuilder sb = new StringBuilder();
2199 final String moduleDescription = encodeAngleBrackets(module.getDescription().orElse(null));
2200 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2202 if (!Strings.isNullOrEmpty(formattedDescription)) {
2203 sb.append(formattedDescription);
2204 sb.append(NEW_LINE);
2207 if (verboseClassComments) {
2209 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2210 sb.append(module.getName());
2212 sb.append(NEW_LINE);
2214 sb.append(NEW_LINE);
2215 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2216 sb.append("</pre>");
2219 return replaceAllIllegalChars(sb);
2222 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2223 for (final ModuleContext ctx : genCtx.values()) {
2224 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2225 if (result != null) {
2232 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2233 for (final ModuleContext ctx : genCtx.values()) {
2234 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2235 if (result != null) {
2242 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2243 for (final ModuleContext ctx : genCtx.values()) {
2244 final GeneratedTypeBuilder result = ctx.getCase(path);
2245 if (result != null) {
2252 public Map<Module, ModuleContext> getModuleContexts() {
2257 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2258 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2259 return ret.isEmpty() ? "" : ret;
2262 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2263 if (status == Status.DEPRECATED) {
2264 builder.addAnnotation("", "Deprecated");