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.opaqueObject;
34 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
35 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
36 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
37 import static org.opendaylight.mdsal.binding.model.util.Types.augmentationTypeFor;
38 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
39 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
40 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
41 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
42 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
43 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
44 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
45 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
46 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
48 import com.google.common.base.Splitter;
49 import com.google.common.collect.Iterables;
50 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
51 import java.util.AbstractMap.SimpleImmutableEntry;
52 import java.util.ArrayList;
53 import java.util.Collection;
54 import java.util.Collections;
55 import java.util.Comparator;
56 import java.util.HashMap;
57 import java.util.HashSet;
58 import java.util.Iterator;
59 import java.util.List;
61 import java.util.Optional;
63 import org.eclipse.jdt.annotation.Nullable;
64 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
65 import org.opendaylight.mdsal.binding.model.api.Constant;
66 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
67 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
68 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
69 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
70 import org.opendaylight.mdsal.binding.model.api.Restrictions;
71 import org.opendaylight.mdsal.binding.model.api.Type;
72 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
73 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
74 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
75 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
76 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
81 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
82 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
83 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
84 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
85 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
86 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
87 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
88 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
89 import org.opendaylight.yangtools.yang.common.QName;
90 import org.opendaylight.yangtools.yang.common.QNameModule;
91 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
92 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
93 import org.opendaylight.yangtools.yang.model.api.AnyDataSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
100 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
103 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
104 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
105 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.Module;
110 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
111 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
112 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
113 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
114 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
116 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
117 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
118 import org.opendaylight.yangtools.yang.model.api.UsesNode;
119 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
120 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
121 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
122 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
123 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
124 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
125 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
126 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
127 import org.slf4j.Logger;
128 import org.slf4j.LoggerFactory;
130 abstract class AbstractTypeGenerator {
131 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
132 private static final Splitter COLON_SPLITTER = Splitter.on(':');
133 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
134 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
135 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
138 * Comparator based on augment target path.
140 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
141 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
142 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
144 while (thisIt.hasNext()) {
145 if (!otherIt.hasNext()) {
149 final int comp = thisIt.next().compareTo(otherIt.next());
155 return otherIt.hasNext() ? -1 : 0;
159 * Constant with the concrete name of identifier.
161 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
164 * Constant with the concrete name of namespace.
166 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
168 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
171 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
172 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
173 * for schema node specified in key part.
175 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
178 * Provide methods for converting YANG types to JAVA types.
180 private final AbstractTypeProvider typeProvider;
183 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
185 private final SchemaContext schemaContext;
188 * Holds renamed elements.
190 private final Map<SchemaNode, JavaTypeName> renames;
192 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
193 final Map<SchemaNode, JavaTypeName> renames) {
194 this.schemaContext = requireNonNull(context);
195 this.typeProvider = requireNonNull(typeProvider);
196 this.renames = requireNonNull(renames);
198 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
199 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
200 for (final Module contextModule : contextModules) {
201 contexts.add(moduleToGenTypes(contextModule));
204 contexts.forEach(this::allAugmentsToGenTypes);
207 final Collection<ModuleContext> moduleContexts() {
208 return genCtx.values();
211 final ModuleContext moduleContext(final QNameModule module) {
212 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
215 final AbstractTypeProvider typeProvider() {
219 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
221 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
223 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
224 Set<? extends SchemaNode> nodes);
226 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
228 private ModuleContext moduleToGenTypes(final Module module) {
229 final ModuleContext context = new ModuleContext(module);
230 genCtx.put(module.getQNameModule(), context);
231 allTypeDefinitionsToGenTypes(context);
232 groupingsToGenTypes(context, module.getGroupings());
233 rpcMethodsToGenType(context);
234 allIdentitiesToGenTypes(context);
235 notificationsToGenType(context);
237 if (!module.getChildNodes().isEmpty()) {
238 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
239 context.addModuleNode(moduleType);
240 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
246 * Converts all extended type definitions of module to the list of
247 * <code>Type</code> objects.
250 * module from which is obtained set of type definitions
251 * @throws IllegalArgumentException
253 * <li>if module is null</li>
254 * <li>if name of module is null</li>
256 * @throws IllegalStateException
257 * if set of type definitions from module is null
259 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
260 final Module module = context.module();
261 checkArgument(module.getName() != null, "Module name cannot be NULL.");
262 final DataNodeIterator it = new DataNodeIterator(module);
263 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
264 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
266 for (final TypeDefinition<?> typedef : typeDefinitions) {
267 if (typedef != null) {
268 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
270 context.addTypedefType(typedef, type);
271 context.addTypeToSchema(type,typedef);
277 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
278 final DataSchemaNode node, final boolean inGrouping) {
279 if (node.isAugmenting() || node.isAddedByUses()) {
282 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
283 defaultImplementedInterace(genType);
284 annotateDeprecatedIfNecessary(node, genType);
286 final Module module = context.module();
287 genType.setModuleName(module.getName());
288 addCodegenInformation(genType, module, node);
289 genType.setSchemaPath(node.getPath());
290 if (node instanceof DataNodeContainer) {
291 context.addChildNodeType(node, genType);
292 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
293 processUsesAugments((DataNodeContainer) node, context, inGrouping);
298 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
299 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
300 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
301 if (genType != null) {
302 constructGetter(parent, genType, node);
303 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
304 actionsToGenType(context, genType, node, null, inGrouping);
308 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
309 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
310 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
311 if (genType != null) {
312 final List<String> listKeys = listKeys(node);
313 final GeneratedTOBuilder keyTypeBuilder;
314 if (!listKeys.isEmpty()) {
315 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
316 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
317 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
318 .addImplementsType(identifier(genType));
319 genType.addImplementsType(identifiable(keyTypeBuilder));
321 keyTypeBuilder = null;
324 final ParameterizedType listType = listTypeFor(genType);
325 constructGetter(parent, listType, node);
326 constructNonnull(parent, listType, node);
328 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
330 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
331 if (!schemaNode.isAugmenting()) {
332 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
337 if (keyTypeBuilder != null) {
338 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
339 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
340 keyTypeBuilder.setSUID(prop);
343 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
347 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
348 final boolean inGrouping) {
349 for (final UsesNode usesNode : node.getUses()) {
350 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
351 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
352 processUsesAugments(augment, context, inGrouping);
358 * Converts all <b>augmentation</b> of the module to the list
359 * <code>Type</code> objects.
362 * module from which is obtained list of all augmentation objects
363 * to iterate over them
364 * @throws IllegalArgumentException
366 * <li>if the module is null</li>
367 * <li>if the name of module is null</li>
369 * @throws IllegalStateException
370 * if set of augmentations from module is null
372 private void allAugmentsToGenTypes(final ModuleContext context) {
373 final Module module = context.module();
374 checkArgument(module != null, "Module reference cannot be NULL.");
375 checkArgument(module.getName() != null, "Module name cannot be NULL.");
376 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
378 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
379 augmentationToGenTypes(context, augment);
384 * Returns list of <code>AugmentationSchema</code> objects. The objects are
385 * sorted according to the length of their target path from the shortest to
389 * module from which is obtained list of all augmentation objects
390 * @return list of sorted <code>AugmentationSchema</code> objects obtained
391 * from <code>module</code>
392 * @throws IllegalArgumentException
394 * @throws IllegalStateException
395 * if set of module augmentations is null
397 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
398 checkArgument(module != null, "Module reference cannot be NULL.");
399 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
401 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
402 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
403 sortedAugmentations.sort(AUGMENT_COMP);
405 return sortedAugmentations;
409 * Create GeneratedTypeBuilder object from module argument.
412 * Module object from which builder will be created
413 * @return <code>GeneratedTypeBuilder</code> which is internal
414 * representation of the module
415 * @throws IllegalArgumentException
418 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
419 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
420 final Module module = context.module();
421 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
422 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
424 addCodegenInformation(moduleDataTypeBuilder, module);
425 return moduleDataTypeBuilder;
428 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
429 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
430 for (final ActionDefinition action : parentSchema.getActions()) {
431 if (action.isAugmenting()) {
435 final GeneratedType input;
436 final GeneratedType output;
437 if (action.isAddedByUses()) {
438 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
439 input = context.getChildNode(orig.getInput().getPath()).build();
440 output = context.getChildNode(orig.getOutput().getPath()).build();
442 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
443 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
446 if (!(parentSchema instanceof GroupingDefinition)) {
447 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
448 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
449 // and do not capture an actual instantiation.
450 final QName qname = action.getQName();
451 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
452 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
453 BindingMapping.getClassName(qname)));
454 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
455 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
457 annotateDeprecatedIfNecessary(action, builder);
458 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
459 : action(parent, input, output));
461 addCodegenInformation(builder, context.module(), action);
462 context.addChildNodeType(action, builder);
467 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
468 for (UsesNode uses : parent.getUses()) {
469 final GroupingDefinition grp = findUsedGrouping(uses);
470 final Optional<ActionDefinition> found = grp.findAction(action.getQName());
471 if (found.isPresent()) {
472 final ActionDefinition result = found.get();
473 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
477 return Optional.empty();
480 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
481 final ContainerSchemaNode schema, final boolean inGrouping) {
482 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
483 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
484 return genType.build();
488 * Converts all <b>RPCs</b> input and output substatements of the module
489 * to the list of <code>Type</code> objects. In addition are to containers
490 * and lists which belong to input or output also part of returning list.
493 * module from which is obtained set of all rpc objects to
495 * @throws IllegalArgumentException
497 * <li>if the module is null</li>
498 * <li>if the name of module is null</li>
500 * @throws IllegalStateException
501 * if set of rpcs from module is null
503 private void rpcMethodsToGenType(final ModuleContext context) {
504 final Module module = context.module();
505 checkArgument(module.getName() != null, "Module name cannot be NULL.");
506 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
507 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
508 if (rpcDefinitions.isEmpty()) {
512 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
513 interfaceBuilder.addImplementsType(RPC_SERVICE);
515 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
517 for (final RpcDefinition rpc : rpcDefinitions) {
519 final String rpcName = BindingMapping.getClassName(rpc.getQName());
520 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
521 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
523 // Do not refer to annotation class, as it may not be available at runtime
524 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
525 addComment(method, rpc);
527 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
528 method.setReturnType(listenableFutureTypeFor(
529 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
533 context.addTopLevelNodeType(interfaceBuilder);
536 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
537 final ContainerSchemaNode schema, final Type type) {
538 processUsesAugments(schema, context, false);
539 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
540 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
542 addImplementedInterfaceFromUses(schema, outType);
543 outType.addImplementsType(type);
544 outType.addImplementsType(augmentable(outType));
545 defaultImplementedInterace(outType);
546 annotateDeprecatedIfNecessary(rpc, outType);
547 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
548 context.addChildNodeType(schema, outType);
549 return outType.build();
553 * Converts all <b>notifications</b> of the module to the list of
554 * <code>Type</code> objects. In addition are to this list added containers
555 * and lists which are part of this notification.
558 * module from which is obtained set of all notification objects
559 * to iterate over them
560 * @throws IllegalArgumentException
562 * <li>if the module equals null</li>
563 * <li>if the name of module equals null</li>
565 * @throws IllegalStateException
566 * if set of notifications from module is null
568 private void notificationsToGenType(final ModuleContext context) {
569 final Module module = context.module();
570 checkArgument(module.getName() != null, "Module name cannot be NULL.");
571 final Set<NotificationDefinition> notifications = module.getNotifications();
572 if (notifications.isEmpty()) {
576 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
577 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
579 for (final NotificationDefinition notification : notifications) {
580 if (notification != null) {
581 processUsesAugments(notification, context, false);
583 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
584 context.modulePackageName(), notification, DATA_OBJECT, context);
585 defaultImplementedInterace(notificationInterface);
586 annotateDeprecatedIfNecessary(notification, notificationInterface);
587 notificationInterface.addImplementsType(NOTIFICATION);
588 context.addChildNodeType(notification, notificationInterface);
590 // Notification object
591 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
592 notification.getChildNodes(), false);
594 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
595 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
596 .setReturnType(primitiveVoidType()), notification);
600 addCodegenInformation(listenerInterface, module, "notifications", notifications);
601 context.addTopLevelNodeType(listenerInterface);
605 * Converts all <b>identities</b> of the module to the list of
606 * <code>Type</code> objects.
609 * module from which is obtained set of all identity objects to
611 * @param schemaContext
612 * schema context only used as input parameter for method
613 * {@link BindingGeneratorImpl#identityToGenType}
616 private void allIdentitiesToGenTypes(final ModuleContext context) {
617 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
619 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
620 for (final IdentitySchemaNode identity : schemaIdentities) {
621 identityToGenType(context, identity);
627 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
628 * created transport object builder. If identity contains base identity then
629 * reference to base identity is added to superior identity as its extend.
630 * If identity doesn't contain base identity then only reference to abstract
631 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
632 * BaseIdentity} is added
636 * @param basePackageName
637 * string contains the module package name
639 * IdentitySchemaNode which contains data about identity
641 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
642 if (identity == null) {
646 JavaTypeName name = renames.get(identity);
648 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
649 BindingMapping.getClassName(identity.getQName()));
652 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
653 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
654 if (!baseIdentities.isEmpty()) {
655 for (IdentitySchemaNode baseIdentity : baseIdentities) {
656 JavaTypeName base = renames.get(baseIdentity);
658 final QName qname = baseIdentity.getQName();
659 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
660 BindingMapping.getClassName(qname));
663 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
664 newType.addImplementsType(gto);
667 newType.addImplementsType(BASE_IDENTITY);
670 final Module module = context.module();
671 addCodegenInformation(newType, module, identity);
672 newType.setModuleName(module.getName());
673 newType.setSchemaPath(identity.getPath());
675 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
676 identity.getQName().getLocalName());
678 context.addIdentityType(identity, newType);
681 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
682 final JavaTypeName yangModuleInfo, final String localName) {
683 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
684 new SimpleImmutableEntry<>(yangModuleInfo, localName));
688 * Converts all <b>groupings</b> of the module to the list of
689 * <code>Type</code> objects. Firstly are groupings sorted according mutual
690 * dependencies. At least dependent (independent) groupings are in the list
691 * saved at first positions. For every grouping the record is added to map
692 * {@link ModuleContext#groupings allGroupings}
697 * collection of groupings from which types will be generated
700 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
701 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
702 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
703 // node of grouping is resolved to the method.
704 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
705 narrowImplementedInterface(genType);
706 annotateDeprecatedIfNecessary(grouping, genType);
707 context.addGroupingType(grouping, genType);
708 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
709 groupingsToGenTypes(context, grouping.getGroupings());
710 processUsesAugments(grouping, context, true);
711 actionsToGenType(context, genType, grouping, null, true);
716 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
717 * <code>enumTypeDef</code> item is added to builder with its name and value.
719 * @param enumTypeDef EnumTypeDefinition contains enum data
720 * @param enumName string contains name which will be assigned to enumeration builder
721 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
722 * @param module Module in which type should be generated
723 * @return enumeration builder which contains data from <code>enumTypeDef</code>
725 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
726 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
727 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
728 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
729 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
730 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
731 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
738 * Generates type builder for <code>module</code>.
740 * @param module Module which is source of package name for generated type builder
741 * @param postfix string which is added to the module class name representation as suffix
742 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
743 * @throws IllegalArgumentException if <code>module</code> is null
745 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
746 final Module module = context.module();
747 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
748 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
749 JavaTypeName.create(context.modulePackageName(), moduleName));
751 moduleBuilder.setModuleName(moduleName);
752 addCodegenInformation(moduleBuilder, module);
753 return moduleBuilder;
757 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
758 * In addition there are also generated types for all containers, list and choices which are child of
759 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
761 * @param augmentPackageName string with the name of the package to which the augmentation belongs
762 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
763 * @param module current module
764 * @throws IllegalArgumentException
766 * <li>if <code>augmentPackageName</code> equals null</li>
767 * <li>if <code>augSchema</code> equals null</li>
769 * @throws IllegalStateException
770 * if augment target path is null
772 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
773 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
774 checkState(augSchema.getTargetPath() != null,
775 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
777 processUsesAugments(augSchema, context, false);
778 final SchemaPath targetPath = augSchema.getTargetPath();
779 SchemaNode targetSchemaNode = null;
781 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
782 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
783 if (targetSchemaNode instanceof DerivableSchemaNode) {
784 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
786 if (targetSchemaNode == null) {
787 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
788 + " in module " + context.module().getName());
791 if (targetSchemaNode == null) {
792 throw new IllegalArgumentException("augment target not found: " + targetPath);
795 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
796 if (targetTypeBuilder == null) {
797 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
799 if (targetTypeBuilder == null) {
800 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
803 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
804 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
805 addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
808 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
809 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
813 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
814 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
815 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
816 checkState(augSchema.getTargetPath() != null,
817 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
819 processUsesAugments(augSchema, context, inGrouping);
820 final SchemaPath targetPath = augSchema.getTargetPath();
821 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
822 if (targetSchemaNode == null) {
823 throw new IllegalArgumentException("augment target not found: " + targetPath);
826 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
827 if (targetTypeBuilder == null) {
828 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
830 if (targetTypeBuilder == null) {
831 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
834 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
835 if (usesNodeParent instanceof SchemaNode) {
836 addRawAugmentGenTypeDefinition(context,
837 packageNameForAugmentedGeneratedType(context.modulePackageName(),
838 ((SchemaNode) usesNodeParent).getPath()),
839 targetTypeBuilder.build(), augSchema, inGrouping);
841 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
844 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
845 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
849 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
850 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
852 if (targetGrouping instanceof GroupingDefinition) {
853 return (GroupingDefinition) targetGrouping;
856 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
860 * Convenient method to find node added by uses statement.
862 * @param targetPath node path
863 * @param parentUsesNode parent of uses node
864 * @return node from its original location in grouping
866 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
867 SchemaNode result = findUsedGrouping(parentUsesNode);
868 for (final QName node : targetPath.getPathFromRoot()) {
869 if (result instanceof DataNodeContainer) {
870 final QName resultNode = node.withModule(result.getQName().getModule());
871 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
872 } else if (result instanceof ChoiceSchemaNode) {
873 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
876 if (result == null) {
880 if (result instanceof DerivableSchemaNode) {
881 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
882 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
883 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
884 result = originalNode.get();
888 if (result instanceof DataSchemaNode) {
889 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
890 if (resultDataSchemaNode.isAddedByUses()) {
891 // The original node is required, but we have only the copy of
892 // the original node.
893 // Maybe this indicates a bug in Yang parser.
894 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
897 return resultDataSchemaNode;
900 throw new IllegalStateException(
901 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
906 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
907 * of augmented node with serial number as suffix.
909 * @param context current module
910 * @param augmentPackageName string with contains the package name to which the augment belongs
911 * @param basePackageName string with the package name to which the augmented node belongs
912 * @param targetTypeRef target type
913 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
914 * @return generated type builder for augment
916 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
917 final String augmentPackageName, final Type targetTypeRef,
918 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
919 Map<String, GeneratedTypeBuilder> augmentBuilders =
920 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
921 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
924 if (augIdentifier != null) {
925 augTypeName = BindingMapping.getClassName(augIdentifier);
927 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
930 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
931 JavaTypeName.create(augmentPackageName, augTypeName));
933 augTypeBuilder.addImplementsType(DATA_OBJECT);
934 defaultImplementedInterace(augTypeBuilder);
936 augTypeBuilder.addImplementsType(augmentationTypeFor(targetTypeRef));
937 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
938 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
940 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
941 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
942 augmentBuilders.put(augTypeName, augTypeBuilder);
944 if (!augSchema.getChildNodes().isEmpty()) {
945 context.addTypeToAugmentation(augTypeBuilder, augSchema);
948 context.addAugmentType(augTypeBuilder);
949 return augTypeBuilder;
952 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
953 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
954 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
958 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
959 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
960 final QName nodeType = unknownSchemaNode.getNodeType();
961 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
962 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
963 return unknownSchemaNode.getNodeParameter();
970 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
971 * consists from name of augmented node and serial number of its augmentation.
973 * @param builders map of builders which were created in the package to which the augmentation belongs
974 * @param genTypeName string with name of augmented node
975 * @return string with unique name for augmentation builder
977 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
979 if (builders != null) {
980 while (builders.containsKey(genTypeName + index)) {
984 return genTypeName + index;
988 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
989 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
990 * already part of them).
992 * @param module current module
993 * @param parent generated type builder which represents any node. The subnodes of this node are added
994 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
996 * @param childOf parent type
997 * @param schemaNodes set of data schema nodes which are the children of the node for which
998 * <code>typeBuilder</code> was created
999 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1000 * child nodes) could be added to it.
1002 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1003 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
1004 if (schemaNodes != null && parent != null) {
1005 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1006 for (final DataSchemaNode schemaNode : schemaNodes) {
1007 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1008 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1016 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1019 * @param module current module
1020 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1021 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1022 * container, choice.
1023 * @param childOf parent type
1024 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1026 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1027 * The getter method could be added to it.
1029 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1030 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1031 final boolean inGrouping) {
1032 if (schemaNodes != null && typeBuilder != null) {
1033 final Type baseInterface = childOf(typeBuilder);
1034 for (final DataSchemaNode schemaNode : schemaNodes) {
1035 if (!schemaNode.isAugmenting()) {
1036 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1044 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1046 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1047 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1048 * @param childOf parent type
1049 * @param module current module
1051 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1052 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1053 if (node != null && typeBuilder != null) {
1054 if (node instanceof LeafSchemaNode) {
1055 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1056 } else if (node instanceof LeafListSchemaNode) {
1057 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1058 } else if (node instanceof ContainerSchemaNode) {
1059 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1060 } else if (node instanceof ListSchemaNode) {
1061 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1062 } else if (node instanceof ChoiceSchemaNode) {
1063 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1064 } else if (node instanceof AnyXmlSchemaNode || node instanceof AnyDataSchemaNode) {
1065 opaqueToGeneratedType(context, typeBuilder, node);
1067 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1068 typeBuilder.getFullyQualifiedName());
1074 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1075 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1076 * and names of all parents node.
1078 * @param context current module
1079 * @param basePackageName string with the module package name
1080 * @param parent parent type
1081 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1083 * @throws IllegalArgumentException
1085 * <li>if <code>basePackageName</code> is null</li>
1086 * <li>if <code>choiceNode</code> is null</li>
1089 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1090 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1091 if (!choiceNode.isAddedByUses()) {
1092 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1093 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1094 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1095 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1096 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1097 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1099 final GeneratedType choiceType = choiceTypeBuilder.build();
1100 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1102 constructGetter(parent, choiceType, choiceNode);
1106 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1107 final DataSchemaNode anyNode) {
1108 if (!anyNode.isAddedByUses()) {
1109 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(
1110 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1111 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1112 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1113 defaultImplementedInterace(anyxmlTypeBuilder);
1114 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1115 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1117 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1122 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1123 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1124 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1125 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1127 * @param context current module context
1128 * @param refChoiceType type which represents superior <i>case</i>
1129 * @param choiceNode choice case node which is mapped to generated type
1130 * @throws IllegalArgumentException
1132 * <li>if <code>refChoiceType</code> equals null</li>
1133 * <li>if <code>caseNodes</code> equals null</li>
1136 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1137 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1138 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1139 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1141 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1142 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1143 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1144 caseTypeBuilder.addImplementsType(refChoiceType);
1145 defaultImplementedInterace(caseTypeBuilder);
1146 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1147 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1148 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1149 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1150 if (caseChildNodes != null) {
1151 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1153 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1154 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1156 if (parent instanceof AugmentationSchemaNode) {
1157 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1158 final SchemaPath targetPath = augSchema.getTargetPath();
1159 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1160 if (targetSchemaNode instanceof DataSchemaNode
1161 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1162 if (targetSchemaNode instanceof DerivableSchemaNode) {
1163 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1166 if (targetSchemaNode == null) {
1167 throw new IllegalStateException(
1168 "Failed to find target node from grouping for augmentation " + augSchema
1169 + " in module " + context.module().getName());
1172 parent = targetSchemaNode;
1175 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1176 Type childOfType = findChildNodeByPath(parent.getPath());
1177 if (childOfType == null) {
1178 childOfType = findGroupingByPath(parent.getPath());
1180 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1182 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1187 processUsesAugments(caseNode, context, inGrouping);
1192 * Generates list of generated types for all the cases of a choice which are added to the choice through
1195 * @param module current module
1196 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1197 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1198 * of the augmenting choice will belong to pcg2.
1199 * @param targetType Type which represents target choice
1200 * @param targetNode node which represents target choice
1201 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1203 * @throws IllegalArgumentException
1205 * <li>if <code>basePackageName</code> is null</li>
1206 * <li>if <code>targetType</code> is null</li>
1207 * <li>if <code>augmentedNodes</code> is null</li>
1210 // FIXME: nullness rules need to untangled in this method
1211 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1212 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1213 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1214 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1215 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1216 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1218 for (final DataSchemaNode caseNode : augmentedNodes) {
1219 if (caseNode != null) {
1220 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1221 caseTypeBuilder.addImplementsType(targetType);
1222 defaultImplementedInterace(caseTypeBuilder);
1224 CaseSchemaNode node = null;
1225 final String caseLocalName = caseNode.getQName().getLocalName();
1226 if (caseNode instanceof CaseSchemaNode) {
1227 node = (CaseSchemaNode) caseNode;
1228 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1229 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1230 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1231 if (dataSchemaNode instanceof ChoiceSchemaNode
1232 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1233 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1238 node = findNamedCase(targetNode, caseLocalName);
1240 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1241 if (childNodes != null) {
1242 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1245 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1246 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1251 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1252 final SchemaPath nodePath = targetNode.getPath();
1253 final SchemaPath parentSp = nodePath.getParent();
1254 if (parentSp.getParent() == null) {
1255 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1258 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1259 GeneratedTypeBuilder childOfType = null;
1260 if (parent instanceof CaseSchemaNode) {
1261 childOfType = findCaseByPath(parent.getPath());
1262 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1263 childOfType = findChildNodeByPath(parent.getPath());
1264 } else if (parent instanceof GroupingDefinition) {
1265 childOfType = findGroupingByPath(parent.getPath());
1268 if (childOfType == null) {
1269 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1275 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1276 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1277 return cases.isEmpty() ? null : cases.get(0);
1280 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1281 // New parser with encapsulated type
1282 if (leaf.getPath().equals(type.getPath())) {
1286 // Embedded type definition with new parser. Also takes care of the old parser with bits
1287 if (leaf.getPath().equals(type.getPath().getParent())) {
1294 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1295 final List<PatternConstraint> patternConstraints) {
1296 if (!patternConstraints.isEmpty()) {
1297 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1298 .append(BindingMapping.getPropertyName(leafName));
1299 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1300 typeProvider.resolveRegExpressions(patternConstraints));
1305 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1307 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1308 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1309 * @param module Module in which type was defined
1310 * @return boolean value
1312 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1314 * <li>true - in other cases</li>
1317 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1318 final ModuleContext context, final boolean inGrouping) {
1319 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1323 final Module parentModule = findParentModule(schemaContext, leaf);
1324 Type returnType = null;
1326 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1327 if (isInnerType(leaf, typeDef)) {
1328 if (typeDef instanceof EnumTypeDefinition) {
1329 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1330 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1331 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1332 typeBuilder, context);
1333 if (enumBuilder != null) {
1334 returnType = enumBuilder.toInstance(typeBuilder);
1336 typeProvider.putReferencedType(leaf.getPath(), returnType);
1337 } else if (typeDef instanceof UnionTypeDefinition) {
1338 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1339 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1340 // Store the inner type within the union so that we can find the reference for it
1341 context.addInnerTypedefType(typeDef.getPath(), returnType);
1342 } else if (typeDef instanceof BitsTypeDefinition) {
1343 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1345 if (genTOBuilder != null) {
1346 returnType = genTOBuilder.build();
1349 // It is constrained version of already declared type (inner declared type exists,
1350 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1351 // In order to get proper class we need to look up closest derived type
1352 // and apply restrictions from leaf type
1353 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1354 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1355 restrictions, inGrouping);
1356 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1359 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1360 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1361 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1364 if (returnType == null) {
1368 if (typeDef instanceof EnumTypeDefinition) {
1369 typeProvider.putReferencedType(leaf.getPath(), returnType);
1372 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1373 processContextRefExtension(leaf, getter, parentModule);
1377 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1378 // Returns DerivedType in case of new parser.
1379 final TypeDefinition<?> baseType = typeDef.getBaseType();
1380 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1383 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1384 final Module module) {
1385 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1386 final QName nodeType = node.getNodeType();
1387 if ("context-reference".equals(nodeType.getLocalName())) {
1388 final String nodeParam = node.getNodeParameter();
1389 IdentitySchemaNode identity = null;
1390 String basePackageName = null;
1391 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1392 final Iterator<String> iterator = splittedElement.iterator();
1393 final int length = Iterables.size(splittedElement);
1395 identity = findIdentityByName(module.getIdentities(), iterator.next());
1396 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1397 } else if (length == 2) {
1398 final String prefix = iterator.next();
1399 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1400 if (dependentModule == null) {
1401 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1404 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1405 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1407 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1410 if (identity == null) {
1411 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1415 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1416 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1417 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1418 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1423 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1424 for (final IdentitySchemaNode id : identities) {
1425 if (id.getQName().getLocalName().equals(name)) {
1432 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1433 for (final ModuleImport imp : imports) {
1434 if (imp.getPrefix().equals(prefix)) {
1435 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1441 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1442 final boolean isReadOnly) {
1443 if (leaf != null && toBuilder != null) {
1445 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1446 if (typeDef instanceof UnionTypeDefinition) {
1447 // GeneratedType for this type definition should have be already created
1448 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1449 returnType = mc.getTypedefs().get(typeDef.getPath());
1450 if (returnType == null) {
1451 // This may still be an inner type, try to find it
1452 returnType = mc.getInnerType(typeDef.getPath());
1454 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1455 // Annonymous enumeration (already generated, since it is inherited via uses).
1456 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1457 QName qname = originalLeaf.getQName();
1458 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1460 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1462 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1468 * Converts <code>leaf</code> schema node to property of generated TO builder.
1470 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1471 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1472 * @param returnType property type
1473 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1474 * @return boolean value
1476 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1477 * name equals null or if leaf is added by <i>uses</i>.</li>
1478 * <li>true - other cases</li>
1481 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1482 final Type returnType, final boolean isReadOnly) {
1483 if (returnType == null) {
1486 final String leafName = leaf.getQName().getLocalName();
1487 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1488 propBuilder.setReadOnly(isReadOnly);
1489 propBuilder.setReturnType(returnType);
1490 addComment(propBuilder, leaf);
1492 toBuilder.addEqualsIdentity(propBuilder);
1493 toBuilder.addHashIdentity(propBuilder);
1494 toBuilder.addToStringProperty(propBuilder);
1499 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1501 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1502 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1503 * @param module module
1504 * @return boolean value
1506 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1507 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1508 * <li>false - other cases</li>
1511 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1512 final ModuleContext context, final boolean inGrouping) {
1513 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1517 final QName nodeName = node.getQName();
1519 final TypeDefinition<?> typeDef = node.getType();
1520 final Module parentModule = findParentModule(schemaContext, node);
1522 Type returnType = null;
1523 if (typeDef.getBaseType() == null) {
1524 if (typeDef instanceof EnumTypeDefinition) {
1525 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1526 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1527 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1528 typeBuilder, context);
1529 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1530 typeProvider.putReferencedType(node.getPath(), returnType);
1531 } else if (typeDef instanceof UnionTypeDefinition) {
1532 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1533 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1534 } else if (typeDef instanceof BitsTypeDefinition) {
1535 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1536 node, parentModule);
1537 returnType = genTOBuilder.build();
1539 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1540 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1541 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1544 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1545 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1546 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1549 constructGetter(typeBuilder, listTypeFor(returnType), node);
1553 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1554 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1555 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1556 returnTypeBuilder.setIsUnion(true);
1557 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1558 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1559 returnTypeBuilder.setModuleName(parentModule.getName());
1560 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1562 genTOBuilder.setTypedef(true);
1563 genTOBuilder.setIsUnion(true);
1564 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1566 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1570 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1571 final GeneratedTransferObject returnType, final Module parentModule) {
1572 // Append enclosing path hierarchy without dots
1573 final StringBuilder sb = new StringBuilder();
1574 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1575 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1576 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1577 unionBuilder.setIsUnionBuilder(true);
1579 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1580 method.setReturnType(returnType);
1581 method.addParameter(STRING, "defaultValue");
1582 method.setAccessModifier(AccessModifier.PUBLIC);
1583 method.setStatic(true);
1585 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1586 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1589 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1590 final SchemaNode schemaNode) {
1591 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1594 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1595 final SchemaNode schemaNode, final Type baseInterface) {
1596 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1597 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1601 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1602 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1603 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1604 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1605 * If <code>schemaNode</code> is instance of
1606 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1607 * which are specified in <i>uses</i>.
1609 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1610 * @param schemaNode schema node for which is created generated type builder
1611 * @param parent parent type (can be null)
1612 * @return generated type builder <code>schemaNode</code>
1614 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1615 final Type baseInterface, final ModuleContext context) {
1616 JavaTypeName name = renames.get(schemaNode);
1618 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1621 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1622 it.addImplementsType(baseInterface);
1623 if (!(schemaNode instanceof GroupingDefinition)) {
1624 it.addImplementsType(augmentable(it));
1626 if (schemaNode instanceof DataNodeContainer) {
1627 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1628 groupingsToGenTypes(context, containerSchema.getGroupings());
1629 addImplementedInterfaceFromUses(containerSchema, it);
1636 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1637 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1638 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1640 * @param packageName string with the package name to which returning generated type builder belongs
1641 * @param schemaNode schema node which provide data about the schema node name
1642 * @param prefix return type name prefix
1643 * @return generated type builder for <code>schemaNode</code>
1644 * @throws IllegalArgumentException
1646 * <li>if <code>schemaNode</code> is null</li>
1647 * <li>if <code>packageName</code> is null</li>
1648 * <li>if QName of schema node is null</li>
1649 * <li>if schemaNode name is null</li>
1652 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1653 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1654 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1655 final String schemaNodeName = schemaNode.getQName().getLocalName();
1656 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1658 // FIXME: Validation of name conflict
1659 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1660 final Module module = findParentModule(schemaContext, schemaNode);
1661 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1662 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1664 addCodegenInformation(newType, module, schemaNode);
1665 newType.setSchemaPath(schemaNode.getPath());
1666 newType.setModuleName(module.getName());
1668 final String packageName = identifier.packageName();
1669 final String simpleName = identifier.simpleName();
1670 if (!genTypeBuilders.containsKey(packageName)) {
1671 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1672 builders.put(simpleName, newType);
1673 genTypeBuilders.put(packageName, builders);
1675 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1676 if (!builders.containsKey(simpleName)) {
1677 builders.put(simpleName, newType);
1684 * Creates the name of the getter method name from <code>localName</code>.
1686 * @param localName string with the name of the getter method
1687 * @param returnType return type
1688 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1690 public static String getterMethodName(final String localName, final Type returnType) {
1691 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1695 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1696 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1697 * and <code>returnType</code> information are added to the builder.
1699 * @param interfaceBuilder generated type builder for which the getter method should be created
1700 * @param returnType type which represents the return type of the getter method
1701 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1702 * @param comment string with comment for the getter method
1703 * @param status status from yang file, for deprecated annotation
1704 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1706 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1707 final SchemaNode node) {
1708 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1709 getterMethodName(node.getQName().getLocalName(), returnType));
1710 getMethod.setReturnType(returnType);
1712 annotateDeprecatedIfNecessary(node, getMethod);
1713 addComment(getMethod, node);
1718 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1719 final ListSchemaNode node) {
1720 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1721 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1722 getMethod.setReturnType(returnType).setDefault(true);
1723 annotateDeprecatedIfNecessary(node, getMethod);
1727 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1730 * @param basePackageName string contains the module package name
1731 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1732 * or as a property to <code>genTOBuilder</code> if is part of the list key
1733 * @param typeBuilder generated type builder for the list schema node
1734 * @param genTOBuilder generated TO builder for the list keys
1735 * @param listKeys list of string which contains names of the list keys
1736 * @param module current module
1737 * @throws IllegalArgumentException
1739 * <li>if <code>schemaNode</code> equals null</li>
1740 * <li>if <code>typeBuilder</code> equals null</li>
1743 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1744 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1745 final List<String> listKeys, final boolean inGrouping) {
1746 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1747 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1749 if (schemaNode instanceof LeafSchemaNode) {
1750 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1751 final String leafName = leaf.getQName().getLocalName();
1752 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1753 if (listKeys.contains(leafName)) {
1755 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1757 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1760 } else if (!schemaNode.isAddedByUses()) {
1761 if (schemaNode instanceof LeafListSchemaNode) {
1762 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1763 } else if (schemaNode instanceof ContainerSchemaNode) {
1764 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1765 (ContainerSchemaNode) schemaNode, inGrouping);
1766 } else if (schemaNode instanceof ChoiceSchemaNode) {
1767 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1768 } else if (schemaNode instanceof ListSchemaNode) {
1769 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1774 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1775 final GeneratedTOBuilder genTOBuilder) {
1776 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1778 if (genTOBuilder != null) {
1779 final GeneratedTransferObject genTO = genTOBuilder.build();
1780 // Add Identifiable.getKey() for items
1781 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1782 .addAnnotation(OVERRIDE_ANNOTATION);
1783 context.addGeneratedTOBuilder(genTOBuilder);
1788 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1790 * @param list of string with names of the list keys
1791 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1792 * an empty list is returned.
1794 private static List<String> listKeys(final ListSchemaNode list) {
1795 final List<QName> keyDefinition = list.getKeyDefinition();
1796 switch (keyDefinition.size()) {
1798 return Collections.emptyList();
1800 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1802 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1803 for (final QName keyDef : keyDefinition) {
1804 listKeys.add(keyDef.getLocalName());
1811 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1812 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1813 * enclosing transfer objects.
1815 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1816 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1817 * @param leaf string with name for generated TO builder
1818 * @param parentModule parent module
1819 * @return generated TO builder for <code>typeDef</code>
1821 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1822 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1823 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1824 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1826 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1827 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1828 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1829 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1830 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1832 for (GeneratedTOBuilder builder : types) {
1833 if (builder.isUnion()) {
1834 final GeneratedTransferObject type = builder.build();
1835 createUnionBuilder(builder, typeBuilder, type, parentModule);
1839 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1843 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1844 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1845 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1848 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1849 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1850 * @param leaf string with name for generated TO builder
1851 * @param parentModule parent module
1852 * @return generated TO builder for <code>typeDef</code>
1854 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1855 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1856 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1857 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1858 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1859 return genTOBuilder;
1863 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1864 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1865 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1866 * to <code>builder</code>
1868 * @param dataNodeContainer element which contains the list of used YANG groupings
1869 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1870 * @return generated type builder with all implemented types
1872 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1873 final GeneratedTypeBuilder builder) {
1874 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1875 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1876 if (genType == null) {
1877 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1878 + builder.getName());
1881 builder.addImplementsType(genType.build());
1886 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1887 for (final ModuleContext ctx : genCtx.values()) {
1888 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1889 if (result != null) {
1896 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1897 for (final ModuleContext ctx : genCtx.values()) {
1898 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1899 if (result != null) {
1906 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1907 for (final ModuleContext ctx : genCtx.values()) {
1908 final GeneratedTypeBuilder result = ctx.getCase(path);
1909 if (result != null) {
1916 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
1917 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
1918 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
1921 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
1922 switch (node.getStatus()) {
1925 // FIXME: we really want to use a pre-made annotation
1926 builder.addAnnotation(DEPRECATED_ANNOTATION);
1932 throw new IllegalStateException("Unhandled status in " + node);
1936 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
1937 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
1940 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
1941 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
1945 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
1946 final Type classType) {
1947 final MethodSignatureBuilder ret = typeBuilder
1948 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
1949 .setAccessModifier(AccessModifier.PUBLIC)
1950 .setReturnType(classType(classType));
1951 ret.addAnnotation(OVERRIDE_ANNOTATION);