2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. 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.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
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.BASE_IDENTITY;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
34 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
35 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
36 import static org.opendaylight.mdsal.binding.model.util.Types.augmentationTypeFor;
37 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
38 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
39 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
40 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
41 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
42 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
43 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
44 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
45 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
47 import com.google.common.base.Splitter;
48 import com.google.common.collect.Iterables;
49 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
50 import java.util.AbstractMap.SimpleImmutableEntry;
51 import java.util.ArrayList;
52 import java.util.Collection;
53 import java.util.Comparator;
54 import java.util.HashMap;
55 import java.util.HashSet;
56 import java.util.Iterator;
57 import java.util.List;
59 import java.util.Optional;
61 import org.eclipse.jdt.annotation.Nullable;
62 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
63 import org.opendaylight.mdsal.binding.model.api.Constant;
64 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
65 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
66 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
67 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
68 import org.opendaylight.mdsal.binding.model.api.Restrictions;
69 import org.opendaylight.mdsal.binding.model.api.Type;
70 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
71 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
72 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
73 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
74 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
75 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
76 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
79 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
80 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
81 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
82 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
83 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
84 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
85 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
86 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
87 import org.opendaylight.yangtools.yang.common.QName;
88 import org.opendaylight.yangtools.yang.common.QNameModule;
89 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
90 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
91 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
96 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
99 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
100 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.Module;
105 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
106 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
107 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
108 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
109 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
111 import org.opendaylight.yangtools.yang.model.api.Status;
112 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
113 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
114 import org.opendaylight.yangtools.yang.model.api.UsesNode;
115 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
116 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
117 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
118 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
119 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
120 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
121 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
122 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
123 import org.slf4j.Logger;
124 import org.slf4j.LoggerFactory;
126 abstract class AbstractTypeGenerator {
127 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
128 private static final Splitter COLON_SPLITTER = Splitter.on(':');
129 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
130 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
131 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
134 * Comparator based on augment target path.
136 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
137 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
138 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
140 while (thisIt.hasNext()) {
141 if (!otherIt.hasNext()) {
145 final int comp = thisIt.next().compareTo(otherIt.next());
151 return otherIt.hasNext() ? -1 : 0;
155 * Constant with the concrete name of identifier.
157 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
160 * Constant with the concrete name of namespace.
162 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
164 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
167 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
168 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
169 * for schema node specified in key part.
171 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
174 * Provide methods for converting YANG types to JAVA types.
176 private final AbstractTypeProvider typeProvider;
179 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
181 private final SchemaContext schemaContext;
184 * Holds renamed elements.
186 private final Map<SchemaNode, JavaTypeName> renames;
188 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
189 final Map<SchemaNode, JavaTypeName> renames) {
190 this.schemaContext = requireNonNull(context);
191 this.typeProvider = requireNonNull(typeProvider);
192 this.renames = requireNonNull(renames);
194 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
195 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
196 for (final Module contextModule : contextModules) {
197 contexts.add(moduleToGenTypes(contextModule));
200 contexts.forEach(this::allAugmentsToGenTypes);
203 final Collection<ModuleContext> moduleContexts() {
204 return genCtx.values();
207 final ModuleContext moduleContext(final QNameModule module) {
208 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
211 final AbstractTypeProvider typeProvider() {
215 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
217 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
219 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
220 Set<? extends SchemaNode> nodes);
222 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
224 private ModuleContext moduleToGenTypes(final Module module) {
225 final ModuleContext context = new ModuleContext(module);
226 genCtx.put(module.getQNameModule(), context);
227 allTypeDefinitionsToGenTypes(context);
228 groupingsToGenTypes(context, module.getGroupings());
229 rpcMethodsToGenType(context);
230 allIdentitiesToGenTypes(context);
231 notificationsToGenType(context);
233 if (!module.getChildNodes().isEmpty()) {
234 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
235 context.addModuleNode(moduleType);
236 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
242 * Converts all extended type definitions of module to the list of
243 * <code>Type</code> objects.
246 * module from which is obtained set of type definitions
247 * @throws IllegalArgumentException
249 * <li>if module is null</li>
250 * <li>if name of module is null</li>
252 * @throws IllegalStateException
253 * if set of type definitions from module is null
255 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
256 final Module module = context.module();
257 checkArgument(module.getName() != null, "Module name cannot be NULL.");
258 final DataNodeIterator it = new DataNodeIterator(module);
259 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
260 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
262 for (final TypeDefinition<?> typedef : typeDefinitions) {
263 if (typedef != null) {
264 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
266 context.addTypedefType(typedef, type);
267 context.addTypeToSchema(type,typedef);
273 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
274 final DataSchemaNode node, final boolean inGrouping) {
275 if (node.isAugmenting() || node.isAddedByUses()) {
278 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
279 defaultImplementedInterace(genType);
280 annotateDeprecatedIfNecessary(node.getStatus(), genType);
282 final Module module = context.module();
283 genType.setModuleName(module.getName());
284 addCodegenInformation(genType, module, node);
285 genType.setSchemaPath(node.getPath());
286 if (node instanceof DataNodeContainer) {
287 context.addChildNodeType(node, genType);
288 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
289 processUsesAugments((DataNodeContainer) node, context, inGrouping);
294 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
295 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
296 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
297 if (genType != null) {
298 constructGetter(parent, genType, node);
299 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
300 actionsToGenType(context, genType, node, null, inGrouping);
304 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
305 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
306 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
307 if (genType != null) {
308 final ParameterizedType listType = listTypeFor(genType);
309 constructGetter(parent, listType, node);
310 constructNonnull(parent, listType, node);
312 final List<String> listKeys = listKeys(node);
313 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
314 if (genTOBuilder != null) {
315 final Type identifierMarker = identifier(genType);
316 final Type identifiableMarker = identifiable(genTOBuilder);
317 genTOBuilder.addImplementsType(identifierMarker);
318 genType.addImplementsType(identifiableMarker);
321 actionsToGenType(context, genType, node, genTOBuilder, inGrouping);
323 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
324 if (!schemaNode.isAugmenting()) {
325 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys, inGrouping);
330 if (genTOBuilder != null) {
331 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
332 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
333 genTOBuilder.setSUID(prop);
336 typeBuildersToGenTypes(context, genType, genTOBuilder);
340 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
341 final boolean inGrouping) {
342 for (final UsesNode usesNode : node.getUses()) {
343 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
344 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
345 processUsesAugments(augment, context, inGrouping);
351 * Converts all <b>augmentation</b> of the module to the list
352 * <code>Type</code> objects.
355 * module from which is obtained list of all augmentation objects
356 * to iterate over them
357 * @throws IllegalArgumentException
359 * <li>if the module is null</li>
360 * <li>if the name of module is null</li>
362 * @throws IllegalStateException
363 * if set of augmentations from module is null
365 private void allAugmentsToGenTypes(final ModuleContext context) {
366 final Module module = context.module();
367 checkArgument(module != null, "Module reference cannot be NULL.");
368 checkArgument(module.getName() != null, "Module name cannot be NULL.");
369 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
371 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
372 augmentationToGenTypes(context, augment);
377 * Returns list of <code>AugmentationSchema</code> objects. The objects are
378 * sorted according to the length of their target path from the shortest to
382 * module from which is obtained list of all augmentation objects
383 * @return list of sorted <code>AugmentationSchema</code> objects obtained
384 * from <code>module</code>
385 * @throws IllegalArgumentException
387 * @throws IllegalStateException
388 * if set of module augmentations is null
390 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
391 checkArgument(module != null, "Module reference cannot be NULL.");
392 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
394 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
395 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
396 sortedAugmentations.sort(AUGMENT_COMP);
398 return sortedAugmentations;
402 * Create GeneratedTypeBuilder object from module argument.
405 * Module object from which builder will be created
406 * @return <code>GeneratedTypeBuilder</code> which is internal
407 * representation of the module
408 * @throws IllegalArgumentException
411 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
412 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
413 final Module module = context.module();
414 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
415 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
417 addCodegenInformation(moduleDataTypeBuilder, module);
418 return moduleDataTypeBuilder;
421 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
422 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
423 for (final ActionDefinition action : parentSchema.getActions()) {
424 final GeneratedType input;
425 final GeneratedType output;
426 if (action.isAddedByUses()) {
427 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
428 input = context.getChildNode(orig.getInput().getPath()).build();
429 output = context.getChildNode(orig.getOutput().getPath()).build();
431 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
432 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
435 if (!(parentSchema instanceof GroupingDefinition)) {
436 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
437 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
438 // and do not capture an actual instantiation.
439 final QName qname = action.getQName();
440 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
441 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
442 BindingMapping.getClassName(qname)));
443 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
444 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
446 annotateDeprecatedIfNecessary(action.getStatus(), builder);
447 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
448 : action(parent, input, output));
450 addCodegenInformation(builder, context.module(), action);
451 context.addChildNodeType(action, builder);
456 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
457 for (UsesNode uses : parent.getUses()) {
458 final GroupingDefinition grp = findUsedGrouping(uses);
459 final Optional<ActionDefinition> found = grp.getActions().stream()
460 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
461 if (found.isPresent()) {
462 final ActionDefinition result = found.get();
463 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
467 return Optional.empty();
470 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
471 final ContainerSchemaNode schema, final boolean inGrouping) {
472 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
473 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
474 return genType.build();
478 * Converts all <b>RPCs</b> input and output substatements of the module
479 * to the list of <code>Type</code> objects. In addition are to containers
480 * and lists which belong to input or output also part of returning list.
483 * module from which is obtained set of all rpc objects to
485 * @throws IllegalArgumentException
487 * <li>if the module is null</li>
488 * <li>if the name of module is null</li>
490 * @throws IllegalStateException
491 * if set of rpcs from module is null
493 private void rpcMethodsToGenType(final ModuleContext context) {
494 final Module module = context.module();
495 checkArgument(module.getName() != null, "Module name cannot be NULL.");
496 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
497 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
498 if (rpcDefinitions.isEmpty()) {
502 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
503 interfaceBuilder.addImplementsType(RPC_SERVICE);
505 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
507 for (final RpcDefinition rpc : rpcDefinitions) {
509 final String rpcName = BindingMapping.getClassName(rpc.getQName());
510 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
511 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
513 // Do not refer to annotation class, as it may not be available at runtime
514 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
515 addComment(method, rpc);
517 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
518 method.setReturnType(listenableFutureTypeFor(
519 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
523 context.addTopLevelNodeType(interfaceBuilder);
526 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
527 final ContainerSchemaNode schema, final Type type) {
528 processUsesAugments(schema, context, false);
529 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
530 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
532 addImplementedInterfaceFromUses(schema, outType);
533 outType.addImplementsType(type);
534 outType.addImplementsType(augmentable(outType));
535 defaultImplementedInterace(outType);
536 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
537 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
538 context.addChildNodeType(schema, outType);
539 return outType.build();
543 * Converts all <b>notifications</b> of the module to the list of
544 * <code>Type</code> objects. In addition are to this list added containers
545 * and lists which are part of this notification.
548 * module from which is obtained set of all notification objects
549 * to iterate over them
550 * @throws IllegalArgumentException
552 * <li>if the module equals null</li>
553 * <li>if the name of module equals null</li>
555 * @throws IllegalStateException
556 * if set of notifications from module is null
558 private void notificationsToGenType(final ModuleContext context) {
559 final Module module = context.module();
560 checkArgument(module.getName() != null, "Module name cannot be NULL.");
561 final Set<NotificationDefinition> notifications = module.getNotifications();
562 if (notifications.isEmpty()) {
566 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
567 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
569 for (final NotificationDefinition notification : notifications) {
570 if (notification != null) {
571 processUsesAugments(notification, context, false);
573 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
574 context.modulePackageName(), notification, DATA_OBJECT, context);
575 defaultImplementedInterace(notificationInterface);
576 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
577 notificationInterface.addImplementsType(NOTIFICATION);
578 context.addChildNodeType(notification, notificationInterface);
580 // Notification object
581 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
582 notification.getChildNodes(), false);
584 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
585 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
586 .setReturnType(primitiveVoidType()), notification);
590 addCodegenInformation(listenerInterface, module, "notifications", notifications);
591 context.addTopLevelNodeType(listenerInterface);
595 * Converts all <b>identities</b> of the module to the list of
596 * <code>Type</code> objects.
599 * module from which is obtained set of all identity objects to
601 * @param schemaContext
602 * schema context only used as input parameter for method
603 * {@link BindingGeneratorImpl#identityToGenType}
606 private void allIdentitiesToGenTypes(final ModuleContext context) {
607 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
609 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
610 for (final IdentitySchemaNode identity : schemaIdentities) {
611 identityToGenType(context, identity);
617 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
618 * created transport object builder. If identity contains base identity then
619 * reference to base identity is added to superior identity as its extend.
620 * If identity doesn't contain base identity then only reference to abstract
621 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
622 * BaseIdentity} is added
626 * @param basePackageName
627 * string contains the module package name
629 * IdentitySchemaNode which contains data about identity
631 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
632 if (identity == null) {
636 JavaTypeName name = renames.get(identity);
638 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
639 BindingMapping.getClassName(identity.getQName()));
642 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
643 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
644 if (!baseIdentities.isEmpty()) {
645 for (IdentitySchemaNode baseIdentity : baseIdentities) {
646 JavaTypeName base = renames.get(baseIdentity);
648 final QName qname = baseIdentity.getQName();
649 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
650 BindingMapping.getClassName(qname));
653 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
654 newType.addImplementsType(gto);
657 newType.addImplementsType(BASE_IDENTITY);
660 final Module module = context.module();
661 addCodegenInformation(newType, module, identity);
662 newType.setModuleName(module.getName());
663 newType.setSchemaPath(identity.getPath());
665 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
666 identity.getQName().getLocalName());
668 context.addIdentityType(identity, newType);
671 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
672 final JavaTypeName yangModuleInfo, final String localName) {
673 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
674 new SimpleImmutableEntry<>(yangModuleInfo, localName));
678 * Converts all <b>groupings</b> of the module to the list of
679 * <code>Type</code> objects. Firstly are groupings sorted according mutual
680 * dependencies. At least dependent (independent) groupings are in the list
681 * saved at first positions. For every grouping the record is added to map
682 * {@link ModuleContext#groupings allGroupings}
687 * collection of groupings from which types will be generated
690 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
691 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
692 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
693 // node of grouping is resolved to the method.
694 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
695 narrowImplementedInterface(genType);
696 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
697 context.addGroupingType(grouping, genType);
698 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
699 groupingsToGenTypes(context, grouping.getGroupings());
700 processUsesAugments(grouping, context, true);
701 actionsToGenType(context, genType, grouping, null, true);
706 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
707 * <code>enumTypeDef</code> item is added to builder with its name and value.
709 * @param enumTypeDef EnumTypeDefinition contains enum data
710 * @param enumName string contains name which will be assigned to enumeration builder
711 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
712 * @param module Module in which type should be generated
713 * @return enumeration builder which contains data from <code>enumTypeDef</code>
715 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
716 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
717 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
718 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
719 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
720 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
721 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
728 * Generates type builder for <code>module</code>.
730 * @param module Module which is source of package name for generated type builder
731 * @param postfix string which is added to the module class name representation as suffix
732 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
733 * @throws IllegalArgumentException if <code>module</code> is null
735 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
736 final Module module = context.module();
737 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
738 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
739 JavaTypeName.create(context.modulePackageName(), moduleName));
741 moduleBuilder.setModuleName(moduleName);
742 addCodegenInformation(moduleBuilder, module);
743 return moduleBuilder;
747 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
748 * In addition there are also generated types for all containers, list and choices which are child of
749 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
751 * @param augmentPackageName string with the name of the package to which the augmentation belongs
752 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
753 * @param module current module
754 * @throws IllegalArgumentException
756 * <li>if <code>augmentPackageName</code> equals null</li>
757 * <li>if <code>augSchema</code> equals null</li>
759 * @throws IllegalStateException
760 * if augment target path is null
762 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
763 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
764 checkState(augSchema.getTargetPath() != null,
765 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
767 processUsesAugments(augSchema, context, false);
768 final SchemaPath targetPath = augSchema.getTargetPath();
769 SchemaNode targetSchemaNode = null;
771 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
772 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
773 if (targetSchemaNode instanceof DerivableSchemaNode) {
774 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
776 if (targetSchemaNode == null) {
777 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
778 + " in module " + context.module().getName());
781 if (targetSchemaNode == null) {
782 throw new IllegalArgumentException("augment target not found: " + targetPath);
785 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
786 if (targetTypeBuilder == null) {
787 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
789 if (targetTypeBuilder == null) {
790 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
793 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
794 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
795 addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
798 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
799 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
803 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
804 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
805 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
806 checkState(augSchema.getTargetPath() != null,
807 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
809 processUsesAugments(augSchema, context, inGrouping);
810 final SchemaPath targetPath = augSchema.getTargetPath();
811 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
812 if (targetSchemaNode == null) {
813 throw new IllegalArgumentException("augment target not found: " + targetPath);
816 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
817 if (targetTypeBuilder == null) {
818 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
820 if (targetTypeBuilder == null) {
821 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
824 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
825 if (usesNodeParent instanceof SchemaNode) {
826 addRawAugmentGenTypeDefinition(context,
827 packageNameForAugmentedGeneratedType(context.modulePackageName(),
828 ((SchemaNode) usesNodeParent).getPath()),
829 targetTypeBuilder.build(), augSchema, inGrouping);
831 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
834 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
835 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
839 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
840 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
842 if (targetGrouping instanceof GroupingDefinition) {
843 return (GroupingDefinition) targetGrouping;
846 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
850 * Convenient method to find node added by uses statement.
852 * @param targetPath node path
853 * @param parentUsesNode parent of uses node
854 * @return node from its original location in grouping
856 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
857 SchemaNode result = findUsedGrouping(parentUsesNode);
858 for (final QName node : targetPath.getPathFromRoot()) {
859 if (result instanceof DataNodeContainer) {
860 final QName resultNode = node.withModule(result.getQName().getModule());
861 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
862 } else if (result instanceof ChoiceSchemaNode) {
863 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
866 if (result == null) {
870 if (result instanceof DerivableSchemaNode) {
871 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
872 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
873 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
874 result = originalNode.get();
878 if (result instanceof DataSchemaNode) {
879 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
880 if (resultDataSchemaNode.isAddedByUses()) {
881 // The original node is required, but we have only the copy of
882 // the original node.
883 // Maybe this indicates a bug in Yang parser.
884 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
887 return resultDataSchemaNode;
890 throw new IllegalStateException(
891 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
896 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
897 * of augmented node with serial number as suffix.
899 * @param context current module
900 * @param augmentPackageName string with contains the package name to which the augment belongs
901 * @param basePackageName string with the package name to which the augmented node belongs
902 * @param targetTypeRef target type
903 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
904 * @return generated type builder for augment
906 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
907 final String augmentPackageName, final Type targetTypeRef,
908 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
909 Map<String, GeneratedTypeBuilder> augmentBuilders =
910 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
911 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
914 if (augIdentifier != null) {
915 augTypeName = BindingMapping.getClassName(augIdentifier);
917 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
920 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
921 JavaTypeName.create(augmentPackageName, augTypeName));
923 augTypeBuilder.addImplementsType(DATA_OBJECT);
924 defaultImplementedInterace(augTypeBuilder);
926 augTypeBuilder.addImplementsType(augmentationTypeFor(targetTypeRef));
927 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
928 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
930 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
931 augmentBuilders.put(augTypeName, augTypeBuilder);
933 if (!augSchema.getChildNodes().isEmpty()) {
934 context.addTypeToAugmentation(augTypeBuilder, augSchema);
937 context.addAugmentType(augTypeBuilder);
938 return augTypeBuilder;
941 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
942 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
943 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
947 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
948 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
949 final QName nodeType = unknownSchemaNode.getNodeType();
950 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
951 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
952 return unknownSchemaNode.getNodeParameter();
959 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
960 * consists from name of augmented node and serial number of its augmentation.
962 * @param builders map of builders which were created in the package to which the augmentation belongs
963 * @param genTypeName string with name of augmented node
964 * @return string with unique name for augmentation builder
966 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
968 if (builders != null) {
969 while (builders.containsKey(genTypeName + index)) {
973 return genTypeName + index;
977 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
978 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
979 * already part of them).
981 * @param module current module
982 * @param parent generated type builder which represents any node. The subnodes of this node are added
983 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
985 * @param childOf parent type
986 * @param schemaNodes set of data schema nodes which are the children of the node for which
987 * <code>typeBuilder</code> was created
988 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
989 * child nodes) could be added to it.
991 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
992 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
993 if (schemaNodes != null && parent != null) {
994 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
995 for (final DataSchemaNode schemaNode : schemaNodes) {
996 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
997 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1005 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1008 * @param module current module
1009 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1010 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1011 * container, choice.
1012 * @param childOf parent type
1013 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1015 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1016 * The getter method could be added to it.
1018 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1019 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1020 final boolean inGrouping) {
1021 if (schemaNodes != null && typeBuilder != null) {
1022 final Type baseInterface = childOf(typeBuilder);
1023 for (final DataSchemaNode schemaNode : schemaNodes) {
1024 if (!schemaNode.isAugmenting()) {
1025 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1033 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1035 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1036 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1037 * @param childOf parent type
1038 * @param module current module
1040 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1041 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1042 if (node != null && typeBuilder != null) {
1043 if (node instanceof LeafSchemaNode) {
1044 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1045 } else if (node instanceof LeafListSchemaNode) {
1046 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1047 } else if (node instanceof ContainerSchemaNode) {
1048 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1049 } else if (node instanceof ListSchemaNode) {
1050 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1051 } else if (node instanceof ChoiceSchemaNode) {
1052 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1054 // TODO: anyxml not yet supported
1055 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1056 typeBuilder.getFullyQualifiedName());
1062 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1063 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1064 * and names of all parents node.
1066 * @param context current module
1067 * @param basePackageName string with the module package name
1068 * @param parent parent type
1069 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1071 * @throws IllegalArgumentException
1073 * <li>if <code>basePackageName</code> is null</li>
1074 * <li>if <code>choiceNode</code> is null</li>
1077 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1078 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1079 checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1081 if (!choiceNode.isAddedByUses()) {
1082 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1083 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1084 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1085 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1086 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1087 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1089 final GeneratedType choiceType = choiceTypeBuilder.build();
1090 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1092 constructGetter(parent, choiceType, choiceNode);
1097 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1098 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1099 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1100 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1102 * @param context current module context
1103 * @param refChoiceType type which represents superior <i>case</i>
1104 * @param choiceNode choice case node which is mapped to generated type
1105 * @throws IllegalArgumentException
1107 * <li>if <code>refChoiceType</code> equals null</li>
1108 * <li>if <code>caseNodes</code> equals null</li>
1111 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1112 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1113 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1114 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1116 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1117 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1118 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1119 caseTypeBuilder.addImplementsType(refChoiceType);
1120 defaultImplementedInterace(caseTypeBuilder);
1121 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1122 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1123 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1124 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1125 if (caseChildNodes != null) {
1126 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1128 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1129 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1131 if (parent instanceof AugmentationSchemaNode) {
1132 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1133 final SchemaPath targetPath = augSchema.getTargetPath();
1134 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1135 if (targetSchemaNode instanceof DataSchemaNode
1136 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1137 if (targetSchemaNode instanceof DerivableSchemaNode) {
1138 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1141 if (targetSchemaNode == null) {
1142 throw new IllegalStateException(
1143 "Failed to find target node from grouping for augmentation " + augSchema
1144 + " in module " + context.module().getName());
1147 parent = targetSchemaNode;
1150 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1151 Type childOfType = findChildNodeByPath(parent.getPath());
1152 if (childOfType == null) {
1153 childOfType = findGroupingByPath(parent.getPath());
1155 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1157 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1162 processUsesAugments(caseNode, context, inGrouping);
1167 * Generates list of generated types for all the cases of a choice which are added to the choice through
1170 * @param module current module
1171 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1172 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1173 * of the augmenting choice will belong to pcg2.
1174 * @param targetType Type which represents target choice
1175 * @param targetNode node which represents target choice
1176 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1178 * @throws IllegalArgumentException
1180 * <li>if <code>basePackageName</code> is null</li>
1181 * <li>if <code>targetType</code> is null</li>
1182 * <li>if <code>augmentedNodes</code> is null</li>
1185 // FIXME: nullness rules need to untangled in this method
1186 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1187 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1188 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1189 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1190 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1191 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1193 for (final DataSchemaNode caseNode : augmentedNodes) {
1194 if (caseNode != null) {
1195 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1196 caseTypeBuilder.addImplementsType(targetType);
1197 defaultImplementedInterace(caseTypeBuilder);
1199 CaseSchemaNode node = null;
1200 final String caseLocalName = caseNode.getQName().getLocalName();
1201 if (caseNode instanceof CaseSchemaNode) {
1202 node = (CaseSchemaNode) caseNode;
1203 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1204 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1205 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1206 if (dataSchemaNode instanceof ChoiceSchemaNode
1207 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1208 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1213 node = findNamedCase(targetNode, caseLocalName);
1215 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1216 if (childNodes != null) {
1217 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1220 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1221 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1226 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1227 final SchemaPath nodePath = targetNode.getPath();
1228 final SchemaPath parentSp = nodePath.getParent();
1229 if (parentSp.getParent() == null) {
1230 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1233 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1234 GeneratedTypeBuilder childOfType = null;
1235 if (parent instanceof CaseSchemaNode) {
1236 childOfType = findCaseByPath(parent.getPath());
1237 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1238 childOfType = findChildNodeByPath(parent.getPath());
1239 } else if (parent instanceof GroupingDefinition) {
1240 childOfType = findGroupingByPath(parent.getPath());
1243 if (childOfType == null) {
1244 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1250 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1251 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1252 return cases.isEmpty() ? null : cases.get(0);
1255 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1256 // New parser with encapsulated type
1257 if (leaf.getPath().equals(type.getPath())) {
1261 // Embedded type definition with new parser. Also takes care of the old parser with bits
1262 if (leaf.getPath().equals(type.getPath().getParent())) {
1269 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1270 final List<PatternConstraint> patternConstraints) {
1271 if (!patternConstraints.isEmpty()) {
1272 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1273 .append(BindingMapping.getPropertyName(leafName));
1274 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1275 typeProvider.resolveRegExpressions(patternConstraints));
1280 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1282 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1283 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1284 * @param module Module in which type was defined
1285 * @return boolean value
1287 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1289 * <li>true - in other cases</li>
1292 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1293 final ModuleContext context, final boolean inGrouping) {
1294 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1298 final Module parentModule = findParentModule(schemaContext, leaf);
1299 Type returnType = null;
1301 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1302 if (isInnerType(leaf, typeDef)) {
1303 if (typeDef instanceof EnumTypeDefinition) {
1304 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1305 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1306 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1307 typeBuilder, context);
1308 if (enumBuilder != null) {
1309 returnType = enumBuilder.toInstance(typeBuilder);
1311 typeProvider.putReferencedType(leaf.getPath(), returnType);
1312 } else if (typeDef instanceof UnionTypeDefinition) {
1313 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1314 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1315 // Store the inner type within the union so that we can find the reference for it
1316 context.addInnerTypedefType(typeDef.getPath(), returnType);
1317 } else if (typeDef instanceof BitsTypeDefinition) {
1318 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1320 if (genTOBuilder != null) {
1321 returnType = genTOBuilder.build();
1324 // It is constrained version of already declared type (inner declared type exists,
1325 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1326 // In order to get proper class we need to look up closest derived type
1327 // and apply restrictions from leaf type
1328 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1329 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1330 restrictions, inGrouping);
1331 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1334 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1335 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1336 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1339 if (returnType == null) {
1343 if (typeDef instanceof EnumTypeDefinition) {
1344 typeProvider.putReferencedType(leaf.getPath(), returnType);
1347 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1348 processContextRefExtension(leaf, getter, parentModule);
1352 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1353 // Returns DerivedType in case of new parser.
1354 final TypeDefinition<?> baseType = typeDef.getBaseType();
1355 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1358 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1359 final Module module) {
1360 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1361 final QName nodeType = node.getNodeType();
1362 if ("context-reference".equals(nodeType.getLocalName())) {
1363 final String nodeParam = node.getNodeParameter();
1364 IdentitySchemaNode identity = null;
1365 String basePackageName = null;
1366 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1367 final Iterator<String> iterator = splittedElement.iterator();
1368 final int length = Iterables.size(splittedElement);
1370 identity = findIdentityByName(module.getIdentities(), iterator.next());
1371 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1372 } else if (length == 2) {
1373 final String prefix = iterator.next();
1374 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1375 if (dependentModule == null) {
1376 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1379 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1380 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1382 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1385 if (identity == null) {
1386 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1390 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1391 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1392 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1393 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1398 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1399 for (final IdentitySchemaNode id : identities) {
1400 if (id.getQName().getLocalName().equals(name)) {
1407 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1408 for (final ModuleImport imp : imports) {
1409 if (imp.getPrefix().equals(prefix)) {
1410 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1416 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1417 final boolean isReadOnly) {
1418 if (leaf != null && toBuilder != null) {
1420 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1421 if (typeDef instanceof UnionTypeDefinition) {
1422 // GeneratedType for this type definition should have be already created
1423 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1424 returnType = mc.getTypedefs().get(typeDef.getPath());
1425 if (returnType == null) {
1426 // This may still be an inner type, try to find it
1427 returnType = mc.getInnerType(typeDef.getPath());
1429 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1430 // Annonymous enumeration (already generated, since it is inherited via uses).
1431 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1432 QName qname = originalLeaf.getQName();
1433 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1435 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1437 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1443 * Converts <code>leaf</code> schema node to property of generated TO builder.
1445 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1446 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1447 * @param returnType property type
1448 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1449 * @return boolean value
1451 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1452 * name equals null or if leaf is added by <i>uses</i>.</li>
1453 * <li>true - other cases</li>
1456 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1457 final Type returnType, final boolean isReadOnly) {
1458 if (returnType == null) {
1461 final String leafName = leaf.getQName().getLocalName();
1462 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1463 propBuilder.setReadOnly(isReadOnly);
1464 propBuilder.setReturnType(returnType);
1465 addComment(propBuilder, leaf);
1467 toBuilder.addEqualsIdentity(propBuilder);
1468 toBuilder.addHashIdentity(propBuilder);
1469 toBuilder.addToStringProperty(propBuilder);
1474 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1476 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1477 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1478 * @param module module
1479 * @return boolean value
1481 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1482 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1483 * <li>false - other cases</li>
1486 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1487 final ModuleContext context, final boolean inGrouping) {
1488 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1492 final QName nodeName = node.getQName();
1494 final TypeDefinition<?> typeDef = node.getType();
1495 final Module parentModule = findParentModule(schemaContext, node);
1497 Type returnType = null;
1498 if (typeDef.getBaseType() == null) {
1499 if (typeDef instanceof EnumTypeDefinition) {
1500 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1501 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1502 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1503 typeBuilder, context);
1504 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1505 typeProvider.putReferencedType(node.getPath(), returnType);
1506 } else if (typeDef instanceof UnionTypeDefinition) {
1507 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1508 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1509 } else if (typeDef instanceof BitsTypeDefinition) {
1510 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1511 node, parentModule);
1512 returnType = genTOBuilder.build();
1514 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1515 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1516 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1519 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1520 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1521 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1524 constructGetter(typeBuilder, listTypeFor(returnType), node);
1528 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1529 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1530 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1531 returnTypeBuilder.setIsUnion(true);
1532 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1533 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1534 returnTypeBuilder.setModuleName(parentModule.getName());
1535 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1537 genTOBuilder.setTypedef(true);
1538 genTOBuilder.setIsUnion(true);
1539 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1541 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1545 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1546 final GeneratedTransferObject returnType, final Module parentModule) {
1547 // Append enclosing path hierarchy without dots
1548 final StringBuilder sb = new StringBuilder();
1549 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1550 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1551 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1552 unionBuilder.setIsUnionBuilder(true);
1554 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1555 method.setReturnType(returnType);
1556 method.addParameter(STRING, "defaultValue");
1557 method.setAccessModifier(AccessModifier.PUBLIC);
1558 method.setStatic(true);
1560 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1561 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1564 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1565 final SchemaNode schemaNode) {
1566 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1569 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1570 final SchemaNode schemaNode, final Type baseInterface) {
1571 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1572 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1576 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1577 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1578 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1579 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1580 * If <code>schemaNode</code> is instance of
1581 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1582 * which are specified in <i>uses</i>.
1584 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1585 * @param schemaNode schema node for which is created generated type builder
1586 * @param parent parent type (can be null)
1587 * @return generated type builder <code>schemaNode</code>
1589 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1590 final Type baseInterface, final ModuleContext context) {
1591 JavaTypeName name = renames.get(schemaNode);
1593 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1596 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1597 it.addImplementsType(baseInterface);
1598 if (!(schemaNode instanceof GroupingDefinition)) {
1599 it.addImplementsType(augmentable(it));
1601 if (schemaNode instanceof DataNodeContainer) {
1602 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1603 groupingsToGenTypes(context, containerSchema.getGroupings());
1604 addImplementedInterfaceFromUses(containerSchema, it);
1611 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1612 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1613 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1615 * @param packageName string with the package name to which returning generated type builder belongs
1616 * @param schemaNode schema node which provide data about the schema node name
1617 * @param prefix return type name prefix
1618 * @return generated type builder for <code>schemaNode</code>
1619 * @throws IllegalArgumentException
1621 * <li>if <code>schemaNode</code> is null</li>
1622 * <li>if <code>packageName</code> is null</li>
1623 * <li>if QName of schema node is null</li>
1624 * <li>if schemaNode name is null</li>
1627 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1628 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1629 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1630 final String schemaNodeName = schemaNode.getQName().getLocalName();
1631 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1633 // FIXME: Validation of name conflict
1634 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1635 final Module module = findParentModule(schemaContext, schemaNode);
1636 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1637 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1639 addCodegenInformation(newType, module, schemaNode);
1640 newType.setSchemaPath(schemaNode.getPath());
1641 newType.setModuleName(module.getName());
1643 final String packageName = identifier.packageName();
1644 final String simpleName = identifier.simpleName();
1645 if (!genTypeBuilders.containsKey(packageName)) {
1646 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1647 builders.put(simpleName, newType);
1648 genTypeBuilders.put(packageName, builders);
1650 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1651 if (!builders.containsKey(simpleName)) {
1652 builders.put(simpleName, newType);
1659 * Creates the name of the getter method name from <code>localName</code>.
1661 * @param localName string with the name of the getter method
1662 * @param returnType return type
1663 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1665 public static String getterMethodName(final String localName, final Type returnType) {
1666 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1670 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1671 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1672 * and <code>returnType</code> information are added to the builder.
1674 * @param interfaceBuilder generated type builder for which the getter method should be created
1675 * @param returnType type which represents the return type of the getter method
1676 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1677 * @param comment string with comment for the getter method
1678 * @param status status from yang file, for deprecated annotation
1679 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1681 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1682 final SchemaNode node) {
1683 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1684 getterMethodName(node.getQName().getLocalName(), returnType));
1685 getMethod.setReturnType(returnType);
1687 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1688 addComment(getMethod, node);
1693 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1694 final ListSchemaNode node) {
1695 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1696 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1697 getMethod.setReturnType(returnType).setDefault(true);
1698 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1702 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1705 * @param basePackageName string contains the module package name
1706 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1707 * or as a property to <code>genTOBuilder</code> if is part of the list key
1708 * @param typeBuilder generated type builder for the list schema node
1709 * @param genTOBuilder generated TO builder for the list keys
1710 * @param listKeys list of string which contains names of the list keys
1711 * @param module current module
1712 * @throws IllegalArgumentException
1714 * <li>if <code>schemaNode</code> equals null</li>
1715 * <li>if <code>typeBuilder</code> equals null</li>
1718 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1719 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1720 final List<String> listKeys, final boolean inGrouping) {
1721 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1722 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1724 if (schemaNode instanceof LeafSchemaNode) {
1725 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1726 final String leafName = leaf.getQName().getLocalName();
1727 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1728 if (listKeys.contains(leafName)) {
1730 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1732 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1735 } else if (!schemaNode.isAddedByUses()) {
1736 if (schemaNode instanceof LeafListSchemaNode) {
1737 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1738 } else if (schemaNode instanceof ContainerSchemaNode) {
1739 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1740 (ContainerSchemaNode) schemaNode, inGrouping);
1741 } else if (schemaNode instanceof ChoiceSchemaNode) {
1742 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1743 } else if (schemaNode instanceof ListSchemaNode) {
1744 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1749 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1750 final GeneratedTOBuilder genTOBuilder) {
1751 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1753 if (genTOBuilder != null) {
1754 final GeneratedTransferObject genTO = genTOBuilder.build();
1755 // Add Identifiable.getKey() for items
1756 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1757 .addAnnotation(OVERRIDE_ANNOTATION);
1758 context.addGeneratedTOBuilder(genTOBuilder);
1763 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1765 * @param list of string with names of the list keys
1766 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1767 * an empty list is returned.
1769 private static List<String> listKeys(final ListSchemaNode list) {
1770 final List<String> listKeys = new ArrayList<>();
1772 final List<QName> keyDefinition = list.getKeyDefinition();
1773 if (keyDefinition != null) {
1774 for (final QName keyDef : keyDefinition) {
1775 listKeys.add(keyDef.getLocalName());
1782 * Generates for the <code>list</code> which contains any list keys special generated TO builder.
1784 * @param packageName string with package name to which the list belongs
1785 * @param list list schema node which is source of data about the list name
1786 * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
1787 * null or list of key definitions is null or empty.
1789 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1790 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1791 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1792 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1793 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1799 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1800 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1801 * enclosing transfer objects.
1803 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1804 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1805 * @param leaf string with name for generated TO builder
1806 * @param parentModule parent module
1807 * @return generated TO builder for <code>typeDef</code>
1809 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1810 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1811 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1812 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1815 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1816 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1817 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1818 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1819 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1821 for (GeneratedTOBuilder builder : types) {
1822 if (builder.isUnion()) {
1823 final GeneratedTransferObject type = builder.build();
1824 createUnionBuilder(builder, typeBuilder, type, parentModule);
1828 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1832 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1833 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1834 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1837 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1838 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1839 * @param leaf string with name for generated TO builder
1840 * @param parentModule parent module
1841 * @return generated TO builder for <code>typeDef</code>
1843 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1844 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1845 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1846 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1847 typeDef, parentModule.getName());
1848 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1849 return genTOBuilder;
1854 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1855 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1856 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1857 * to <code>builder</code>
1859 * @param dataNodeContainer element which contains the list of used YANG groupings
1860 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1861 * @return generated type builder with all implemented types
1863 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1864 final GeneratedTypeBuilder builder) {
1865 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1866 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1867 if (genType == null) {
1868 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1869 + builder.getName());
1872 builder.addImplementsType(genType);
1877 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1878 for (final ModuleContext ctx : genCtx.values()) {
1879 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1880 if (result != null) {
1887 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1888 for (final ModuleContext ctx : genCtx.values()) {
1889 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1890 if (result != null) {
1897 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1898 for (final ModuleContext ctx : genCtx.values()) {
1899 final GeneratedTypeBuilder result = ctx.getCase(path);
1900 if (result != null) {
1907 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1908 if (status == Status.DEPRECATED) {
1909 builder.addAnnotation(DEPRECATED_ANNOTATION);
1913 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
1914 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
1917 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
1918 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
1922 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
1923 final Type classType) {
1924 final MethodSignatureBuilder ret = typeBuilder
1925 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
1926 .setAccessModifier(AccessModifier.PUBLIC)
1927 .setReturnType(classType(classType));
1928 ret.addAnnotation(OVERRIDE_ANNOTATION);