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.QNAME;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentation;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
34 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.instanceNotification;
35 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
36 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListNotification;
37 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.opaqueObject;
38 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
39 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
40 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
41 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
42 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
43 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
44 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
45 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
46 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
47 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
48 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
50 import com.google.common.base.Splitter;
51 import com.google.common.collect.Iterables;
52 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
53 import java.util.AbstractMap.SimpleImmutableEntry;
54 import java.util.ArrayList;
55 import java.util.Collection;
56 import java.util.Collections;
57 import java.util.Comparator;
58 import java.util.HashMap;
59 import java.util.HashSet;
60 import java.util.Iterator;
61 import java.util.List;
63 import java.util.Optional;
65 import org.eclipse.jdt.annotation.Nullable;
66 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
67 import org.opendaylight.mdsal.binding.model.api.Constant;
68 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
69 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
70 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
71 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
72 import org.opendaylight.mdsal.binding.model.api.Restrictions;
73 import org.opendaylight.mdsal.binding.model.api.Type;
74 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
75 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
76 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
83 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
84 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
85 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
86 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
87 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
88 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
89 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
90 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
91 import org.opendaylight.yangtools.yang.common.QName;
92 import org.opendaylight.yangtools.yang.common.QNameModule;
93 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
94 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
95 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
102 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
105 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
106 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
107 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.Module;
112 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
113 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
114 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
115 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
116 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
117 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
118 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
119 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
120 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
121 import org.opendaylight.yangtools.yang.model.api.UsesNode;
122 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
123 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
124 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
125 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
126 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
127 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
128 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
129 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
130 import org.slf4j.Logger;
131 import org.slf4j.LoggerFactory;
133 abstract class AbstractTypeGenerator {
134 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
135 private static final Splitter COLON_SPLITTER = Splitter.on(':');
136 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
137 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
138 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
141 * Comparator based on augment target path.
143 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
144 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
145 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
147 while (thisIt.hasNext()) {
148 if (!otherIt.hasNext()) {
152 final int comp = thisIt.next().compareTo(otherIt.next());
158 return otherIt.hasNext() ? -1 : 0;
162 * Constant with the concrete name of identifier.
164 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
167 * Constant with the concrete name of namespace.
169 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
171 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
174 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
175 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
176 * for schema node specified in key part.
178 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
181 * Provide methods for converting YANG types to JAVA types.
183 private final AbstractTypeProvider typeProvider;
186 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
188 private final SchemaContext schemaContext;
191 * Holds renamed elements.
193 private final Map<SchemaNode, JavaTypeName> renames;
195 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
196 final Map<SchemaNode, JavaTypeName> renames) {
197 this.schemaContext = requireNonNull(context);
198 this.typeProvider = requireNonNull(typeProvider);
199 this.renames = requireNonNull(renames);
201 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
202 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
203 for (final Module contextModule : contextModules) {
204 contexts.add(moduleToGenTypes(contextModule));
207 contexts.forEach(this::allAugmentsToGenTypes);
210 final Collection<ModuleContext> moduleContexts() {
211 return genCtx.values();
214 final ModuleContext moduleContext(final QNameModule module) {
215 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
218 final AbstractTypeProvider typeProvider() {
222 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
224 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
226 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
227 Set<? extends SchemaNode> nodes);
229 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
231 private ModuleContext moduleToGenTypes(final Module module) {
232 final ModuleContext context = new ModuleContext(module);
233 genCtx.put(module.getQNameModule(), context);
234 allTypeDefinitionsToGenTypes(context);
235 groupingsToGenTypes(context, module.getGroupings());
236 rpcMethodsToGenType(context);
237 allIdentitiesToGenTypes(context);
238 notificationsToGenType(context);
240 if (!module.getChildNodes().isEmpty()) {
241 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
242 context.addModuleNode(moduleType);
243 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
249 * Converts all extended type definitions of module to the list of
250 * <code>Type</code> objects.
253 * module from which is obtained set of type definitions
254 * @throws IllegalArgumentException
256 * <li>if module is null</li>
257 * <li>if name of module is null</li>
259 * @throws IllegalStateException
260 * if set of type definitions from module is null
262 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
263 final Module module = context.module();
264 checkArgument(module.getName() != null, "Module name cannot be NULL.");
265 final DataNodeIterator it = new DataNodeIterator(module);
266 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
267 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
269 for (final TypeDefinition<?> typedef : typeDefinitions) {
270 if (typedef != null) {
271 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
273 context.addTypedefType(typedef, type);
274 context.addTypeToSchema(type,typedef);
280 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
281 final DataSchemaNode node, final boolean inGrouping) {
282 if (node.isAugmenting() || node.isAddedByUses()) {
285 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
286 defaultImplementedInterace(genType);
287 annotateDeprecatedIfNecessary(node, genType);
289 final Module module = context.module();
290 genType.setModuleName(module.getName());
291 addCodegenInformation(genType, module, node);
292 genType.setSchemaPath(node.getPath());
293 if (node instanceof DataNodeContainer) {
294 context.addChildNodeType(node, genType);
295 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
296 processUsesAugments((DataNodeContainer) node, context, inGrouping);
301 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
302 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
303 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
304 if (genType != null) {
305 constructGetter(parent, genType, node);
306 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
307 actionsToGenType(context, genType, node, null, inGrouping);
308 notificationsToGenType(context, genType, node, null, inGrouping);
312 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
313 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
314 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
315 if (genType != null) {
316 final List<String> listKeys = listKeys(node);
317 final GeneratedTOBuilder keyTypeBuilder;
318 if (!listKeys.isEmpty()) {
319 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
320 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
321 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
322 .addImplementsType(identifier(genType));
323 genType.addImplementsType(identifiable(keyTypeBuilder));
325 keyTypeBuilder = null;
328 final ParameterizedType listType = listTypeFor(genType);
329 constructGetter(parent, listType, node);
330 constructNonnull(parent, listType, node);
332 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
333 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
335 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
336 if (!schemaNode.isAugmenting()) {
337 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
342 if (keyTypeBuilder != null) {
343 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
344 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
345 keyTypeBuilder.setSUID(prop);
348 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
352 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
353 final boolean inGrouping) {
354 for (final UsesNode usesNode : node.getUses()) {
355 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
356 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
357 processUsesAugments(augment, context, inGrouping);
363 * Converts all <b>augmentation</b> of the module to the list
364 * <code>Type</code> objects.
367 * module from which is obtained list of all augmentation objects
368 * to iterate over them
369 * @throws IllegalArgumentException
371 * <li>if the module is null</li>
372 * <li>if the name of module is null</li>
374 * @throws IllegalStateException
375 * if set of augmentations from module is null
377 private void allAugmentsToGenTypes(final ModuleContext context) {
378 final Module module = context.module();
379 checkArgument(module != null, "Module reference cannot be NULL.");
380 checkArgument(module.getName() != null, "Module name cannot be NULL.");
381 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
383 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
384 augmentationToGenTypes(context, augment);
389 * Returns list of <code>AugmentationSchema</code> objects. The objects are
390 * sorted according to the length of their target path from the shortest to
394 * module from which is obtained list of all augmentation objects
395 * @return list of sorted <code>AugmentationSchema</code> objects obtained
396 * from <code>module</code>
397 * @throws IllegalArgumentException
399 * @throws IllegalStateException
400 * if set of module augmentations is null
402 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
403 checkArgument(module != null, "Module reference cannot be NULL.");
404 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
406 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
407 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
408 sortedAugmentations.sort(AUGMENT_COMP);
410 return sortedAugmentations;
414 * Create GeneratedTypeBuilder object from module argument.
417 * Module object from which builder will be created
418 * @return <code>GeneratedTypeBuilder</code> which is internal
419 * representation of the module
420 * @throws IllegalArgumentException
423 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
424 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
425 final Module module = context.module();
426 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
427 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
429 addCodegenInformation(moduleDataTypeBuilder, module);
430 return moduleDataTypeBuilder;
433 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
434 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
435 for (final ActionDefinition action : parentSchema.getActions()) {
436 if (action.isAugmenting()) {
440 final GeneratedType input;
441 final GeneratedType output;
442 if (action.isAddedByUses()) {
443 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
444 input = context.getChildNode(orig.getInput().getPath()).build();
445 output = context.getChildNode(orig.getOutput().getPath()).build();
447 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
448 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
451 if (!(parentSchema instanceof GroupingDefinition)) {
452 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
453 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
454 // and do not capture an actual instantiation.
455 final QName qname = action.getQName();
456 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
457 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
458 BindingMapping.getClassName(qname)));
459 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
460 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
462 annotateDeprecatedIfNecessary(action, builder);
463 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
464 : action(parent, input, output));
466 addCodegenInformation(builder, context.module(), action);
467 context.addChildNodeType(action, builder);
472 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
473 for (UsesNode uses : parent.getUses()) {
474 final GroupingDefinition grp = findUsedGrouping(uses);
475 final Optional<ActionDefinition> found = grp.findAction(action.getQName());
476 if (found.isPresent()) {
477 final ActionDefinition result = found.get();
478 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
482 return Optional.empty();
485 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
486 final ContainerSchemaNode schema, final boolean inGrouping) {
487 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
488 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
489 return genType.build();
493 * Converts all <b>RPCs</b> input and output substatements of the module
494 * to the list of <code>Type</code> objects. In addition are to containers
495 * and lists which belong to input or output also part of returning list.
498 * module from which is obtained set of all rpc objects to
500 * @throws IllegalArgumentException
502 * <li>if the module is null</li>
503 * <li>if the name of module is null</li>
505 * @throws IllegalStateException
506 * if set of rpcs from module is null
508 private void rpcMethodsToGenType(final ModuleContext context) {
509 final Module module = context.module();
510 checkArgument(module.getName() != null, "Module name cannot be NULL.");
511 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
512 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
513 if (rpcDefinitions.isEmpty()) {
517 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
518 interfaceBuilder.addImplementsType(RPC_SERVICE);
520 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
522 for (final RpcDefinition rpc : rpcDefinitions) {
524 final String rpcName = BindingMapping.getClassName(rpc.getQName());
525 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
526 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
528 // Do not refer to annotation class, as it may not be available at runtime
529 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
530 addComment(method, rpc);
532 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
533 method.setReturnType(listenableFutureTypeFor(
534 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
538 context.addTopLevelNodeType(interfaceBuilder);
541 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
542 final ContainerSchemaNode schema, final Type type) {
543 processUsesAugments(schema, context, false);
544 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
545 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
547 addImplementedInterfaceFromUses(schema, outType);
548 outType.addImplementsType(type);
549 outType.addImplementsType(augmentable(outType));
550 defaultImplementedInterace(outType);
551 annotateDeprecatedIfNecessary(rpc, outType);
552 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
553 context.addChildNodeType(schema, outType);
554 return outType.build();
558 * Converts all <b>notifications</b> of the module to the list of
559 * <code>Type</code> objects. In addition are to this list added containers
560 * and lists which are part of this notification.
563 * module from which is obtained set of all notification objects
564 * to iterate over them
565 * @throws IllegalArgumentException
567 * <li>if the module equals null</li>
568 * <li>if the name of module equals null</li>
570 * @throws IllegalStateException
571 * if set of notifications from module is null
573 private void notificationsToGenType(final ModuleContext context) {
574 final Module module = context.module();
575 checkArgument(module.getName() != null, "Module name cannot be NULL.");
576 final Set<NotificationDefinition> notifications = module.getNotifications();
577 if (notifications.isEmpty()) {
581 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
582 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
584 for (final NotificationDefinition notification : notifications) {
585 if (notification != null) {
586 processUsesAugments(notification, context, false);
588 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
589 context.modulePackageName(), notification, DATA_OBJECT, context);
590 defaultImplementedInterace(notificationInterface);
591 annotateDeprecatedIfNecessary(notification, notificationInterface);
592 notificationInterface.addImplementsType(NOTIFICATION);
593 context.addChildNodeType(notification, notificationInterface);
595 // Notification object
596 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
597 notification.getChildNodes(), false);
599 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
600 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
601 .setReturnType(primitiveVoidType()), notification);
605 addCodegenInformation(listenerInterface, module, "notifications", notifications);
606 context.addTopLevelNodeType(listenerInterface);
609 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
610 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
611 final boolean inGrouping) {
612 final Set<NotificationDefinition> notifications = parentSchema.getNotifications();
613 if (notifications.isEmpty()) {
617 for (NotificationDefinition notif : notifications) {
618 if (notif.isAugmenting()) {
621 if (parentSchema instanceof GroupingDefinition) {
622 // Notifications cannot be really established, as they lack instantiation context, which would be
623 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
627 processUsesAugments(notif, context, false);
629 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
630 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
631 defaultImplementedInterace(notifInterface);
632 annotateDeprecatedIfNecessary(notif, notifInterface);
634 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
635 : instanceNotification(notifInterface, parent));
636 context.addChildNodeType(notif, notifInterface);
638 // Notification object
639 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
644 * Converts all <b>identities</b> of the module to the list of
645 * <code>Type</code> objects.
648 * module from which is obtained set of all identity objects to
650 * @param schemaContext
651 * schema context only used as input parameter for method
652 * {@link BindingGeneratorImpl#identityToGenType}
655 private void allIdentitiesToGenTypes(final ModuleContext context) {
656 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
658 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
659 for (final IdentitySchemaNode identity : schemaIdentities) {
660 identityToGenType(context, identity);
666 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
667 * created transport object builder. If identity contains base identity then
668 * reference to base identity is added to superior identity as its extend.
669 * If identity doesn't contain base identity then only reference to abstract
670 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
671 * BaseIdentity} is added
675 * @param basePackageName
676 * string contains the module package name
678 * IdentitySchemaNode which contains data about identity
680 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
681 if (identity == null) {
685 JavaTypeName name = renames.get(identity);
687 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
688 BindingMapping.getClassName(identity.getQName()));
691 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
692 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
693 if (!baseIdentities.isEmpty()) {
694 for (IdentitySchemaNode baseIdentity : baseIdentities) {
695 JavaTypeName base = renames.get(baseIdentity);
697 final QName qname = baseIdentity.getQName();
698 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
699 BindingMapping.getClassName(qname));
702 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
703 newType.addImplementsType(gto);
706 newType.addImplementsType(BASE_IDENTITY);
709 final Module module = context.module();
710 addCodegenInformation(newType, module, identity);
711 newType.setModuleName(module.getName());
712 newType.setSchemaPath(identity.getPath());
714 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
715 identity.getQName().getLocalName());
717 context.addIdentityType(identity, newType);
720 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
721 final JavaTypeName yangModuleInfo, final String localName) {
722 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
723 new SimpleImmutableEntry<>(yangModuleInfo, localName));
727 * Converts all <b>groupings</b> of the module to the list of
728 * <code>Type</code> objects. Firstly are groupings sorted according mutual
729 * dependencies. At least dependent (independent) groupings are in the list
730 * saved at first positions. For every grouping the record is added to map
731 * {@link ModuleContext#groupings allGroupings}
736 * collection of groupings from which types will be generated
739 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
740 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
741 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
742 // node of grouping is resolved to the method.
743 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
744 narrowImplementedInterface(genType);
745 annotateDeprecatedIfNecessary(grouping, genType);
746 context.addGroupingType(grouping, genType);
747 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
748 groupingsToGenTypes(context, grouping.getGroupings());
749 processUsesAugments(grouping, context, true);
750 actionsToGenType(context, genType, grouping, null, true);
751 notificationsToGenType(context, genType, grouping, null, true);
756 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
757 * <code>enumTypeDef</code> item is added to builder with its name and value.
759 * @param enumTypeDef EnumTypeDefinition contains enum data
760 * @param enumName string contains name which will be assigned to enumeration builder
761 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
762 * @param module Module in which type should be generated
763 * @return enumeration builder which contains data from <code>enumTypeDef</code>
765 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
766 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
767 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
768 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
769 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
770 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
771 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
778 * Generates type builder for <code>module</code>.
780 * @param module Module which is source of package name for generated type builder
781 * @param postfix string which is added to the module class name representation as suffix
782 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
783 * @throws IllegalArgumentException if <code>module</code> is null
785 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
786 final Module module = context.module();
787 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
788 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
789 JavaTypeName.create(context.modulePackageName(), moduleName));
791 moduleBuilder.setModuleName(moduleName);
792 addCodegenInformation(moduleBuilder, module);
793 return moduleBuilder;
797 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
798 * In addition there are also generated types for all containers, list and choices which are child of
799 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
801 * @param augmentPackageName string with the name of the package to which the augmentation belongs
802 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
803 * @param module current module
804 * @throws IllegalArgumentException
806 * <li>if <code>augmentPackageName</code> equals null</li>
807 * <li>if <code>augSchema</code> equals null</li>
809 * @throws IllegalStateException
810 * if augment target path is null
812 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
813 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
814 checkState(augSchema.getTargetPath() != null,
815 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
817 processUsesAugments(augSchema, context, false);
818 final SchemaPath targetPath = augSchema.getTargetPath();
819 SchemaNode targetSchemaNode = null;
821 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
822 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
823 if (targetSchemaNode instanceof DerivableSchemaNode) {
824 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
826 if (targetSchemaNode == null) {
827 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
828 + " in module " + context.module().getName());
831 if (targetSchemaNode == null) {
832 throw new IllegalArgumentException("augment target not found: " + targetPath);
835 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
836 if (targetTypeBuilder == null) {
837 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
839 if (targetTypeBuilder == null) {
840 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
843 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
844 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
845 addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
848 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
849 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
853 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
854 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
855 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
856 checkState(augSchema.getTargetPath() != null,
857 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
859 processUsesAugments(augSchema, context, inGrouping);
860 final SchemaPath targetPath = augSchema.getTargetPath();
861 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
862 if (targetSchemaNode == null) {
863 throw new IllegalArgumentException("augment target not found: " + targetPath);
866 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
867 if (targetTypeBuilder == null) {
868 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
870 if (targetTypeBuilder == null) {
871 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
874 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
875 if (usesNodeParent instanceof SchemaNode) {
876 addRawAugmentGenTypeDefinition(context,
877 packageNameForAugmentedGeneratedType(context.modulePackageName(),
878 ((SchemaNode) usesNodeParent).getPath()),
879 targetTypeBuilder.build(), augSchema, inGrouping);
881 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
884 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
885 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
889 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
890 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
892 if (targetGrouping instanceof GroupingDefinition) {
893 return (GroupingDefinition) targetGrouping;
896 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
900 * Convenient method to find node added by uses statement.
902 * @param targetPath node path
903 * @param parentUsesNode parent of uses node
904 * @return node from its original location in grouping
906 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
907 SchemaNode result = findUsedGrouping(parentUsesNode);
908 for (final QName node : targetPath.getPathFromRoot()) {
909 if (result instanceof DataNodeContainer) {
910 final QName resultNode = node.withModule(result.getQName().getModule());
911 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
912 } else if (result instanceof ChoiceSchemaNode) {
913 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
916 if (result == null) {
920 if (result instanceof DerivableSchemaNode) {
921 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
922 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
923 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
924 result = originalNode.get();
928 if (result instanceof DataSchemaNode) {
929 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
930 if (resultDataSchemaNode.isAddedByUses()) {
931 // The original node is required, but we have only the copy of
932 // the original node.
933 // Maybe this indicates a bug in Yang parser.
934 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
937 return resultDataSchemaNode;
940 throw new IllegalStateException(
941 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
946 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
947 * of augmented node with serial number as suffix.
949 * @param context current module
950 * @param augmentPackageName string with contains the package name to which the augment belongs
951 * @param basePackageName string with the package name to which the augmented node belongs
952 * @param targetTypeRef target type
953 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
954 * @return generated type builder for augment
956 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
957 final String augmentPackageName, final Type targetTypeRef,
958 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
959 Map<String, GeneratedTypeBuilder> augmentBuilders =
960 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
961 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
964 if (augIdentifier != null) {
965 augTypeName = BindingMapping.getClassName(augIdentifier);
967 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
970 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
971 JavaTypeName.create(augmentPackageName, augTypeName));
973 augTypeBuilder.addImplementsType(DATA_OBJECT);
974 defaultImplementedInterace(augTypeBuilder);
976 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
977 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
978 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
980 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
981 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
982 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
984 augmentBuilders.put(augTypeName, augTypeBuilder);
986 if (!augSchema.getChildNodes().isEmpty()) {
987 context.addTypeToAugmentation(augTypeBuilder, augSchema);
990 context.addAugmentType(augTypeBuilder);
991 return augTypeBuilder;
994 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
995 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
996 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1000 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1001 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1002 final QName nodeType = unknownSchemaNode.getNodeType();
1003 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1004 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1005 return unknownSchemaNode.getNodeParameter();
1012 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1013 * consists from name of augmented node and serial number of its augmentation.
1015 * @param builders map of builders which were created in the package to which the augmentation belongs
1016 * @param genTypeName string with name of augmented node
1017 * @return string with unique name for augmentation builder
1019 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1021 if (builders != null) {
1022 while (builders.containsKey(genTypeName + index)) {
1026 return genTypeName + index;
1030 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1031 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1032 * already part of them).
1034 * @param module current module
1035 * @param parent generated type builder which represents any node. The subnodes of this node are added
1036 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1037 * container, choice.
1038 * @param childOf parent type
1039 * @param schemaNodes set of data schema nodes which are the children of the node for which
1040 * <code>typeBuilder</code> was created
1041 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1042 * child nodes) could be added to it.
1044 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1045 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
1046 if (schemaNodes != null && parent != null) {
1047 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1048 for (final DataSchemaNode schemaNode : schemaNodes) {
1049 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1050 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1058 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1061 * @param module current module
1062 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1063 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1064 * container, choice.
1065 * @param childOf parent type
1066 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1068 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1069 * The getter method could be added to it.
1071 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1072 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1073 final boolean inGrouping) {
1074 if (schemaNodes != null && typeBuilder != null) {
1075 final Type baseInterface = childOf(typeBuilder);
1076 for (final DataSchemaNode schemaNode : schemaNodes) {
1077 if (!schemaNode.isAugmenting()) {
1078 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1086 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1088 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1089 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1090 * @param childOf parent type
1091 * @param module current module
1093 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1094 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1095 if (node != null && typeBuilder != null) {
1096 if (node instanceof LeafSchemaNode) {
1097 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1098 } else if (node instanceof LeafListSchemaNode) {
1099 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1100 } else if (node instanceof ContainerSchemaNode) {
1101 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1102 } else if (node instanceof ListSchemaNode) {
1103 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1104 } else if (node instanceof ChoiceSchemaNode) {
1105 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1106 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1107 opaqueToGeneratedType(context, typeBuilder, node);
1109 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1110 typeBuilder.getFullyQualifiedName());
1116 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1117 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1118 * and names of all parents node.
1120 * @param context current module
1121 * @param basePackageName string with the module package name
1122 * @param parent parent type
1123 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1125 * @throws IllegalArgumentException
1127 * <li>if <code>basePackageName</code> is null</li>
1128 * <li>if <code>choiceNode</code> is null</li>
1131 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1132 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1133 if (!choiceNode.isAddedByUses()) {
1134 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1135 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1136 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1137 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1138 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1139 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1141 final GeneratedType choiceType = choiceTypeBuilder.build();
1142 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1144 constructGetter(parent, choiceType, choiceNode);
1148 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1149 final DataSchemaNode anyNode) {
1150 if (!anyNode.isAddedByUses()) {
1151 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(
1152 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1153 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1154 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1155 defaultImplementedInterace(anyxmlTypeBuilder);
1156 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1157 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1159 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1164 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1165 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1166 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1167 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1169 * @param context current module context
1170 * @param refChoiceType type which represents superior <i>case</i>
1171 * @param choiceNode choice case node which is mapped to generated type
1172 * @throws IllegalArgumentException
1174 * <li>if <code>refChoiceType</code> equals null</li>
1175 * <li>if <code>caseNodes</code> equals null</li>
1178 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1179 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1180 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1181 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1183 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1184 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1185 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1186 caseTypeBuilder.addImplementsType(refChoiceType);
1187 defaultImplementedInterace(caseTypeBuilder);
1188 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1189 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1190 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1191 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1192 if (caseChildNodes != null) {
1193 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1195 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1196 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1198 if (parent instanceof AugmentationSchemaNode) {
1199 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1200 final SchemaPath targetPath = augSchema.getTargetPath();
1201 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1202 if (targetSchemaNode instanceof DataSchemaNode
1203 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1204 if (targetSchemaNode instanceof DerivableSchemaNode) {
1205 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1208 if (targetSchemaNode == null) {
1209 throw new IllegalStateException(
1210 "Failed to find target node from grouping for augmentation " + augSchema
1211 + " in module " + context.module().getName());
1214 parent = targetSchemaNode;
1217 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1218 Type childOfType = findChildNodeByPath(parent.getPath());
1219 if (childOfType == null) {
1220 childOfType = findGroupingByPath(parent.getPath());
1222 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1224 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1229 processUsesAugments(caseNode, context, inGrouping);
1234 * Generates list of generated types for all the cases of a choice which are added to the choice through
1237 * @param module current module
1238 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1239 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1240 * of the augmenting choice will belong to pcg2.
1241 * @param targetType Type which represents target choice
1242 * @param targetNode node which represents target choice
1243 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1245 * @throws IllegalArgumentException
1247 * <li>if <code>basePackageName</code> is null</li>
1248 * <li>if <code>targetType</code> is null</li>
1249 * <li>if <code>augmentedNodes</code> is null</li>
1252 // FIXME: nullness rules need to untangled in this method
1253 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1254 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1255 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1256 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1257 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1258 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1260 for (final DataSchemaNode caseNode : augmentedNodes) {
1261 if (caseNode != null) {
1262 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1263 caseTypeBuilder.addImplementsType(targetType);
1264 defaultImplementedInterace(caseTypeBuilder);
1266 CaseSchemaNode node = null;
1267 final String caseLocalName = caseNode.getQName().getLocalName();
1268 if (caseNode instanceof CaseSchemaNode) {
1269 node = (CaseSchemaNode) caseNode;
1270 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1271 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1272 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1273 if (dataSchemaNode instanceof ChoiceSchemaNode
1274 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1275 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1280 node = findNamedCase(targetNode, caseLocalName);
1282 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1283 if (childNodes != null) {
1284 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1287 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1288 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1293 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1294 final SchemaPath nodePath = targetNode.getPath();
1295 final SchemaPath parentSp = nodePath.getParent();
1296 if (parentSp.getParent() == null) {
1297 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1300 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1301 GeneratedTypeBuilder childOfType = null;
1302 if (parent instanceof CaseSchemaNode) {
1303 childOfType = findCaseByPath(parent.getPath());
1304 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1305 childOfType = findChildNodeByPath(parent.getPath());
1306 } else if (parent instanceof GroupingDefinition) {
1307 childOfType = findGroupingByPath(parent.getPath());
1310 if (childOfType == null) {
1311 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1317 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1318 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1319 return cases.isEmpty() ? null : cases.get(0);
1322 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1323 // New parser with encapsulated type
1324 if (leaf.getPath().equals(type.getPath())) {
1328 // Embedded type definition with new parser. Also takes care of the old parser with bits
1329 if (leaf.getPath().equals(type.getPath().getParent())) {
1336 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1337 final List<PatternConstraint> patternConstraints) {
1338 if (!patternConstraints.isEmpty()) {
1339 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1340 .append(BindingMapping.getPropertyName(leafName));
1341 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1342 typeProvider.resolveRegExpressions(patternConstraints));
1347 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1349 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1350 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1351 * @param module Module in which type was defined
1352 * @return boolean value
1354 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1356 * <li>true - in other cases</li>
1359 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1360 final ModuleContext context, final boolean inGrouping) {
1361 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1365 final Module parentModule = findParentModule(schemaContext, leaf);
1366 Type returnType = null;
1368 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1369 if (isInnerType(leaf, typeDef)) {
1370 if (typeDef instanceof EnumTypeDefinition) {
1371 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1372 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1373 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1374 typeBuilder, context);
1375 if (enumBuilder != null) {
1376 returnType = enumBuilder.toInstance(typeBuilder);
1378 typeProvider.putReferencedType(leaf.getPath(), returnType);
1379 } else if (typeDef instanceof UnionTypeDefinition) {
1380 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1381 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1382 // Store the inner type within the union so that we can find the reference for it
1383 context.addInnerTypedefType(typeDef.getPath(), returnType);
1384 } else if (typeDef instanceof BitsTypeDefinition) {
1385 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1387 if (genTOBuilder != null) {
1388 returnType = genTOBuilder.build();
1391 // It is constrained version of already declared type (inner declared type exists,
1392 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1393 // In order to get proper class we need to look up closest derived type
1394 // and apply restrictions from leaf type
1395 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1396 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1397 restrictions, inGrouping);
1398 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1401 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1402 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1403 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1406 if (returnType == null) {
1410 if (typeDef instanceof EnumTypeDefinition) {
1411 typeProvider.putReferencedType(leaf.getPath(), returnType);
1414 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1415 processContextRefExtension(leaf, getter, parentModule);
1419 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1420 // Returns DerivedType in case of new parser.
1421 final TypeDefinition<?> baseType = typeDef.getBaseType();
1422 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1425 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1426 final Module module) {
1427 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1428 final QName nodeType = node.getNodeType();
1429 if ("context-reference".equals(nodeType.getLocalName())) {
1430 final String nodeParam = node.getNodeParameter();
1431 IdentitySchemaNode identity = null;
1432 String basePackageName = null;
1433 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1434 final Iterator<String> iterator = splittedElement.iterator();
1435 final int length = Iterables.size(splittedElement);
1437 identity = findIdentityByName(module.getIdentities(), iterator.next());
1438 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1439 } else if (length == 2) {
1440 final String prefix = iterator.next();
1441 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1442 if (dependentModule == null) {
1443 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1446 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1447 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1449 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1452 if (identity == null) {
1453 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1457 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1458 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1459 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1460 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1465 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1466 for (final IdentitySchemaNode id : identities) {
1467 if (id.getQName().getLocalName().equals(name)) {
1474 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1475 for (final ModuleImport imp : imports) {
1476 if (imp.getPrefix().equals(prefix)) {
1477 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1483 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1484 final boolean isReadOnly) {
1485 if (leaf != null && toBuilder != null) {
1487 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1488 if (typeDef instanceof UnionTypeDefinition) {
1489 // GeneratedType for this type definition should have be already created
1490 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1491 returnType = mc.getTypedefs().get(typeDef.getPath());
1492 if (returnType == null) {
1493 // This may still be an inner type, try to find it
1494 returnType = mc.getInnerType(typeDef.getPath());
1496 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1497 // Annonymous enumeration (already generated, since it is inherited via uses).
1498 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1499 QName qname = originalLeaf.getQName();
1500 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1502 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1504 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1510 * Converts <code>leaf</code> schema node to property of generated TO builder.
1512 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1513 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1514 * @param returnType property type
1515 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1516 * @return boolean value
1518 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1519 * name equals null or if leaf is added by <i>uses</i>.</li>
1520 * <li>true - other cases</li>
1523 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1524 final Type returnType, final boolean isReadOnly) {
1525 if (returnType == null) {
1528 final String leafName = leaf.getQName().getLocalName();
1529 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1530 propBuilder.setReadOnly(isReadOnly);
1531 propBuilder.setReturnType(returnType);
1532 addComment(propBuilder, leaf);
1534 toBuilder.addEqualsIdentity(propBuilder);
1535 toBuilder.addHashIdentity(propBuilder);
1536 toBuilder.addToStringProperty(propBuilder);
1541 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1543 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1544 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1545 * @param module module
1546 * @return boolean value
1548 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1549 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1550 * <li>false - other cases</li>
1553 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1554 final ModuleContext context, final boolean inGrouping) {
1555 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1559 final QName nodeName = node.getQName();
1561 final TypeDefinition<?> typeDef = node.getType();
1562 final Module parentModule = findParentModule(schemaContext, node);
1564 Type returnType = null;
1565 if (typeDef.getBaseType() == null) {
1566 if (typeDef instanceof EnumTypeDefinition) {
1567 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1568 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1569 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1570 typeBuilder, context);
1571 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1572 typeProvider.putReferencedType(node.getPath(), returnType);
1573 } else if (typeDef instanceof UnionTypeDefinition) {
1574 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1575 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1576 } else if (typeDef instanceof BitsTypeDefinition) {
1577 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1578 node, parentModule);
1579 returnType = genTOBuilder.build();
1581 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1582 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1583 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1586 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1587 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1588 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1591 constructGetter(typeBuilder, listTypeFor(returnType), node);
1595 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1596 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1597 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1598 returnTypeBuilder.setIsUnion(true);
1599 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1600 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1601 returnTypeBuilder.setModuleName(parentModule.getName());
1602 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1604 genTOBuilder.setTypedef(true);
1605 genTOBuilder.setIsUnion(true);
1606 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1608 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1612 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1613 final GeneratedTransferObject returnType, final Module parentModule) {
1614 // Append enclosing path hierarchy without dots
1615 final StringBuilder sb = new StringBuilder();
1616 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1617 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1618 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1619 unionBuilder.setIsUnionBuilder(true);
1621 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1622 method.setReturnType(returnType);
1623 method.addParameter(STRING, "defaultValue");
1624 method.setAccessModifier(AccessModifier.PUBLIC);
1625 method.setStatic(true);
1627 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1628 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1631 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1632 final SchemaNode schemaNode) {
1633 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1636 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1637 final SchemaNode schemaNode, final Type baseInterface) {
1638 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1639 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1643 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1644 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1645 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1646 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1647 * If <code>schemaNode</code> is instance of
1648 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1649 * which are specified in <i>uses</i>.
1651 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1652 * @param schemaNode schema node for which is created generated type builder
1653 * @param parent parent type (can be null)
1654 * @return generated type builder <code>schemaNode</code>
1656 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1657 final Type baseInterface, final ModuleContext context) {
1658 JavaTypeName name = renames.get(schemaNode);
1660 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1663 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1664 it.addImplementsType(baseInterface);
1665 if (!(schemaNode instanceof GroupingDefinition)) {
1666 it.addImplementsType(augmentable(it));
1668 if (schemaNode instanceof DataNodeContainer) {
1669 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1670 groupingsToGenTypes(context, containerSchema.getGroupings());
1671 addImplementedInterfaceFromUses(containerSchema, it);
1678 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1679 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1680 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1682 * @param packageName string with the package name to which returning generated type builder belongs
1683 * @param schemaNode schema node which provide data about the schema node name
1684 * @param prefix return type name prefix
1685 * @return generated type builder for <code>schemaNode</code>
1686 * @throws IllegalArgumentException
1688 * <li>if <code>schemaNode</code> is null</li>
1689 * <li>if <code>packageName</code> is null</li>
1690 * <li>if QName of schema node is null</li>
1691 * <li>if schemaNode name is null</li>
1694 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1695 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1696 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1697 final String schemaNodeName = schemaNode.getQName().getLocalName();
1698 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1700 // FIXME: Validation of name conflict
1701 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1702 final Module module = findParentModule(schemaContext, schemaNode);
1703 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1704 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1706 addCodegenInformation(newType, module, schemaNode);
1707 newType.setSchemaPath(schemaNode.getPath());
1708 newType.setModuleName(module.getName());
1710 final String packageName = identifier.packageName();
1711 final String simpleName = identifier.simpleName();
1712 if (!genTypeBuilders.containsKey(packageName)) {
1713 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1714 builders.put(simpleName, newType);
1715 genTypeBuilders.put(packageName, builders);
1717 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1718 if (!builders.containsKey(simpleName)) {
1719 builders.put(simpleName, newType);
1726 * Creates the name of the getter method name from <code>localName</code>.
1728 * @param localName string with the name of the getter method
1729 * @param returnType return type
1730 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1732 public static String getterMethodName(final String localName, final Type returnType) {
1733 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1737 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1738 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1739 * and <code>returnType</code> information are added to the builder.
1741 * @param interfaceBuilder generated type builder for which the getter method should be created
1742 * @param returnType type which represents the return type of the getter method
1743 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1744 * @param comment string with comment for the getter method
1745 * @param status status from yang file, for deprecated annotation
1746 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1748 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1749 final SchemaNode node) {
1750 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1751 getterMethodName(node.getQName().getLocalName(), returnType));
1752 getMethod.setReturnType(returnType);
1754 annotateDeprecatedIfNecessary(node, getMethod);
1755 addComment(getMethod, node);
1760 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1761 final ListSchemaNode node) {
1762 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1763 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1764 getMethod.setReturnType(returnType).setDefault(true);
1765 annotateDeprecatedIfNecessary(node, getMethod);
1769 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1772 * @param basePackageName string contains the module package name
1773 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1774 * or as a property to <code>genTOBuilder</code> if is part of the list key
1775 * @param typeBuilder generated type builder for the list schema node
1776 * @param genTOBuilder generated TO builder for the list keys
1777 * @param listKeys list of string which contains names of the list keys
1778 * @param module current module
1779 * @throws IllegalArgumentException
1781 * <li>if <code>schemaNode</code> equals null</li>
1782 * <li>if <code>typeBuilder</code> equals null</li>
1785 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1786 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1787 final List<String> listKeys, final boolean inGrouping) {
1788 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1789 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1791 if (schemaNode instanceof LeafSchemaNode) {
1792 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1793 final String leafName = leaf.getQName().getLocalName();
1794 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1795 if (listKeys.contains(leafName)) {
1797 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1799 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1802 } else if (!schemaNode.isAddedByUses()) {
1803 if (schemaNode instanceof LeafListSchemaNode) {
1804 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1805 } else if (schemaNode instanceof ContainerSchemaNode) {
1806 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1807 (ContainerSchemaNode) schemaNode, inGrouping);
1808 } else if (schemaNode instanceof ChoiceSchemaNode) {
1809 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1810 } else if (schemaNode instanceof ListSchemaNode) {
1811 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1812 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1813 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1818 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1819 final GeneratedTOBuilder genTOBuilder) {
1820 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1822 if (genTOBuilder != null) {
1823 final GeneratedTransferObject genTO = genTOBuilder.build();
1824 // Add Identifiable.getKey() for items
1825 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1826 .addAnnotation(OVERRIDE_ANNOTATION);
1827 context.addGeneratedTOBuilder(genTOBuilder);
1832 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1834 * @param list of string with names of the list keys
1835 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1836 * an empty list is returned.
1838 private static List<String> listKeys(final ListSchemaNode list) {
1839 final List<QName> keyDefinition = list.getKeyDefinition();
1840 switch (keyDefinition.size()) {
1842 return Collections.emptyList();
1844 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1846 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1847 for (final QName keyDef : keyDefinition) {
1848 listKeys.add(keyDef.getLocalName());
1855 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1856 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1857 * enclosing transfer objects.
1859 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1860 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1861 * @param leaf string with name for generated TO builder
1862 * @param parentModule parent module
1863 * @return generated TO builder for <code>typeDef</code>
1865 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1866 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1867 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1868 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1870 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1871 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1872 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1873 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1874 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1876 for (GeneratedTOBuilder builder : types) {
1877 if (builder.isUnion()) {
1878 final GeneratedTransferObject type = builder.build();
1879 createUnionBuilder(builder, typeBuilder, type, parentModule);
1883 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1887 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1888 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1889 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1892 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1893 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1894 * @param leaf string with name for generated TO builder
1895 * @param parentModule parent module
1896 * @return generated TO builder for <code>typeDef</code>
1898 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1899 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1900 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1901 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1902 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1903 return genTOBuilder;
1907 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1908 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1909 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1910 * to <code>builder</code>
1912 * @param dataNodeContainer element which contains the list of used YANG groupings
1913 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1914 * @return generated type builder with all implemented types
1916 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1917 final GeneratedTypeBuilder builder) {
1918 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1919 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1920 if (genType == null) {
1921 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1922 + builder.getName());
1925 builder.addImplementsType(genType.build());
1930 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1931 for (final ModuleContext ctx : genCtx.values()) {
1932 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1933 if (result != null) {
1940 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1941 for (final ModuleContext ctx : genCtx.values()) {
1942 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1943 if (result != null) {
1950 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1951 for (final ModuleContext ctx : genCtx.values()) {
1952 final GeneratedTypeBuilder result = ctx.getCase(path);
1953 if (result != null) {
1960 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
1961 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
1962 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
1965 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
1966 switch (node.getStatus()) {
1968 // FIXME: we really want to use a pre-made annotation
1969 builder.addAnnotation(DEPRECATED_ANNOTATION);
1972 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
1978 throw new IllegalStateException("Unhandled status in " + node);
1982 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
1983 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
1986 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
1987 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
1991 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
1992 final Type classType) {
1993 final MethodSignatureBuilder ret = typeBuilder
1994 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
1995 .setAccessModifier(AccessModifier.PUBLIC)
1996 .setReturnType(classType(classType));
1997 ret.addAnnotation(OVERRIDE_ANNOTATION);