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 «module.name» cannot be NULL.");
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 final GeneratedTypeBuilder inType = addRawInterfaceDefinition(basePackageName, input, rpcName);
520 addImplementedInterfaceFromUses(input, inType);
521 inType.addImplementsType(DATA_OBJECT);
522 inType.addImplementsType(augmentable(inType));
523 annotateDeprecatedIfNecessary(rpc.getStatus(), inType);
524 resolveDataSchemaNodes(module, basePackageName, inType, inType, input.getChildNodes());
525 genCtx.get(module).addChildNodeType(input, inType);
526 final GeneratedType inTypeInstance = inType.toInstance();
527 method.addParameter(inTypeInstance, "input");
530 Type outTypeInstance = VOID;
531 //in case of implicit RPC output (StatementSource.CONTEXT),
532 //stay compatible (Future<RpcResult<Void>> return type generated)
533 if (output != null && isExplicitStatement(output)) {
534 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(basePackageName, output, rpcName);
535 addImplementedInterfaceFromUses(output, outType);
536 outType.addImplementsType(DATA_OBJECT);
537 outType.addImplementsType(augmentable(outType));
538 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
539 resolveDataSchemaNodes(module, basePackageName, outType, outType, output.getChildNodes());
540 genCtx.get(module).addChildNodeType(output, outType);
541 outTypeInstance = outType.toInstance();
544 final Type rpcRes = Types.parameterizedTypeFor(Types.typeForClass(RpcResult.class), outTypeInstance);
545 method.setComment(rpcComment);
546 method.setReturnType(Types.parameterizedTypeFor(FUTURE, rpcRes));
550 genCtx.get(module).addTopLevelNodeType(interfaceBuilder);
553 private static boolean isExplicitStatement(final ContainerSchemaNode node) {
554 return node instanceof EffectiveStatement
555 && ((EffectiveStatement<?, ?>) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
559 * Converts all <b>notifications</b> of the module to the list of
560 * <code>Type</code> objects. In addition are to this list added containers
561 * and lists which are part of this notification.
564 * module from which is obtained set of all notification objects
565 * to iterate over them
566 * @throws IllegalArgumentException
568 * <li>if the module equals null</li>
569 * <li>if the name of module equals null</li>
571 * @throws IllegalStateException
572 * if set of notifications from module is null
574 private void notificationsToGenType(final Module module) {
575 checkArgument(module != null, "Module reference cannot be NULL.");
576 checkArgument(module.getName() != null, "Module name cannot be NULL.");
577 final Set<NotificationDefinition> notifications = module.getNotifications();
578 if (notifications.isEmpty()) {
582 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener");
583 listenerInterface.addImplementsType(BindingTypes.NOTIFICATION_LISTENER);
584 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
588 for (final NotificationDefinition notification : notifications) {
589 if (notification != null) {
590 processUsesAugments(notification, module);
592 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
593 notification, null, module);
594 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
595 notificationInterface.addImplementsType(NOTIFICATION);
596 genCtx.get(module).addChildNodeType(notification, notificationInterface);
598 // Notification object
599 resolveDataSchemaNodes(module, basePackageName, notificationInterface, notificationInterface,
600 notification.getChildNodes());
602 listenerInterface.addMethod("on" + notificationInterface.getName())
603 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
604 .setComment(encodeAngleBrackets(notification.getDescription().orElse(null))).setReturnType(Types.VOID);
607 listenerInterface.setDescription(createDescription(notifications, module.getName()));
609 genCtx.get(module).addTopLevelNodeType(listenerInterface);
613 * Converts all <b>identities</b> of the module to the list of
614 * <code>Type</code> objects.
617 * module from which is obtained set of all identity objects to
620 * schema context only used as input parameter for method
621 * {@link BindingGeneratorImpl#identityToGenType}
624 private void allIdentitiesToGenTypes(final Module module, final SchemaContext context) {
625 final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
626 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
628 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
629 for (final IdentitySchemaNode identity : schemaIdentities) {
630 identityToGenType(module, basePackageName, identity, context);
636 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
637 * created transport object builder. If identity contains base identity then
638 * reference to base identity is added to superior identity as its extend.
639 * If identity doesn't contain base identity then only reference to abstract
640 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
641 * BaseIdentity} is added
645 * @param basePackageName
646 * string contains the module package name
648 * IdentitySchemaNode which contains data about identity
650 * SchemaContext which is used to get package and name
651 * information about base of identity
654 private void identityToGenType(final Module module, final String basePackageName,
655 final IdentitySchemaNode identity, final SchemaContext context) {
656 if (identity == null) {
659 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
660 final String genTypeName = BindingMapping.getClassName(identity.getQName());
661 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
662 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
663 if (baseIdentities.isEmpty()) {
664 final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
665 BaseIdentity.class.getSimpleName());
666 newType.setExtendsType(gto.toInstance());
668 final IdentitySchemaNode baseIdentity = baseIdentities.iterator().next();
669 final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
670 final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
672 final String returnTypeName = BindingMapping.getClassName(baseIdentity.getQName());
673 final GeneratedTransferObject gto = new GeneratedTOBuilderImpl(returnTypePkgName, returnTypeName)
675 newType.setExtendsType(gto);
677 newType.setAbstract(true);
678 newType.addComment(identity.getDescription().orElse(null));
679 newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
680 newType.setReference(identity.getReference().orElse(null));
681 newType.setModuleName(module.getName());
682 newType.setSchemaPath(identity.getPath().getPathFromRoot());
684 final QName qname = identity.getQName();
685 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, qname);
687 genCtx.get(module).addIdentityType(identity.getQName(), newType);
690 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
692 return toBuilder.addConstant(typeForClass(QName.class), constantName, name);
696 * Converts all <b>groupings</b> of the module to the list of
697 * <code>Type</code> objects. Firstly are groupings sorted according mutual
698 * dependencies. At least dependent (independent) groupings are in the list
699 * saved at first positions. For every grouping the record is added to map
700 * {@link ModuleContext#groupings allGroupings}
705 * collection of groupings from which types will be generated
708 private void groupingsToGenTypes(final Module module, final Collection<GroupingDefinition> groupings) {
709 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
710 final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
712 for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
713 groupingToGenType(basePackageName, grouping, module);
718 * Converts individual grouping to GeneratedType. Firstly generated type
719 * builder is created and every child node of grouping is resolved to the
722 * @param basePackageName
723 * string contains the module package name
725 * GroupingDefinition which contains data about grouping
729 private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping,
730 final Module module) {
731 final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
732 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
733 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
734 genCtx.get(module).addGroupingType(grouping.getPath(), genType);
735 resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
736 groupingsToGenTypes(module, grouping.getGroupings());
737 processUsesAugments(grouping, module);
741 * Adds enumeration builder created from <code>enumTypeDef</code> to
742 * <code>typeBuilder</code>.
744 * Each <code>enumTypeDef</code> item is added to builder with its name and
748 * EnumTypeDefinition contains enum data
750 * string contains name which will be assigned to enumeration
753 * GeneratedTypeBuilder to which will be enum builder assigned
755 * Module in which type should be generated
756 * @return enumeration builder which contains data from
757 * <code>enumTypeDef</code>
759 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
760 final GeneratedTypeBuilder typeBuilder, final Module module) {
761 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
762 final String enumerationName = BindingMapping.getClassName(enumName);
763 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
764 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null));
765 enumBuilder.setDescription(enumTypedefDescription);
766 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
767 ModuleContext ctx = genCtx.get(module);
768 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
775 * Generates type builder for <code>module</code>.
778 * Module which is source of package name for generated type
781 * string which is added to the module class name representation
783 * @return instance of GeneratedTypeBuilder which represents
784 * <code>module</code>.
785 * @throws IllegalArgumentException
786 * if <code>module</code> is null
788 private GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix) {
789 checkArgument(module != null, "Module reference cannot be NULL.");
790 final String packageName = BindingMapping.getRootPackageName(module.getQNameModule());
791 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
793 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
794 moduleBuilder.setDescription(createDescription(module));
795 moduleBuilder.setReference(module.getReference().orElse(null));
796 moduleBuilder.setModuleName(moduleName);
798 return moduleBuilder;
802 * Converts <code>augSchema</code> to list of <code>Type</code> which
803 * contains generated type for augmentation. In addition there are also
804 * generated types for all containers, list and choices which are child of
805 * <code>augSchema</code> node or a generated types for cases are added if
806 * augmented node is choice.
808 * @param augmentPackageName
809 * string with the name of the package to which the augmentation
812 * AugmentationSchema which is contains data about augmentation
813 * (target path, childs...)
816 * @throws IllegalArgumentException
818 * <li>if <code>augmentPackageName</code> equals null</li>
819 * <li>if <code>augSchema</code> equals null</li>
821 * @throws IllegalStateException
822 * if augment target path is null
824 private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchemaNode augSchema,
825 final Module module) {
826 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
827 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
828 checkState(augSchema.getTargetPath() != null,
829 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
831 processUsesAugments(augSchema, module);
832 final SchemaPath targetPath = augSchema.getTargetPath();
833 SchemaNode targetSchemaNode = null;
835 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
836 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
837 if (targetSchemaNode instanceof DerivableSchemaNode) {
838 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
840 if (targetSchemaNode == null) {
841 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
842 + " in module " + module.getName());
845 if (targetSchemaNode == null) {
846 throw new IllegalArgumentException("augment target not found: " + targetPath);
849 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
850 if (targetTypeBuilder == null) {
851 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
853 if (targetTypeBuilder == null) {
854 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
857 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
858 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
859 targetTypeBuilder.getName());
860 addRawAugmentGenTypeDefinition(module, augmentPackageName, augmentPackageName, targetType, augSchema);
863 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
864 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
868 private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchemaNode augSchema,
869 final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
870 checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
871 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
872 checkState(augSchema.getTargetPath() != null,
873 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
875 processUsesAugments(augSchema, module);
876 final SchemaPath targetPath = augSchema.getTargetPath();
877 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
878 if (targetSchemaNode == null) {
879 throw new IllegalArgumentException("augment target not found: " + targetPath);
882 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
883 if (targetTypeBuilder == null) {
884 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
886 if (targetTypeBuilder == null) {
887 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
890 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
891 String packageName = augmentPackageName;
892 if (usesNodeParent instanceof SchemaNode) {
893 packageName = packageNameForAugmentedGeneratedType(augmentPackageName,
894 ((SchemaNode) usesNodeParent).getPath());
896 addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
899 generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
900 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
905 * Convenient method to find node added by uses statement.
909 * @param parentUsesNode
910 * parent of uses node
911 * @return node from its original location in grouping
913 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
914 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
916 if (!(targetGrouping instanceof GroupingDefinition)) {
917 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
920 SchemaNode result = targetGrouping;
921 for (final QName node : targetPath.getPathFromRoot()) {
922 if (result instanceof DataNodeContainer) {
923 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
924 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
925 } else if (result instanceof ChoiceSchemaNode) {
926 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
929 if (result == null) {
933 if (result instanceof DerivableSchemaNode) {
934 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
935 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
936 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
937 result = originalNode.get();
941 if (result instanceof DataSchemaNode) {
942 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
943 if (resultDataSchemaNode.isAddedByUses()) {
944 // The original node is required, but we have only the copy of
945 // the original node.
946 // Maybe this indicates a bug in Yang parser.
947 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
950 return resultDataSchemaNode;
953 throw new IllegalStateException(
954 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
959 * Returns a generated type builder for an augmentation.
961 * The name of the type builder is equal to the name of augmented node with
962 * serial number as suffix.
966 * @param augmentPackageName
967 * string with contains the package name to which the augment
969 * @param basePackageName
970 * string with the package name to which the augmented node
972 * @param targetTypeRef
975 * augmentation schema which contains data about the child nodes
976 * and uses of augment
977 * @return generated type builder for augment
979 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
980 final String basePackageName, final Type targetTypeRef, final AugmentationSchemaNode augSchema) {
981 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
982 if (augmentBuilders == null) {
983 augmentBuilders = new HashMap<>();
984 genTypeBuilders.put(augmentPackageName, augmentBuilders);
986 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
989 if (augIdentifier != null) {
990 augTypeName = BindingMapping.getClassName(augIdentifier);
992 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
995 final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
997 augTypeBuilder.addImplementsType(DATA_OBJECT);
998 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
999 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
1000 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1002 augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
1003 augmentBuilders.put(augTypeName, augTypeBuilder);
1005 if (!augSchema.getChildNodes().isEmpty()) {
1006 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1009 genCtx.get(module).addAugmentType(augTypeBuilder);
1010 return augTypeBuilder;
1015 * @param unknownSchemaNodes
1016 * @return nodeParameter of UnknownSchemaNode
1018 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1019 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1020 final QName nodeType = unknownSchemaNode.getNodeType();
1021 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1022 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1023 return unknownSchemaNode.getNodeParameter();
1030 * Returns first unique name for the augment generated type builder. The
1031 * generated type builder name for augment consists from name of augmented
1032 * node and serial number of its augmentation.
1035 * map of builders which were created in the package to which the
1036 * augmentation belongs
1037 * @param genTypeName
1038 * string with name of augmented node
1039 * @return string with unique name for augmentation builder
1041 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1043 if (builders != null) {
1044 while (builders.containsKey(genTypeName + index)) {
1048 return genTypeName + index;
1052 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1053 * node for which <code>typeBuilder</code> was created.
1055 * The subnodes aren't mapped to the methods if they are part of grouping or
1056 * augment (in this case are already part of them).
1060 * @param basePackageName
1061 * string contains the module package name
1063 * generated type builder which represents any node. The subnodes
1064 * of this node are added to the <code>typeBuilder</code> as
1065 * methods. The subnode can be of type leaf, leaf-list, list,
1066 * container, choice.
1069 * @param schemaNodes
1070 * set of data schema nodes which are the children of the node
1071 * for which <code>typeBuilder</code> was created
1072 * @return generated type builder which is the same builder as input
1073 * parameter. The getter methods (representing child nodes) could be
1076 private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1077 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1078 if (schemaNodes != null && parent != null) {
1079 for (final DataSchemaNode schemaNode : schemaNodes) {
1080 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1081 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1089 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1090 * node for which <code>typeBuilder</code> was created.
1094 * @param basePackageName
1095 * string contains the module package name
1096 * @param typeBuilder
1097 * generated type builder which represents any node. The subnodes
1098 * of this node are added to the <code>typeBuilder</code> as
1099 * methods. The subnode can be of type leaf, leaf-list, list,
1100 * container, choice.
1103 * @param schemaNodes
1104 * set of data schema nodes which are the children of the node
1105 * for which <code>typeBuilder</code> was created
1106 * @return generated type builder which is the same object as the input
1107 * parameter <code>typeBuilder</code>. The getter method could be
1110 private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1111 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1112 final Iterable<DataSchemaNode> schemaNodes) {
1113 if (schemaNodes != null && typeBuilder != null) {
1114 for (final DataSchemaNode schemaNode : schemaNodes) {
1115 if (!schemaNode.isAugmenting()) {
1116 addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1124 * Adds to <code>typeBuilder</code> a method which is derived from
1125 * <code>schemaNode</code>.
1127 * @param basePackageName
1128 * string with the module package name
1130 * data schema node which is added to <code>typeBuilder</code> as
1132 * @param typeBuilder
1133 * generated type builder to which is <code>schemaNode</code>
1134 * added as a method.
1140 private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1141 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1142 if (node != null && typeBuilder != null) {
1143 if (node instanceof LeafSchemaNode) {
1144 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1145 } else if (node instanceof LeafListSchemaNode) {
1146 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1147 } else if (node instanceof ContainerSchemaNode) {
1148 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1149 } else if (node instanceof ListSchemaNode) {
1150 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1151 } else if (node instanceof ChoiceSchemaNode) {
1152 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1154 // TODO: anyxml not yet supported
1155 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1156 typeBuilder.getFullyQualifiedName());
1162 * Converts <code>choiceNode</code> to the list of generated types for
1163 * choice and its cases.
1165 * The package names for choice and for its cases are created as
1166 * concatenation of the module package (<code>basePackageName</code>) and
1167 * names of all parents node.
1171 * @param basePackageName
1172 * string with the module package name
1176 * choice node which is mapped to generated type. Also child
1177 * nodes - cases are mapped to generated types.
1178 * @throws IllegalArgumentException
1180 * <li>if <code>basePackageName</code> is null</li>
1181 * <li>if <code>choiceNode</code> is null</li>
1184 private void choiceToGeneratedType(final Module module, final String basePackageName,
1185 final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1186 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1187 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1189 if (!choiceNode.isAddedByUses()) {
1190 final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1191 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1192 constructGetter(parent, choiceNode.getQName().getLocalName(),
1193 choiceNode.getDescription().orElse(null), choiceTypeBuilder, choiceNode.getStatus());
1194 choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1195 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1196 genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1197 generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1202 * Converts <code>caseNodes</code> set to list of corresponding generated
1205 * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1206 * created generated type builder. The package names for the builder is
1207 * created as concatenation of the module package (
1208 * <code>basePackageName</code>) and names of all parents nodes of the
1209 * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1210 * between every case builder and <i>choice</i> type
1214 * @param basePackageName
1215 * string with the module package name
1216 * @param refChoiceType
1217 * type which represents superior <i>case</i>
1219 * choice case node which is mapped to generated type
1220 * @throws IllegalArgumentException
1222 * <li>if <code>basePackageName</code> equals null</li>
1223 * <li>if <code>refChoiceType</code> equals null</li>
1224 * <li>if <code>caseNodes</code> equals null</li>
1227 private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1228 final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1229 checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1230 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1231 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1233 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1234 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1235 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1236 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode,
1238 caseTypeBuilder.addImplementsType(refChoiceType);
1239 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1240 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1241 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1242 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1243 if (caseChildNodes != null) {
1244 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1246 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1247 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1249 if (parent instanceof AugmentationSchemaNode) {
1250 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1251 final SchemaPath targetPath = augSchema.getTargetPath();
1252 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1253 if (targetSchemaNode instanceof DataSchemaNode
1254 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1255 if (targetSchemaNode instanceof DerivableSchemaNode) {
1256 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
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 CaseSchemaNode) {
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 CaseSchemaNode node = null;
1343 final String caseLocalName = caseNode.getQName().getLocalName();
1344 if (caseNode instanceof CaseSchemaNode) {
1345 node = (CaseSchemaNode) caseNode;
1346 } else if (findNamedCase(targetNode, 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 = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1356 node = findNamedCase(targetNode, 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 CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1369 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1370 return cases.isEmpty() ? null : cases.get(0);
1373 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1374 // New parser with encapsulated type
1375 if (leaf.getPath().equals(type.getPath())) {
1379 // Embedded type definition with new parser. Also takes care of the old parser with bits
1380 if (leaf.getPath().equals(type.getPath().getParent())) {
1388 * Converts <code>leaf</code> to the getter method which is added to
1389 * <code>typeBuilder</code>.
1391 * @param typeBuilder
1392 * generated type builder to which is added getter method as
1393 * <code>leaf</code> mapping
1395 * leaf schema node which is mapped as getter method which is
1396 * added to <code>typeBuilder</code>
1398 * Module in which type was defined
1399 * @return boolean value
1401 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1403 * <li>true - in other cases</li>
1406 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1407 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1411 final String leafName = leaf.getQName().getLocalName();
1412 if (leafName == null) {
1416 final Module parentModule = findParentModule(schemaContext, leaf);
1417 Type returnType = null;
1419 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1420 if (isInnerType(leaf, typeDef)) {
1421 if (typeDef instanceof EnumTypeDefinition) {
1422 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1423 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1424 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1425 typeBuilder, module);
1426 if (enumBuilder != null) {
1427 returnType = enumBuilder.toInstance(typeBuilder);
1429 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1430 } else if (typeDef instanceof UnionTypeDefinition) {
1431 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1432 if (genTOBuilder != null) {
1433 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1435 } else if (typeDef instanceof BitsTypeDefinition) {
1436 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1437 if (genTOBuilder != null) {
1438 returnType = genTOBuilder.toInstance();
1441 // It is constrained version of already declared type (inner declared type exists,
1442 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1443 // In order to get proper class we need to look up closest derived type
1444 // and apply restrictions from leaf type
1445 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1446 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1450 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1451 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1454 if (returnType == null) {
1458 if (typeDef instanceof EnumTypeDefinition) {
1459 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1462 final String leafDesc = leaf.getDescription().orElse("");
1463 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType,
1465 processContextRefExtension(leaf, getter, parentModule);
1469 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1470 // Returns DerivedType in case of new parser.
1471 final TypeDefinition<?> baseType = typeDef.getBaseType();
1472 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1475 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1476 final Module module) {
1477 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1478 final QName nodeType = node.getNodeType();
1479 if ("context-reference".equals(nodeType.getLocalName())) {
1480 final String nodeParam = node.getNodeParameter();
1481 IdentitySchemaNode identity = null;
1482 String basePackageName = null;
1483 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1484 final Iterator<String> iterator = splittedElement.iterator();
1485 final int length = Iterables.size(splittedElement);
1487 identity = findIdentityByName(module.getIdentities(), iterator.next());
1488 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1489 } else if (length == 2) {
1490 final String prefix = iterator.next();
1491 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1492 if (dependentModule == null) {
1493 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1496 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1497 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1499 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1502 if (identity == null) {
1503 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1507 final Class<RoutingContext> clazz = RoutingContext.class;
1508 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1509 clazz.getSimpleName());
1510 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1511 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1512 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1517 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1518 for (final IdentitySchemaNode id : identities) {
1519 if (id.getQName().getLocalName().equals(name)) {
1526 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1527 for (final ModuleImport imp : imports) {
1528 if (imp.getPrefix().equals(prefix)) {
1529 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1535 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1536 final boolean isReadOnly, final Module module) {
1537 if (leaf != null && toBuilder != null) {
1539 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1540 if (typeDef instanceof UnionTypeDefinition) {
1541 // GeneratedType for this type definition should be already
1543 final QName qname = typeDef.getQName();
1544 final Module unionModule = schemaContext.findModule(qname.getModule()).orElse(null);
1545 final ModuleContext mc = genCtx.get(unionModule);
1546 returnType = mc.getTypedefs().get(typeDef.getPath());
1547 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1548 // Annonymous enumeration (already generated, since it is inherited via uses).
1549 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1550 QName qname = originalLeaf.getQName();
1551 final Module enumModule = schemaContext.findModule(qname.getModule()).orElse(null);
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().orElse(null));
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,
1618 final Module module) {
1619 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1623 final QName nodeName = node.getQName();
1625 final TypeDefinition<?> typeDef = node.getType();
1626 final Module parentModule = findParentModule(schemaContext, node);
1628 Type returnType = null;
1629 if (typeDef.getBaseType() == null) {
1630 if (typeDef instanceof EnumTypeDefinition) {
1631 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1632 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1633 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1634 typeBuilder,module);
1635 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1636 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1637 } else if (typeDef instanceof UnionTypeDefinition) {
1638 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1639 if (genTOBuilder != null) {
1640 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1642 } else if (typeDef instanceof BitsTypeDefinition) {
1643 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1644 returnType = genTOBuilder.toInstance();
1646 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1647 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1650 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1651 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1654 final ParameterizedType listType = Types.listTypeFor(returnType);
1655 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription().orElse(null), listType,
1660 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1661 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1662 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1663 genTOBuilder.getName());
1664 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription().orElse(null));
1666 returnType.setDescription(typedefDescription);
1667 returnType.setReference(typeDef.getReference().orElse(null));
1668 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1669 returnType.setModuleName(parentModule.getName());
1671 genTOBuilder.setTypedef(true);
1672 genTOBuilder.setIsUnion(true);
1673 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1677 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1680 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1681 method.setReturnType(returnType);
1682 method.addParameter(Types.STRING, "defaultValue");
1683 method.setAccessModifier(AccessModifier.PUBLIC);
1684 method.setStatic(true);
1686 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1687 if (types == null) {
1688 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1689 Sets.newHashSet(unionBuilder.toInstance()));
1691 types.add(unionBuilder.toInstance());
1693 return returnType.toInstance();
1696 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1697 final String outerCls = Types.getOuterClassName(genTOBuilder);
1698 final StringBuilder name;
1699 if (outerCls != null) {
1700 name = new StringBuilder(outerCls);
1702 name = new StringBuilder();
1704 name.append(genTOBuilder.getName());
1705 name.append("Builder");
1706 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1707 unionBuilder.setIsUnionBuilder(true);
1708 return unionBuilder;
1711 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1712 final Module module) {
1713 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1717 * Instantiates generated type builder with <code>packageName</code> and
1718 * <code>schemaNode</code>.
1720 * The new builder always implements
1721 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1722 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1723 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1725 * If <code>schemaNode</code> is instance of
1726 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1727 * DataNodeContainer} it can also implement nodes which are specified in
1730 * @param packageName
1731 * string with the name of the package to which
1732 * <code>schemaNode</code> belongs.
1734 * schema node for which is created generated type builder
1736 * parent type (can be null)
1737 * @return generated type builder <code>schemaNode</code>
1739 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1740 final Type parent, final Module module) {
1741 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1742 if (parent == null) {
1743 it.addImplementsType(DATA_OBJECT);
1745 it.addImplementsType(BindingTypes.childOf(parent));
1747 if (!(schemaNode instanceof GroupingDefinition)) {
1748 it.addImplementsType(augmentable(it));
1751 if (schemaNode instanceof DataNodeContainer) {
1752 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1753 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1760 * Wraps the calling of the same overloaded method.
1762 * @param packageName
1763 * string with the package name to which returning generated type
1766 * schema node which provide data about the schema node name
1767 * @return generated type builder for <code>schemaNode</code>
1769 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1770 return addRawInterfaceDefinition(packageName, schemaNode, "");
1774 * Returns reference to generated type builder for specified
1775 * <code>schemaNode</code> with <code>packageName</code>.
1777 * Firstly the generated type builder is searched in
1778 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1779 * found it is created and added to <code>genTypeBuilders</code>.
1781 * @param packageName
1782 * string with the package name to which returning generated type
1785 * schema node which provide data about the schema node name
1787 * return type name prefix
1788 * @return generated type builder for <code>schemaNode</code>
1789 * @throws IllegalArgumentException
1791 * <li>if <code>schemaNode</code> is null</li>
1792 * <li>if <code>packageName</code> is null</li>
1793 * <li>if QName of schema node is null</li>
1794 * <li>if schemaNode name is null</li>
1798 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1799 final String prefix) {
1800 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1801 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1802 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1803 final String schemaNodeName = schemaNode.getQName().getLocalName();
1804 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1807 if (prefix == null) {
1808 genTypeName = BindingMapping.getClassName(schemaNodeName);
1810 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1813 // FIXME: Validation of name conflict
1814 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1815 final Module module = findParentModule(schemaContext, schemaNode);
1816 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1817 newType.addComment(schemaNode.getDescription().orElse(null));
1818 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1819 newType.setReference(schemaNode.getReference().orElse(null));
1820 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1821 newType.setModuleName(module.getName());
1823 if (!genTypeBuilders.containsKey(packageName)) {
1824 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1825 builders.put(genTypeName, newType);
1826 genTypeBuilders.put(packageName, builders);
1828 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1829 if (!builders.containsKey(genTypeName)) {
1830 builders.put(genTypeName, newType);
1837 * Creates the name of the getter method name from <code>localName</code>.
1840 * string with the name of the getter method
1843 * @return string with the name of the getter method for
1844 * <code>methodName</code> in JAVA method format
1846 public static String getterMethodName(final String localName, final Type returnType) {
1847 final StringBuilder method = new StringBuilder();
1848 if (BOOLEAN.equals(returnType)) {
1849 method.append("is");
1851 method.append("get");
1853 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1854 method.append(name);
1855 return method.toString();
1859 * Created a method signature builder as part of
1860 * <code>interfaceBuilder</code>.
1862 * The method signature builder is created for the getter method of
1863 * <code>schemaNodeName</code>. Also <code>comment</code> and
1864 * <code>returnType</code> information are added to the builder.
1866 * @param interfaceBuilder
1867 * generated type builder for which the getter method should be
1869 * @param schemaNodeName
1870 * string with schema node name. The name will be the part of the
1871 * getter method name.
1873 * string with comment for the getter method
1875 * type which represents the return type of the getter method
1877 * status from yang file, for deprecated annotation
1878 * @return method signature builder which represents the getter method of
1879 * <code>interfaceBuilder</code>
1881 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1882 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1883 final MethodSignatureBuilder getMethod = interfaceBuilder
1884 .addMethod(getterMethodName(schemaNodeName, returnType));
1885 if (status == Status.DEPRECATED) {
1886 getMethod.addAnnotation("", "Deprecated");
1888 getMethod.setComment(encodeAngleBrackets(comment));
1889 getMethod.setReturnType(returnType);
1894 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1895 * or to <code>genTOBuilder</code> as property.
1897 * @param basePackageName
1898 * string contains the module package name
1900 * data schema node which should be added as getter method to
1901 * <code>typeBuilder</code> or as a property to
1902 * <code>genTOBuilder</code> if is part of the list key
1903 * @param typeBuilder
1904 * generated type builder for the list schema node
1905 * @param genTOBuilder
1906 * generated TO builder for the list keys
1908 * list of string which contains names of the list keys
1911 * @throws IllegalArgumentException
1913 * <li>if <code>schemaNode</code> equals null</li>
1914 * <li>if <code>typeBuilder</code> equals null</li>
1917 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1918 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1919 final Module module) {
1920 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1921 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1923 if (schemaNode instanceof LeafSchemaNode) {
1924 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1925 final String leafName = leaf.getQName().getLocalName();
1926 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1927 if (listKeys.contains(leafName)) {
1929 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1931 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1934 } else if (!schemaNode.isAddedByUses()) {
1935 if (schemaNode instanceof LeafListSchemaNode) {
1936 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1937 } else if (schemaNode instanceof ContainerSchemaNode) {
1938 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1939 } else if (schemaNode instanceof ChoiceSchemaNode) {
1940 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1941 } else if (schemaNode instanceof ListSchemaNode) {
1942 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1947 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1948 final GeneratedTOBuilder genTOBuilder) {
1949 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1951 if (genTOBuilder != null) {
1952 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1953 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1954 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1959 * Selects the names of the list keys from <code>list</code> and returns
1960 * them as the list of the strings
1963 * of string with names of the list keys
1964 * @return list of string which represents names of the list keys. If the
1965 * <code>list</code> contains no keys then the empty list is
1968 private static List<String> listKeys(final ListSchemaNode list) {
1969 final List<String> listKeys = new ArrayList<>();
1971 final List<QName> keyDefinition = list.getKeyDefinition();
1972 if (keyDefinition != null) {
1973 for (final QName keyDef : keyDefinition) {
1974 listKeys.add(keyDef.getLocalName());
1981 * Generates for the <code>list</code> which contains any list keys special
1982 * generated TO builder.
1984 * @param packageName
1985 * string with package name to which the list belongs
1987 * list schema node which is source of data about the list name
1988 * @return generated TO builder which represents the keys of the
1989 * <code>list</code> or null if <code>list</code> is null or list of
1990 * key definitions is null or empty.
1992 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1993 GeneratedTOBuilder genTOBuilder = null;
1994 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1995 final String listName = list.getQName().getLocalName() + "Key";
1996 final String genTOName = BindingMapping.getClassName(listName);
1997 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1999 return genTOBuilder;
2003 * Builds generated TO builders for <code>typeDef</code> of type
2004 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
2005 * also added to <code>typeBuilder</code> as enclosing transfer object.
2007 * If more then one generated TO builder is created for enclosing then all
2008 * of the generated TO builders are added to <code>typeBuilder</code> as
2009 * enclosing transfer objects.
2012 * type definition which can be of type <code>UnionType</code> or
2013 * <code>BitsTypeDefinition</code>
2014 * @param typeBuilder
2015 * generated type builder to which is added generated TO created
2016 * from <code>typeDef</code>
2018 * string with name for generated TO builder
2019 * @param parentModule
2021 * @return generated TO builder for <code>typeDef</code>
2023 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2024 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2025 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2026 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2027 final String packageName = typeBuilder.getFullyQualifiedName();
2028 if (typeDef instanceof UnionTypeDefinition) {
2029 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2030 .provideGeneratedTOBuildersForUnionTypeDef(packageName, (UnionTypeDefinition) typeDef,
2031 classNameFromLeaf, leaf);
2032 genTOBuilders.addAll(types);
2034 GeneratedTOBuilder resultTOBuilder;
2035 if (types.isEmpty()) {
2036 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2038 resultTOBuilder = types.remove(0);
2039 for (final GeneratedTOBuilder genTOBuilder : types) {
2040 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2043 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2044 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2045 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2046 resultTOBuilder.addHashIdentity(genPropBuilder);
2047 resultTOBuilder.addToStringProperty(genPropBuilder);
2049 } else if (typeDef instanceof BitsTypeDefinition) {
2050 genTOBuilders.add(((TypeProviderImpl) typeProvider).provideGeneratedTOBuilderForBitsTypeDefinition(
2051 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2053 if (!genTOBuilders.isEmpty()) {
2054 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2055 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2057 return genTOBuilders.get(0);
2064 * Adds the implemented types to type builder.
2066 * The method passes through the list of <i>uses</i> in
2067 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2068 * generated type from {@link ModuleContext#groupings
2069 * allGroupings} which is added as <i>implements type</i> to
2070 * <code>builder</code>
2072 * @param dataNodeContainer
2073 * element which contains the list of used YANG groupings
2075 * builder to which are added implemented types according to
2076 * <code>dataNodeContainer</code>
2077 * @return generated type builder with all implemented types
2079 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2080 final GeneratedTypeBuilder builder) {
2081 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2082 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2083 if (genType == null) {
2084 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2085 + builder.getName());
2088 builder.addImplementsType(genType);
2093 private static boolean isNullOrEmpty(final Collection<?> list) {
2094 return list == null || list.isEmpty();
2097 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2098 final StringBuilder sb = new StringBuilder();
2100 if (!isNullOrEmpty(schemaNodes)) {
2101 final SchemaNode node = schemaNodes.iterator().next();
2103 if (node instanceof RpcDefinition) {
2104 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2105 } else if (node instanceof NotificationDefinition) {
2106 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2109 sb.append(NEW_LINE);
2111 if (verboseClassComments) {
2113 sb.append(NEW_LINE);
2114 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2115 sb.append("</pre>");
2116 sb.append(NEW_LINE);
2119 return replaceAllIllegalChars(sb);
2122 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2123 final StringBuilder sb = new StringBuilder();
2124 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription().orElse(null));
2125 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2127 if (!Strings.isNullOrEmpty(formattedDescription)) {
2128 sb.append(formattedDescription);
2129 sb.append(NEW_LINE);
2132 if (verboseClassComments) {
2133 final Module module = findParentModule(schemaContext, schemaNode);
2134 final StringBuilder linkToBuilderClass = new StringBuilder();
2135 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2136 final String className = namespace[namespace.length - 1];
2138 if (hasBuilderClass(schemaNode)) {
2139 linkToBuilderClass.append(className);
2140 linkToBuilderClass.append("Builder");
2144 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2145 sb.append(module.getName());
2147 sb.append(NEW_LINE);
2149 sb.append(NEW_LINE);
2150 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2151 sb.append("</pre>");
2152 sb.append(NEW_LINE);
2153 sb.append("The schema path to identify an instance is");
2154 sb.append(NEW_LINE);
2156 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2158 sb.append(NEW_LINE);
2160 if (hasBuilderClass(schemaNode)) {
2161 sb.append(NEW_LINE);
2162 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2163 sb.append(NEW_LINE);
2165 sb.append(linkToBuilderClass);
2166 sb.append(NEW_LINE);
2167 if (schemaNode instanceof ListSchemaNode) {
2168 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2169 if (keyDef != null && !keyDef.isEmpty()) {
2171 sb.append(className);
2174 sb.append(NEW_LINE);
2179 return replaceAllIllegalChars(sb);
2182 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2183 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2184 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2190 private String createDescription(final Module module) {
2191 final StringBuilder sb = new StringBuilder();
2192 final String moduleDescription = encodeAngleBrackets(module.getDescription().orElse(null));
2193 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2195 if (!Strings.isNullOrEmpty(formattedDescription)) {
2196 sb.append(formattedDescription);
2197 sb.append(NEW_LINE);
2200 if (verboseClassComments) {
2202 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2203 sb.append(module.getName());
2205 sb.append(NEW_LINE);
2207 sb.append(NEW_LINE);
2208 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2209 sb.append("</pre>");
2212 return replaceAllIllegalChars(sb);
2215 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2216 for (final ModuleContext ctx : genCtx.values()) {
2217 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2218 if (result != null) {
2225 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2226 for (final ModuleContext ctx : genCtx.values()) {
2227 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2228 if (result != null) {
2235 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2236 for (final ModuleContext ctx : genCtx.values()) {
2237 final GeneratedTypeBuilder result = ctx.getCase(path);
2238 if (result != null) {
2245 public Map<Module, ModuleContext> getModuleContexts() {
2250 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2251 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2252 return ret.isEmpty() ? "" : ret;
2255 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2256 if (status == Status.DEPRECATED) {
2257 builder.addAnnotation("", "Deprecated");