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 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);
1437 } else if (typeDef instanceof BitsTypeDefinition) {
1438 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1439 if (genTOBuilder != null) {
1440 returnType = genTOBuilder.toInstance();
1443 // It is constrained version of already declared type (inner declared type exists,
1444 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1445 // In order to get proper class we need to look up closest derived type
1446 // and apply restrictions from leaf type
1447 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1448 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1452 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1453 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1456 if (returnType == null) {
1460 if (typeDef instanceof EnumTypeDefinition) {
1461 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1464 final String leafDesc = leaf.getDescription().orElse("");
1465 final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType,
1467 processContextRefExtension(leaf, getter, parentModule);
1471 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1472 // Returns DerivedType in case of new parser.
1473 final TypeDefinition<?> baseType = typeDef.getBaseType();
1474 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1477 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1478 final Module module) {
1479 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1480 final QName nodeType = node.getNodeType();
1481 if ("context-reference".equals(nodeType.getLocalName())) {
1482 final String nodeParam = node.getNodeParameter();
1483 IdentitySchemaNode identity = null;
1484 String basePackageName = null;
1485 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1486 final Iterator<String> iterator = splittedElement.iterator();
1487 final int length = Iterables.size(splittedElement);
1489 identity = findIdentityByName(module.getIdentities(), iterator.next());
1490 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1491 } else if (length == 2) {
1492 final String prefix = iterator.next();
1493 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1494 if (dependentModule == null) {
1495 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1498 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1499 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1501 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1504 if (identity == null) {
1505 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1509 final Class<RoutingContext> clazz = RoutingContext.class;
1510 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1511 clazz.getSimpleName());
1512 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1513 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1514 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1519 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1520 for (final IdentitySchemaNode id : identities) {
1521 if (id.getQName().getLocalName().equals(name)) {
1528 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1529 for (final ModuleImport imp : imports) {
1530 if (imp.getPrefix().equals(prefix)) {
1531 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1537 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1538 final boolean isReadOnly, final Module module) {
1539 if (leaf != null && toBuilder != null) {
1541 final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1542 if (typeDef instanceof UnionTypeDefinition) {
1543 // GeneratedType for this type definition should be already
1545 final QName qname = typeDef.getQName();
1546 final Module unionModule = schemaContext.findModule(qname.getModule()).orElse(null);
1547 final ModuleContext mc = genCtx.get(unionModule);
1548 returnType = mc.getTypedefs().get(typeDef.getPath());
1549 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1550 // Annonymous enumeration (already generated, since it is inherited via uses).
1551 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1552 QName qname = originalLeaf.getQName();
1553 final Module enumModule = schemaContext.findModule(qname.getModule()).orElse(null);
1554 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1556 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1558 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1564 * Converts <code>leaf</code> schema node to property of generated TO
1568 * generated TO builder to which is <code>leaf</code> added as
1571 * leaf schema node which is added to <code>toBuilder</code> as
1576 * boolean value which says if leaf property is|isn't read only
1577 * @return boolean value
1579 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1580 * name equals null or if leaf is added by <i>uses</i>.</li>
1581 * <li>true - other cases</li>
1584 private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1585 final Type returnType, final boolean isReadOnly) {
1586 if (returnType == null) {
1589 final String leafName = leaf.getQName().getLocalName();
1590 final String leafDesc = encodeAngleBrackets(leaf.getDescription().orElse(null));
1591 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1592 propBuilder.setReadOnly(isReadOnly);
1593 propBuilder.setReturnType(returnType);
1594 propBuilder.setComment(leafDesc);
1595 toBuilder.addEqualsIdentity(propBuilder);
1596 toBuilder.addHashIdentity(propBuilder);
1597 toBuilder.addToStringProperty(propBuilder);
1602 * Converts <code>node</code> leaf list schema node to getter method of
1603 * <code>typeBuilder</code>.
1605 * @param typeBuilder
1606 * generated type builder to which is <code>node</code> added as
1609 * leaf list schema node which is added to
1610 * <code>typeBuilder</code> as getter method
1611 * @param module module
1612 * @return boolean value
1614 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1615 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1616 * <li>false - other cases</li>
1619 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1620 final Module module) {
1621 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1625 final QName nodeName = node.getQName();
1627 final TypeDefinition<?> typeDef = node.getType();
1628 final Module parentModule = findParentModule(schemaContext, node);
1630 Type returnType = null;
1631 if (typeDef.getBaseType() == null) {
1632 if (typeDef instanceof EnumTypeDefinition) {
1633 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1634 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1635 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1636 typeBuilder,module);
1637 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1638 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1639 } else if (typeDef instanceof UnionTypeDefinition) {
1640 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1641 if (genTOBuilder != null) {
1642 returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1644 } else if (typeDef instanceof BitsTypeDefinition) {
1645 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1646 returnType = genTOBuilder.toInstance();
1648 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1649 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1652 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1653 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1656 final ParameterizedType listType = Types.listTypeFor(returnType);
1657 constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription().orElse(null), listType,
1662 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1663 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1664 final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1665 genTOBuilder.getName());
1666 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription().orElse(null));
1668 returnType.setDescription(typedefDescription);
1669 returnType.setReference(typeDef.getReference().orElse(null));
1670 returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1671 returnType.setModuleName(parentModule.getName());
1673 genTOBuilder.setTypedef(true);
1674 genTOBuilder.setIsUnion(true);
1675 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1679 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1682 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1683 method.setReturnType(returnType);
1684 method.addParameter(Types.STRING, "defaultValue");
1685 method.setAccessModifier(AccessModifier.PUBLIC);
1686 method.setStatic(true);
1688 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1689 if (types == null) {
1690 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1691 Sets.newHashSet(unionBuilder.toInstance()));
1693 types.add(unionBuilder.toInstance());
1695 return returnType.toInstance();
1698 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1699 final String outerCls = Types.getOuterClassName(genTOBuilder);
1700 final StringBuilder name;
1701 if (outerCls != null) {
1702 name = new StringBuilder(outerCls);
1704 name = new StringBuilder();
1706 name.append(genTOBuilder.getName());
1707 name.append("Builder");
1708 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1709 unionBuilder.setIsUnionBuilder(true);
1710 return unionBuilder;
1713 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1714 final Module module) {
1715 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1719 * Instantiates generated type builder with <code>packageName</code> and
1720 * <code>schemaNode</code>.
1722 * The new builder always implements
1723 * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1724 * If <code>schemaNode</code> is instance of GroupingDefinition it also
1725 * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1727 * If <code>schemaNode</code> is instance of
1728 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1729 * DataNodeContainer} it can also implement nodes which are specified in
1732 * @param packageName
1733 * string with the name of the package to which
1734 * <code>schemaNode</code> belongs.
1736 * schema node for which is created generated type builder
1738 * parent type (can be null)
1739 * @return generated type builder <code>schemaNode</code>
1741 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1742 final Type parent, final Module module) {
1743 final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1744 if (parent == null) {
1745 it.addImplementsType(DATA_OBJECT);
1747 it.addImplementsType(BindingTypes.childOf(parent));
1749 if (!(schemaNode instanceof GroupingDefinition)) {
1750 it.addImplementsType(augmentable(it));
1753 if (schemaNode instanceof DataNodeContainer) {
1754 groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1755 addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1762 * Wraps the calling of the same overloaded method.
1764 * @param packageName
1765 * string with the package name to which returning generated type
1768 * schema node which provide data about the schema node name
1769 * @return generated type builder for <code>schemaNode</code>
1771 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1772 return addRawInterfaceDefinition(packageName, schemaNode, "");
1776 * Returns reference to generated type builder for specified
1777 * <code>schemaNode</code> with <code>packageName</code>.
1779 * Firstly the generated type builder is searched in
1780 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1781 * found it is created and added to <code>genTypeBuilders</code>.
1783 * @param packageName
1784 * string with the package name to which returning generated type
1787 * schema node which provide data about the schema node name
1789 * return type name prefix
1790 * @return generated type builder for <code>schemaNode</code>
1791 * @throws IllegalArgumentException
1793 * <li>if <code>schemaNode</code> is null</li>
1794 * <li>if <code>packageName</code> is null</li>
1795 * <li>if QName of schema node is null</li>
1796 * <li>if schemaNode name is null</li>
1800 private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1801 final String prefix) {
1802 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1803 checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1804 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1805 final String schemaNodeName = schemaNode.getQName().getLocalName();
1806 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1809 if (prefix == null) {
1810 genTypeName = BindingMapping.getClassName(schemaNodeName);
1812 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1815 // FIXME: Validation of name conflict
1816 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1817 final Module module = findParentModule(schemaContext, schemaNode);
1818 qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1819 newType.addComment(schemaNode.getDescription().orElse(null));
1820 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1821 newType.setReference(schemaNode.getReference().orElse(null));
1822 newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1823 newType.setModuleName(module.getName());
1825 if (!genTypeBuilders.containsKey(packageName)) {
1826 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1827 builders.put(genTypeName, newType);
1828 genTypeBuilders.put(packageName, builders);
1830 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1831 if (!builders.containsKey(genTypeName)) {
1832 builders.put(genTypeName, newType);
1839 * Creates the name of the getter method name from <code>localName</code>.
1842 * string with the name of the getter method
1845 * @return string with the name of the getter method for
1846 * <code>methodName</code> in JAVA method format
1848 public static String getterMethodName(final String localName, final Type returnType) {
1849 final StringBuilder method = new StringBuilder();
1850 if (BOOLEAN.equals(returnType)) {
1851 method.append("is");
1853 method.append("get");
1855 final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1856 method.append(name);
1857 return method.toString();
1861 * Created a method signature builder as part of
1862 * <code>interfaceBuilder</code>.
1864 * The method signature builder is created for the getter method of
1865 * <code>schemaNodeName</code>. Also <code>comment</code> and
1866 * <code>returnType</code> information are added to the builder.
1868 * @param interfaceBuilder
1869 * generated type builder for which the getter method should be
1871 * @param schemaNodeName
1872 * string with schema node name. The name will be the part of the
1873 * getter method name.
1875 * string with comment for the getter method
1877 * type which represents the return type of the getter method
1879 * status from yang file, for deprecated annotation
1880 * @return method signature builder which represents the getter method of
1881 * <code>interfaceBuilder</code>
1883 private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1884 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1885 final MethodSignatureBuilder getMethod = interfaceBuilder
1886 .addMethod(getterMethodName(schemaNodeName, returnType));
1887 if (status == Status.DEPRECATED) {
1888 getMethod.addAnnotation("", "Deprecated");
1890 getMethod.setComment(encodeAngleBrackets(comment));
1891 getMethod.setReturnType(returnType);
1896 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1897 * or to <code>genTOBuilder</code> as property.
1899 * @param basePackageName
1900 * string contains the module package name
1902 * data schema node which should be added as getter method to
1903 * <code>typeBuilder</code> or as a property to
1904 * <code>genTOBuilder</code> if is part of the list key
1905 * @param typeBuilder
1906 * generated type builder for the list schema node
1907 * @param genTOBuilder
1908 * generated TO builder for the list keys
1910 * list of string which contains names of the list keys
1913 * @throws IllegalArgumentException
1915 * <li>if <code>schemaNode</code> equals null</li>
1916 * <li>if <code>typeBuilder</code> equals null</li>
1919 private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1920 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1921 final Module module) {
1922 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1923 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1925 if (schemaNode instanceof LeafSchemaNode) {
1926 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1927 final String leafName = leaf.getQName().getLocalName();
1928 final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1929 if (listKeys.contains(leafName)) {
1931 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1933 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1936 } else if (!schemaNode.isAddedByUses()) {
1937 if (schemaNode instanceof LeafListSchemaNode) {
1938 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1939 } else if (schemaNode instanceof ContainerSchemaNode) {
1940 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1941 } else if (schemaNode instanceof ChoiceSchemaNode) {
1942 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1943 } else if (schemaNode instanceof ListSchemaNode) {
1944 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1949 private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1950 final GeneratedTOBuilder genTOBuilder) {
1951 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1953 if (genTOBuilder != null) {
1954 final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1955 constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1956 genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1961 * Selects the names of the list keys from <code>list</code> and returns
1962 * them as the list of the strings
1965 * of string with names of the list keys
1966 * @return list of string which represents names of the list keys. If the
1967 * <code>list</code> contains no keys then the empty list is
1970 private static List<String> listKeys(final ListSchemaNode list) {
1971 final List<String> listKeys = new ArrayList<>();
1973 final List<QName> keyDefinition = list.getKeyDefinition();
1974 if (keyDefinition != null) {
1975 for (final QName keyDef : keyDefinition) {
1976 listKeys.add(keyDef.getLocalName());
1983 * Generates for the <code>list</code> which contains any list keys special
1984 * generated TO builder.
1986 * @param packageName
1987 * string with package name to which the list belongs
1989 * list schema node which is source of data about the list name
1990 * @return generated TO builder which represents the keys of the
1991 * <code>list</code> or null if <code>list</code> is null or list of
1992 * key definitions is null or empty.
1994 private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1995 GeneratedTOBuilder genTOBuilder = null;
1996 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1997 final String listName = list.getQName().getLocalName() + "Key";
1998 final String genTOName = BindingMapping.getClassName(listName);
1999 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
2001 return genTOBuilder;
2005 * Builds generated TO builders for <code>typeDef</code> of type
2006 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
2007 * also added to <code>typeBuilder</code> as enclosing transfer object.
2009 * If more then one generated TO builder is created for enclosing then all
2010 * of the generated TO builders are added to <code>typeBuilder</code> as
2011 * enclosing transfer objects.
2014 * type definition which can be of type <code>UnionType</code> or
2015 * <code>BitsTypeDefinition</code>
2016 * @param typeBuilder
2017 * generated type builder to which is added generated TO created
2018 * from <code>typeDef</code>
2020 * string with name for generated TO builder
2021 * @param parentModule
2023 * @return generated TO builder for <code>typeDef</code>
2025 private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2026 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2027 final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2028 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2029 final String packageName = typeBuilder.getFullyQualifiedName();
2030 if (typeDef instanceof UnionTypeDefinition) {
2031 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2032 .provideGeneratedTOBuildersForUnionTypeDef(packageName, (UnionTypeDefinition) typeDef,
2033 classNameFromLeaf, leaf);
2034 genTOBuilders.addAll(types);
2036 GeneratedTOBuilder resultTOBuilder;
2037 if (types.isEmpty()) {
2038 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2040 resultTOBuilder = types.remove(0);
2041 for (final GeneratedTOBuilder genTOBuilder : types) {
2042 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2045 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2046 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2047 resultTOBuilder.addEqualsIdentity(genPropBuilder);
2048 resultTOBuilder.addHashIdentity(genPropBuilder);
2049 resultTOBuilder.addToStringProperty(genPropBuilder);
2051 } else if (typeDef instanceof BitsTypeDefinition) {
2052 genTOBuilders.add(((TypeProviderImpl) typeProvider).provideGeneratedTOBuilderForBitsTypeDefinition(
2053 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2055 if (!genTOBuilders.isEmpty()) {
2056 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2057 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2059 return genTOBuilders.get(0);
2066 * Adds the implemented types to type builder.
2068 * The method passes through the list of <i>uses</i> in
2069 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2070 * generated type from {@link ModuleContext#groupings
2071 * allGroupings} which is added as <i>implements type</i> to
2072 * <code>builder</code>
2074 * @param dataNodeContainer
2075 * element which contains the list of used YANG groupings
2077 * builder to which are added implemented types according to
2078 * <code>dataNodeContainer</code>
2079 * @return generated type builder with all implemented types
2081 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2082 final GeneratedTypeBuilder builder) {
2083 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2084 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2085 if (genType == null) {
2086 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2087 + builder.getName());
2090 builder.addImplementsType(genType);
2095 private static boolean isNullOrEmpty(final Collection<?> list) {
2096 return list == null || list.isEmpty();
2099 private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2100 final StringBuilder sb = new StringBuilder();
2102 if (!isNullOrEmpty(schemaNodes)) {
2103 final SchemaNode node = schemaNodes.iterator().next();
2105 if (node instanceof RpcDefinition) {
2106 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2107 } else if (node instanceof NotificationDefinition) {
2108 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2111 sb.append(NEW_LINE);
2113 if (verboseClassComments) {
2115 sb.append(NEW_LINE);
2116 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2117 sb.append("</pre>");
2118 sb.append(NEW_LINE);
2121 return replaceAllIllegalChars(sb);
2124 private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2125 final StringBuilder sb = new StringBuilder();
2126 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription().orElse(null));
2127 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2129 if (!Strings.isNullOrEmpty(formattedDescription)) {
2130 sb.append(formattedDescription);
2131 sb.append(NEW_LINE);
2134 if (verboseClassComments) {
2135 final Module module = findParentModule(schemaContext, schemaNode);
2136 final StringBuilder linkToBuilderClass = new StringBuilder();
2137 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2138 final String className = namespace[namespace.length - 1];
2140 if (hasBuilderClass(schemaNode)) {
2141 linkToBuilderClass.append(className);
2142 linkToBuilderClass.append("Builder");
2146 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2147 sb.append(module.getName());
2149 sb.append(NEW_LINE);
2151 sb.append(NEW_LINE);
2152 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2153 sb.append("</pre>");
2154 sb.append(NEW_LINE);
2155 sb.append("The schema path to identify an instance is");
2156 sb.append(NEW_LINE);
2158 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2160 sb.append(NEW_LINE);
2162 if (hasBuilderClass(schemaNode)) {
2163 sb.append(NEW_LINE);
2164 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2165 sb.append(NEW_LINE);
2167 sb.append(linkToBuilderClass);
2168 sb.append(NEW_LINE);
2169 if (schemaNode instanceof ListSchemaNode) {
2170 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2171 if (keyDef != null && !keyDef.isEmpty()) {
2173 sb.append(className);
2176 sb.append(NEW_LINE);
2181 return replaceAllIllegalChars(sb);
2184 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2185 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2186 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2192 private String createDescription(final Module module) {
2193 final StringBuilder sb = new StringBuilder();
2194 final String moduleDescription = encodeAngleBrackets(module.getDescription().orElse(null));
2195 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2197 if (!Strings.isNullOrEmpty(formattedDescription)) {
2198 sb.append(formattedDescription);
2199 sb.append(NEW_LINE);
2202 if (verboseClassComments) {
2204 sb.append("This class represents the following YANG schema fragment defined in module <b>");
2205 sb.append(module.getName());
2207 sb.append(NEW_LINE);
2209 sb.append(NEW_LINE);
2210 sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2211 sb.append("</pre>");
2214 return replaceAllIllegalChars(sb);
2217 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2218 for (final ModuleContext ctx : genCtx.values()) {
2219 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2220 if (result != null) {
2227 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2228 for (final ModuleContext ctx : genCtx.values()) {
2229 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2230 if (result != null) {
2237 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2238 for (final ModuleContext ctx : genCtx.values()) {
2239 final GeneratedTypeBuilder result = ctx.getCase(path);
2240 if (result != null) {
2247 public Map<Module, ModuleContext> getModuleContexts() {
2252 static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2253 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2254 return ret.isEmpty() ? "" : ret;
2257 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2258 if (status == Status.DEPRECATED) {
2259 builder.addAnnotation("", "Deprecated");