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.mapTypeFor;
45 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
46 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
47 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
48 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
49 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
51 import com.google.common.base.Splitter;
52 import com.google.common.collect.Iterables;
53 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
54 import java.util.AbstractMap.SimpleImmutableEntry;
55 import java.util.ArrayList;
56 import java.util.Collection;
57 import java.util.Collections;
58 import java.util.Comparator;
59 import java.util.HashMap;
60 import java.util.HashSet;
61 import java.util.Iterator;
62 import java.util.List;
64 import java.util.Optional;
66 import org.eclipse.jdt.annotation.Nullable;
67 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
68 import org.opendaylight.mdsal.binding.model.api.Constant;
69 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
70 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
71 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
72 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
73 import org.opendaylight.mdsal.binding.model.api.Restrictions;
74 import org.opendaylight.mdsal.binding.model.api.Type;
75 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
76 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
83 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
84 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
85 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
86 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
87 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
88 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
89 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
90 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
91 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
92 import org.opendaylight.yangtools.yang.common.QName;
93 import org.opendaylight.yangtools.yang.common.QNameModule;
94 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
95 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
96 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
103 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
106 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
107 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
108 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
112 import org.opendaylight.yangtools.yang.model.api.Module;
113 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
114 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
115 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
116 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
117 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
118 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
119 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
120 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
121 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
122 import org.opendaylight.yangtools.yang.model.api.UsesNode;
123 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
124 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
125 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
126 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
127 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
128 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
129 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
130 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
131 import org.slf4j.Logger;
132 import org.slf4j.LoggerFactory;
134 abstract class AbstractTypeGenerator {
135 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
136 private static final Splitter COLON_SPLITTER = Splitter.on(':');
137 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
138 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
139 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
142 * Comparator based on augment target path.
144 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
145 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
146 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
148 while (thisIt.hasNext()) {
149 if (!otherIt.hasNext()) {
153 final int comp = thisIt.next().compareTo(otherIt.next());
159 return otherIt.hasNext() ? -1 : 0;
163 * Constant with the concrete name of identifier.
165 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
168 * Constant with the concrete name of namespace.
170 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
172 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
175 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
176 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
177 * for schema node specified in key part.
179 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
182 * Provide methods for converting YANG types to JAVA types.
184 private final AbstractTypeProvider typeProvider;
187 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
189 private final SchemaContext schemaContext;
192 * Holds renamed elements.
194 private final Map<SchemaNode, JavaTypeName> renames;
196 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
197 final Map<SchemaNode, JavaTypeName> renames) {
198 this.schemaContext = requireNonNull(context);
199 this.typeProvider = requireNonNull(typeProvider);
200 this.renames = requireNonNull(renames);
202 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
203 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
204 for (final Module contextModule : contextModules) {
205 contexts.add(moduleToGenTypes(contextModule));
208 contexts.forEach(this::allAugmentsToGenTypes);
211 final Collection<ModuleContext> moduleContexts() {
212 return genCtx.values();
215 final ModuleContext moduleContext(final QNameModule module) {
216 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
219 final AbstractTypeProvider typeProvider() {
223 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
225 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
227 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
228 Set<? extends SchemaNode> nodes);
230 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
232 private ModuleContext moduleToGenTypes(final Module module) {
233 final ModuleContext context = new ModuleContext(module);
234 genCtx.put(module.getQNameModule(), context);
235 allTypeDefinitionsToGenTypes(context);
236 groupingsToGenTypes(context, module.getGroupings());
237 rpcMethodsToGenType(context);
238 allIdentitiesToGenTypes(context);
239 notificationsToGenType(context);
241 if (!module.getChildNodes().isEmpty()) {
242 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
243 context.addModuleNode(moduleType);
244 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
250 * Converts all extended type definitions of module to the list of
251 * <code>Type</code> objects.
254 * module from which is obtained set of type definitions
255 * @throws IllegalArgumentException
257 * <li>if module is null</li>
258 * <li>if name of module is null</li>
260 * @throws IllegalStateException
261 * if set of type definitions from module is null
263 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
264 final Module module = context.module();
265 checkArgument(module.getName() != null, "Module name cannot be NULL.");
266 final DataNodeIterator it = new DataNodeIterator(module);
267 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
268 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
270 for (final TypeDefinition<?> typedef : typeDefinitions) {
271 if (typedef != null) {
272 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
274 context.addTypedefType(typedef, type);
275 context.addTypeToSchema(type,typedef);
281 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
282 final DataSchemaNode node, final boolean inGrouping) {
283 if (node.isAugmenting() || node.isAddedByUses()) {
286 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
287 defaultImplementedInterace(genType);
288 annotateDeprecatedIfNecessary(node, genType);
290 final Module module = context.module();
291 genType.setModuleName(module.getName());
292 addCodegenInformation(genType, module, node);
293 genType.setSchemaPath(node.getPath());
294 if (node instanceof DataNodeContainer) {
295 context.addChildNodeType(node, genType);
296 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
297 processUsesAugments((DataNodeContainer) node, context, inGrouping);
302 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
303 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
304 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
305 if (genType != null) {
306 constructGetter(parent, genType, node);
307 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
308 actionsToGenType(context, genType, node, null, inGrouping);
309 notificationsToGenType(context, genType, node, null, inGrouping);
313 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
314 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
315 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
316 if (genType != null) {
317 final List<String> listKeys = listKeys(node);
318 final GeneratedTOBuilder keyTypeBuilder;
319 if (!listKeys.isEmpty()) {
320 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
321 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
322 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
323 .addImplementsType(identifier(genType));
324 genType.addImplementsType(identifiable(keyTypeBuilder));
326 keyTypeBuilder = null;
329 // Decide whether to generate a List or a Map
330 final ParameterizedType listType;
331 if (keyTypeBuilder != null && !node.isUserOrdered()) {
332 listType = mapTypeFor(keyTypeBuilder, genType);
334 listType = listTypeFor(genType);
337 constructGetter(parent, listType, node);
338 constructNonnull(parent, listType, node);
340 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
341 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
343 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
344 if (!schemaNode.isAugmenting()) {
345 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
350 if (keyTypeBuilder != null) {
351 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
352 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
353 keyTypeBuilder.setSUID(prop);
356 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
360 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
361 final boolean inGrouping) {
362 for (final UsesNode usesNode : node.getUses()) {
363 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
364 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
365 processUsesAugments(augment, context, inGrouping);
371 * Converts all <b>augmentation</b> of the module to the list
372 * <code>Type</code> objects.
375 * module from which is obtained list of all augmentation objects
376 * to iterate over them
377 * @throws IllegalArgumentException
379 * <li>if the module is null</li>
380 * <li>if the name of module is null</li>
382 * @throws IllegalStateException
383 * if set of augmentations from module is null
385 private void allAugmentsToGenTypes(final ModuleContext context) {
386 final Module module = context.module();
387 checkArgument(module != null, "Module reference cannot be NULL.");
388 checkArgument(module.getName() != null, "Module name cannot be NULL.");
389 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
391 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
392 augmentationToGenTypes(context, augment);
397 * Returns list of <code>AugmentationSchema</code> objects. The objects are
398 * sorted according to the length of their target path from the shortest to
402 * module from which is obtained list of all augmentation objects
403 * @return list of sorted <code>AugmentationSchema</code> objects obtained
404 * from <code>module</code>
405 * @throws IllegalArgumentException
407 * @throws IllegalStateException
408 * if set of module augmentations is null
410 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
411 checkArgument(module != null, "Module reference cannot be NULL.");
412 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
414 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
415 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
416 sortedAugmentations.sort(AUGMENT_COMP);
418 return sortedAugmentations;
422 * Create GeneratedTypeBuilder object from module argument.
425 * Module object from which builder will be created
426 * @return <code>GeneratedTypeBuilder</code> which is internal
427 * representation of the module
428 * @throws IllegalArgumentException
431 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
432 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
433 final Module module = context.module();
434 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
435 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
437 addCodegenInformation(moduleDataTypeBuilder, module);
438 return moduleDataTypeBuilder;
441 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
442 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
443 for (final ActionDefinition action : parentSchema.getActions()) {
444 if (action.isAugmenting()) {
448 final GeneratedType input;
449 final GeneratedType output;
450 if (action.isAddedByUses()) {
451 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
452 input = context.getChildNode(orig.getInput().getPath()).build();
453 output = context.getChildNode(orig.getOutput().getPath()).build();
455 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
456 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
459 if (!(parentSchema instanceof GroupingDefinition)) {
460 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
461 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
462 // and do not capture an actual instantiation.
463 final QName qname = action.getQName();
464 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
465 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
466 BindingMapping.getClassName(qname)));
467 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
468 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
470 annotateDeprecatedIfNecessary(action, builder);
471 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
472 : action(parent, input, output));
474 addCodegenInformation(builder, context.module(), action);
475 context.addChildNodeType(action, builder);
480 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
481 for (UsesNode uses : parent.getUses()) {
482 final GroupingDefinition grp = findUsedGrouping(uses);
483 final Optional<ActionDefinition> found = grp.findAction(action.getQName());
484 if (found.isPresent()) {
485 final ActionDefinition result = found.get();
486 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
490 return Optional.empty();
493 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
494 final ContainerSchemaNode schema, final boolean inGrouping) {
495 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
496 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
497 return genType.build();
501 * Converts all <b>RPCs</b> input and output substatements of the module
502 * to the list of <code>Type</code> objects. In addition are to containers
503 * and lists which belong to input or output also part of returning list.
506 * module from which is obtained set of all rpc objects to
508 * @throws IllegalArgumentException
510 * <li>if the module is null</li>
511 * <li>if the name of module is null</li>
513 * @throws IllegalStateException
514 * if set of rpcs from module is null
516 private void rpcMethodsToGenType(final ModuleContext context) {
517 final Module module = context.module();
518 checkArgument(module.getName() != null, "Module name cannot be NULL.");
519 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
520 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
521 if (rpcDefinitions.isEmpty()) {
525 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
526 interfaceBuilder.addImplementsType(RPC_SERVICE);
528 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
530 for (final RpcDefinition rpc : rpcDefinitions) {
532 final String rpcName = BindingMapping.getClassName(rpc.getQName());
533 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
534 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
536 // Do not refer to annotation class, as it may not be available at runtime
537 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
538 addComment(method, rpc);
540 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
541 method.setReturnType(listenableFutureTypeFor(
542 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
546 context.addTopLevelNodeType(interfaceBuilder);
549 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
550 final ContainerSchemaNode schema, final Type type) {
551 processUsesAugments(schema, context, false);
552 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
553 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
555 addImplementedInterfaceFromUses(schema, outType);
556 outType.addImplementsType(type);
557 outType.addImplementsType(augmentable(outType));
558 defaultImplementedInterace(outType);
559 annotateDeprecatedIfNecessary(rpc, outType);
560 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
561 context.addChildNodeType(schema, outType);
562 return outType.build();
566 * Converts all <b>notifications</b> of the module to the list of
567 * <code>Type</code> objects. In addition are to this list added containers
568 * and lists which are part of this notification.
571 * module from which is obtained set of all notification objects
572 * to iterate over them
573 * @throws IllegalArgumentException
575 * <li>if the module equals null</li>
576 * <li>if the name of module equals null</li>
578 * @throws IllegalStateException
579 * if set of notifications from module is null
581 private void notificationsToGenType(final ModuleContext context) {
582 final Module module = context.module();
583 checkArgument(module.getName() != null, "Module name cannot be NULL.");
584 final Set<NotificationDefinition> notifications = module.getNotifications();
585 if (notifications.isEmpty()) {
589 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
590 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
592 for (final NotificationDefinition notification : notifications) {
593 if (notification != null) {
594 processUsesAugments(notification, context, false);
596 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
597 context.modulePackageName(), notification, DATA_OBJECT, context);
598 defaultImplementedInterace(notificationInterface);
599 annotateDeprecatedIfNecessary(notification, notificationInterface);
600 notificationInterface.addImplementsType(NOTIFICATION);
601 context.addChildNodeType(notification, notificationInterface);
603 // Notification object
604 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
605 notification.getChildNodes(), false);
607 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
608 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
609 .setReturnType(primitiveVoidType()), notification);
613 addCodegenInformation(listenerInterface, module, "notifications", notifications);
614 context.addTopLevelNodeType(listenerInterface);
617 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
618 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
619 final boolean inGrouping) {
620 final Set<NotificationDefinition> notifications = parentSchema.getNotifications();
621 if (notifications.isEmpty()) {
625 for (NotificationDefinition notif : notifications) {
626 if (notif.isAugmenting()) {
629 if (parentSchema instanceof GroupingDefinition) {
630 // Notifications cannot be really established, as they lack instantiation context, which would be
631 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
635 processUsesAugments(notif, context, false);
637 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
638 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
639 defaultImplementedInterace(notifInterface);
640 annotateDeprecatedIfNecessary(notif, notifInterface);
642 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
643 : instanceNotification(notifInterface, parent));
644 context.addChildNodeType(notif, notifInterface);
646 // Notification object
647 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
652 * Converts all <b>identities</b> of the module to the list of
653 * <code>Type</code> objects.
656 * module from which is obtained set of all identity objects to
658 * @param schemaContext
659 * schema context only used as input parameter for method
660 * {@link BindingGeneratorImpl#identityToGenType}
663 private void allIdentitiesToGenTypes(final ModuleContext context) {
664 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
666 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
667 for (final IdentitySchemaNode identity : schemaIdentities) {
668 identityToGenType(context, identity);
674 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
675 * created transport object builder. If identity contains base identity then
676 * reference to base identity is added to superior identity as its extend.
677 * If identity doesn't contain base identity then only reference to abstract
678 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
679 * BaseIdentity} is added
683 * @param basePackageName
684 * string contains the module package name
686 * IdentitySchemaNode which contains data about identity
688 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
689 if (identity == null) {
693 JavaTypeName name = renames.get(identity);
695 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
696 BindingMapping.getClassName(identity.getQName()));
699 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
700 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
701 if (!baseIdentities.isEmpty()) {
702 for (IdentitySchemaNode baseIdentity : baseIdentities) {
703 JavaTypeName base = renames.get(baseIdentity);
705 final QName qname = baseIdentity.getQName();
706 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
707 BindingMapping.getClassName(qname));
710 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
711 newType.addImplementsType(gto);
714 newType.addImplementsType(BASE_IDENTITY);
717 final Module module = context.module();
718 addCodegenInformation(newType, module, identity);
719 newType.setModuleName(module.getName());
720 newType.setSchemaPath(identity.getPath());
722 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
723 identity.getQName().getLocalName());
725 context.addIdentityType(identity, newType);
728 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
729 final JavaTypeName yangModuleInfo, final String localName) {
730 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
731 new SimpleImmutableEntry<>(yangModuleInfo, localName));
735 * Converts all <b>groupings</b> of the module to the list of
736 * <code>Type</code> objects. Firstly are groupings sorted according mutual
737 * dependencies. At least dependent (independent) groupings are in the list
738 * saved at first positions. For every grouping the record is added to map
739 * {@link ModuleContext#groupings allGroupings}
744 * collection of groupings from which types will be generated
747 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
748 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
749 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
750 // node of grouping is resolved to the method.
751 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
752 narrowImplementedInterface(genType);
753 annotateDeprecatedIfNecessary(grouping, genType);
754 context.addGroupingType(grouping, genType);
755 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
756 groupingsToGenTypes(context, grouping.getGroupings());
757 processUsesAugments(grouping, context, true);
758 actionsToGenType(context, genType, grouping, null, true);
759 notificationsToGenType(context, genType, grouping, null, true);
764 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
765 * <code>enumTypeDef</code> item is added to builder with its name and value.
767 * @param enumTypeDef EnumTypeDefinition contains enum data
768 * @param enumName string contains name which will be assigned to enumeration builder
769 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
770 * @param module Module in which type should be generated
771 * @return enumeration builder which contains data from <code>enumTypeDef</code>
773 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
774 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
775 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
776 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
777 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
778 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
779 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
786 * Generates type builder for <code>module</code>.
788 * @param module Module which is source of package name for generated type builder
789 * @param postfix string which is added to the module class name representation as suffix
790 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
791 * @throws IllegalArgumentException if <code>module</code> is null
793 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
794 final Module module = context.module();
795 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
796 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
797 JavaTypeName.create(context.modulePackageName(), moduleName));
799 moduleBuilder.setModuleName(moduleName);
800 addCodegenInformation(moduleBuilder, module);
801 return moduleBuilder;
805 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
806 * In addition there are also generated types for all containers, list and choices which are child of
807 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
809 * @param augmentPackageName string with the name of the package to which the augmentation belongs
810 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
811 * @param module current module
812 * @throws IllegalArgumentException
814 * <li>if <code>augmentPackageName</code> equals null</li>
815 * <li>if <code>augSchema</code> equals null</li>
817 * @throws IllegalStateException
818 * if augment target path is null
820 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
821 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
822 checkState(augSchema.getTargetPath() != null,
823 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
825 processUsesAugments(augSchema, context, false);
826 final SchemaPath targetPath = augSchema.getTargetPath();
827 SchemaNode targetSchemaNode = null;
829 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
830 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
831 if (targetSchemaNode instanceof DerivableSchemaNode) {
832 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
834 if (targetSchemaNode == null) {
835 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
836 + " in module " + context.module().getName());
839 if (targetSchemaNode == null) {
840 throw new IllegalArgumentException("augment target not found: " + targetPath);
843 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
844 if (targetTypeBuilder == null) {
845 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
847 if (targetTypeBuilder == null) {
848 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
851 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
852 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
853 addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
856 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
857 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
861 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
862 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
863 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
864 checkState(augSchema.getTargetPath() != null,
865 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
867 processUsesAugments(augSchema, context, inGrouping);
868 final SchemaPath targetPath = augSchema.getTargetPath();
869 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
870 if (targetSchemaNode == null) {
871 throw new IllegalArgumentException("augment target not found: " + targetPath);
874 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
875 if (targetTypeBuilder == null) {
876 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
878 if (targetTypeBuilder == null) {
879 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
882 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
883 if (usesNodeParent instanceof SchemaNode) {
884 addRawAugmentGenTypeDefinition(context,
885 packageNameForAugmentedGeneratedType(context.modulePackageName(),
886 ((SchemaNode) usesNodeParent).getPath()),
887 targetTypeBuilder.build(), augSchema, inGrouping);
889 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
892 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
893 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
897 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
898 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
900 if (targetGrouping instanceof GroupingDefinition) {
901 return (GroupingDefinition) targetGrouping;
904 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
908 * Convenient method to find node added by uses statement.
910 * @param targetPath node path
911 * @param parentUsesNode parent of uses node
912 * @return node from its original location in grouping
914 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
915 SchemaNode result = findUsedGrouping(parentUsesNode);
916 for (final QName node : targetPath.getPathFromRoot()) {
917 if (result instanceof DataNodeContainer) {
918 final QName resultNode = node.withModule(result.getQName().getModule());
919 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
920 } else if (result instanceof ChoiceSchemaNode) {
921 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
924 if (result == null) {
928 if (result instanceof DerivableSchemaNode) {
929 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
930 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
931 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
932 result = originalNode.get();
936 if (result instanceof DataSchemaNode) {
937 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
938 if (resultDataSchemaNode.isAddedByUses()) {
939 // The original node is required, but we have only the copy of
940 // the original node.
941 // Maybe this indicates a bug in Yang parser.
942 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
945 return resultDataSchemaNode;
948 throw new IllegalStateException(
949 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
954 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
955 * of augmented node with serial number as suffix.
957 * @param context current module
958 * @param augmentPackageName string with contains the package name to which the augment belongs
959 * @param basePackageName string with the package name to which the augmented node belongs
960 * @param targetTypeRef target type
961 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
962 * @return generated type builder for augment
964 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
965 final String augmentPackageName, final Type targetTypeRef,
966 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
967 Map<String, GeneratedTypeBuilder> augmentBuilders =
968 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
969 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
972 if (augIdentifier != null) {
973 augTypeName = BindingMapping.getClassName(augIdentifier);
975 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
978 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
979 JavaTypeName.create(augmentPackageName, augTypeName));
981 augTypeBuilder.addImplementsType(DATA_OBJECT);
982 defaultImplementedInterace(augTypeBuilder);
984 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
985 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
986 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
988 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
989 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
990 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
992 augmentBuilders.put(augTypeName, augTypeBuilder);
994 if (!augSchema.getChildNodes().isEmpty()) {
995 context.addTypeToAugmentation(augTypeBuilder, augSchema);
998 context.addAugmentType(augTypeBuilder);
999 return augTypeBuilder;
1002 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1003 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1004 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1008 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1009 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1010 final QName nodeType = unknownSchemaNode.getNodeType();
1011 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1012 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1013 return unknownSchemaNode.getNodeParameter();
1020 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1021 * consists from name of augmented node and serial number of its augmentation.
1023 * @param builders map of builders which were created in the package to which the augmentation belongs
1024 * @param genTypeName string with name of augmented node
1025 * @return string with unique name for augmentation builder
1027 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1029 if (builders != null) {
1030 while (builders.containsKey(genTypeName + index)) {
1034 return genTypeName + index;
1038 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1039 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1040 * already part of them).
1042 * @param module current module
1043 * @param parent generated type builder which represents any node. The subnodes of this node are added
1044 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1045 * container, choice.
1046 * @param childOf parent type
1047 * @param schemaNodes set of data schema nodes which are the children of the node for which
1048 * <code>typeBuilder</code> was created
1049 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1050 * child nodes) could be added to it.
1052 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1053 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
1054 if (schemaNodes != null && parent != null) {
1055 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1056 for (final DataSchemaNode schemaNode : schemaNodes) {
1057 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1058 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1066 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1069 * @param module current module
1070 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1071 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1072 * container, choice.
1073 * @param childOf parent type
1074 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1076 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1077 * The getter method could be added to it.
1079 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1080 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1081 final boolean inGrouping) {
1082 if (schemaNodes != null && typeBuilder != null) {
1083 final Type baseInterface = childOf(typeBuilder);
1084 for (final DataSchemaNode schemaNode : schemaNodes) {
1085 if (!schemaNode.isAugmenting()) {
1086 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1094 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1096 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1097 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1098 * @param childOf parent type
1099 * @param module current module
1101 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1102 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1103 if (node != null && typeBuilder != null) {
1104 if (node instanceof LeafSchemaNode) {
1105 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1106 } else if (node instanceof LeafListSchemaNode) {
1107 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1108 } else if (node instanceof ContainerSchemaNode) {
1109 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1110 } else if (node instanceof ListSchemaNode) {
1111 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1112 } else if (node instanceof ChoiceSchemaNode) {
1113 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1114 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1115 opaqueToGeneratedType(context, typeBuilder, node);
1117 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1118 typeBuilder.getFullyQualifiedName());
1124 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1125 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1126 * and names of all parents node.
1128 * @param context current module
1129 * @param basePackageName string with the module package name
1130 * @param parent parent type
1131 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1133 * @throws IllegalArgumentException
1135 * <li>if <code>basePackageName</code> is null</li>
1136 * <li>if <code>choiceNode</code> is null</li>
1139 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1140 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1141 if (!choiceNode.isAddedByUses()) {
1142 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1143 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1144 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1145 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1146 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1147 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1149 final GeneratedType choiceType = choiceTypeBuilder.build();
1150 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1152 constructGetter(parent, choiceType, choiceNode);
1156 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1157 final DataSchemaNode anyNode) {
1158 if (!anyNode.isAddedByUses()) {
1159 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(
1160 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1161 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1162 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1163 defaultImplementedInterace(anyxmlTypeBuilder);
1164 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1165 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1167 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1172 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1173 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1174 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1175 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1177 * @param context current module context
1178 * @param refChoiceType type which represents superior <i>case</i>
1179 * @param choiceNode choice case node which is mapped to generated type
1180 * @throws IllegalArgumentException
1182 * <li>if <code>refChoiceType</code> equals null</li>
1183 * <li>if <code>caseNodes</code> equals null</li>
1186 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1187 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1188 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1189 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1191 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1192 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1193 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1194 caseTypeBuilder.addImplementsType(refChoiceType);
1195 defaultImplementedInterace(caseTypeBuilder);
1196 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1197 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1198 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1199 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1200 if (caseChildNodes != null) {
1201 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1203 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1204 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1206 if (parent instanceof AugmentationSchemaNode) {
1207 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1208 final SchemaPath targetPath = augSchema.getTargetPath();
1209 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1210 if (targetSchemaNode instanceof DataSchemaNode
1211 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1212 if (targetSchemaNode instanceof DerivableSchemaNode) {
1213 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1216 if (targetSchemaNode == null) {
1217 throw new IllegalStateException(
1218 "Failed to find target node from grouping for augmentation " + augSchema
1219 + " in module " + context.module().getName());
1222 parent = targetSchemaNode;
1225 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1226 Type childOfType = findChildNodeByPath(parent.getPath());
1227 if (childOfType == null) {
1228 childOfType = findGroupingByPath(parent.getPath());
1230 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1232 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1237 processUsesAugments(caseNode, context, inGrouping);
1242 * Generates list of generated types for all the cases of a choice which are added to the choice through
1245 * @param module current module
1246 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1247 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1248 * of the augmenting choice will belong to pcg2.
1249 * @param targetType Type which represents target choice
1250 * @param targetNode node which represents target choice
1251 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1253 * @throws IllegalArgumentException
1255 * <li>if <code>basePackageName</code> is null</li>
1256 * <li>if <code>targetType</code> is null</li>
1257 * <li>if <code>augmentedNodes</code> is null</li>
1260 // FIXME: nullness rules need to untangled in this method
1261 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1262 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1263 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1264 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1265 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1266 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1268 for (final DataSchemaNode caseNode : augmentedNodes) {
1269 if (caseNode != null) {
1270 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1271 caseTypeBuilder.addImplementsType(targetType);
1272 defaultImplementedInterace(caseTypeBuilder);
1274 CaseSchemaNode node = null;
1275 final String caseLocalName = caseNode.getQName().getLocalName();
1276 if (caseNode instanceof CaseSchemaNode) {
1277 node = (CaseSchemaNode) caseNode;
1278 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1279 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1280 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1281 if (dataSchemaNode instanceof ChoiceSchemaNode
1282 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1283 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1288 node = findNamedCase(targetNode, caseLocalName);
1290 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1291 if (childNodes != null) {
1292 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1295 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1296 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1301 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1302 final SchemaPath nodePath = targetNode.getPath();
1303 final SchemaPath parentSp = nodePath.getParent();
1304 if (parentSp.getParent() == null) {
1305 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1308 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1309 GeneratedTypeBuilder childOfType = null;
1310 if (parent instanceof CaseSchemaNode) {
1311 childOfType = findCaseByPath(parent.getPath());
1312 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1313 childOfType = findChildNodeByPath(parent.getPath());
1314 } else if (parent instanceof GroupingDefinition) {
1315 childOfType = findGroupingByPath(parent.getPath());
1318 if (childOfType == null) {
1319 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1325 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1326 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1327 return cases.isEmpty() ? null : cases.get(0);
1330 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1331 // New parser with encapsulated type
1332 if (leaf.getPath().equals(type.getPath())) {
1336 // Embedded type definition with new parser. Also takes care of the old parser with bits
1337 if (leaf.getPath().equals(type.getPath().getParent())) {
1344 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1345 final List<PatternConstraint> patternConstraints) {
1346 if (!patternConstraints.isEmpty()) {
1347 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1348 .append(BindingMapping.getPropertyName(leafName));
1349 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1350 typeProvider.resolveRegExpressions(patternConstraints));
1355 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1357 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1358 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1359 * @param module Module in which type was defined
1360 * @return boolean value
1362 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1364 * <li>true - in other cases</li>
1367 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1368 final ModuleContext context, final boolean inGrouping) {
1369 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1373 final Module parentModule = findParentModule(schemaContext, leaf);
1374 Type returnType = null;
1376 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1377 if (isInnerType(leaf, typeDef)) {
1378 if (typeDef instanceof EnumTypeDefinition) {
1379 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1380 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1381 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1382 typeBuilder, context);
1383 if (enumBuilder != null) {
1384 returnType = enumBuilder.toInstance(typeBuilder);
1386 typeProvider.putReferencedType(leaf.getPath(), returnType);
1387 } else if (typeDef instanceof UnionTypeDefinition) {
1388 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1389 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1390 // Store the inner type within the union so that we can find the reference for it
1391 context.addInnerTypedefType(typeDef.getPath(), returnType);
1392 } else if (typeDef instanceof BitsTypeDefinition) {
1393 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1395 if (genTOBuilder != null) {
1396 returnType = genTOBuilder.build();
1399 // It is constrained version of already declared type (inner declared type exists,
1400 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1401 // In order to get proper class we need to look up closest derived type
1402 // and apply restrictions from leaf type
1403 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1404 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1405 restrictions, inGrouping);
1406 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1409 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1410 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1411 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1414 if (returnType == null) {
1418 if (typeDef instanceof EnumTypeDefinition) {
1419 typeProvider.putReferencedType(leaf.getPath(), returnType);
1422 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1423 processContextRefExtension(leaf, getter, parentModule);
1427 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1428 // Returns DerivedType in case of new parser.
1429 final TypeDefinition<?> baseType = typeDef.getBaseType();
1430 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1433 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1434 final Module module) {
1435 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1436 final QName nodeType = node.getNodeType();
1437 if ("context-reference".equals(nodeType.getLocalName())) {
1438 final String nodeParam = node.getNodeParameter();
1439 IdentitySchemaNode identity = null;
1440 String basePackageName = null;
1441 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1442 final Iterator<String> iterator = splittedElement.iterator();
1443 final int length = Iterables.size(splittedElement);
1445 identity = findIdentityByName(module.getIdentities(), iterator.next());
1446 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1447 } else if (length == 2) {
1448 final String prefix = iterator.next();
1449 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1450 if (dependentModule == null) {
1451 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1454 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1455 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1457 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1460 if (identity == null) {
1461 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1465 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1466 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1467 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1468 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1473 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1474 for (final IdentitySchemaNode id : identities) {
1475 if (id.getQName().getLocalName().equals(name)) {
1482 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1483 for (final ModuleImport imp : imports) {
1484 if (imp.getPrefix().equals(prefix)) {
1485 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1491 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1492 final boolean isReadOnly) {
1493 if (leaf != null && toBuilder != null) {
1495 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1496 if (typeDef instanceof UnionTypeDefinition) {
1497 // GeneratedType for this type definition should have be already created
1498 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1499 returnType = mc.getTypedefs().get(typeDef.getPath());
1500 if (returnType == null) {
1501 // This may still be an inner type, try to find it
1502 returnType = mc.getInnerType(typeDef.getPath());
1504 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1505 // Annonymous enumeration (already generated, since it is inherited via uses).
1506 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1507 QName qname = originalLeaf.getQName();
1508 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1510 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1512 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1518 * Converts <code>leaf</code> schema node to property of generated TO builder.
1520 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1521 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1522 * @param returnType property type
1523 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1524 * @return boolean value
1526 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1527 * name equals null or if leaf is added by <i>uses</i>.</li>
1528 * <li>true - other cases</li>
1531 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1532 final Type returnType, final boolean isReadOnly) {
1533 if (returnType == null) {
1536 final String leafName = leaf.getQName().getLocalName();
1537 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1538 propBuilder.setReadOnly(isReadOnly);
1539 propBuilder.setReturnType(returnType);
1540 addComment(propBuilder, leaf);
1542 toBuilder.addEqualsIdentity(propBuilder);
1543 toBuilder.addHashIdentity(propBuilder);
1544 toBuilder.addToStringProperty(propBuilder);
1549 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1551 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1552 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1553 * @param module module
1554 * @return boolean value
1556 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1557 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1558 * <li>false - other cases</li>
1561 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1562 final ModuleContext context, final boolean inGrouping) {
1563 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1567 final QName nodeName = node.getQName();
1569 final TypeDefinition<?> typeDef = node.getType();
1570 final Module parentModule = findParentModule(schemaContext, node);
1572 Type returnType = null;
1573 if (typeDef.getBaseType() == null) {
1574 if (typeDef instanceof EnumTypeDefinition) {
1575 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1576 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1577 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1578 typeBuilder, context);
1579 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1580 typeProvider.putReferencedType(node.getPath(), returnType);
1581 } else if (typeDef instanceof UnionTypeDefinition) {
1582 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1583 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1584 } else if (typeDef instanceof BitsTypeDefinition) {
1585 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1586 node, parentModule);
1587 returnType = genTOBuilder.build();
1589 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1590 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1591 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1594 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1595 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1596 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1599 constructGetter(typeBuilder, listTypeFor(returnType), node);
1603 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1604 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1605 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1606 returnTypeBuilder.setIsUnion(true);
1607 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1608 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1609 returnTypeBuilder.setModuleName(parentModule.getName());
1610 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1612 genTOBuilder.setTypedef(true);
1613 genTOBuilder.setIsUnion(true);
1614 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1616 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1620 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1621 final GeneratedTransferObject returnType, final Module parentModule) {
1622 // Append enclosing path hierarchy without dots
1623 final StringBuilder sb = new StringBuilder();
1624 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1625 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1626 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1627 unionBuilder.setIsUnionBuilder(true);
1629 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1630 method.setReturnType(returnType);
1631 method.addParameter(STRING, "defaultValue");
1632 method.setAccessModifier(AccessModifier.PUBLIC);
1633 method.setStatic(true);
1635 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1636 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1639 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1640 final SchemaNode schemaNode) {
1641 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1644 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1645 final SchemaNode schemaNode, final Type baseInterface) {
1646 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1647 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1651 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1652 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1653 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1654 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1655 * If <code>schemaNode</code> is instance of
1656 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1657 * which are specified in <i>uses</i>.
1659 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1660 * @param schemaNode schema node for which is created generated type builder
1661 * @param parent parent type (can be null)
1662 * @return generated type builder <code>schemaNode</code>
1664 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1665 final Type baseInterface, final ModuleContext context) {
1666 JavaTypeName name = renames.get(schemaNode);
1668 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1671 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1672 it.addImplementsType(baseInterface);
1673 if (!(schemaNode instanceof GroupingDefinition)) {
1674 it.addImplementsType(augmentable(it));
1676 if (schemaNode instanceof DataNodeContainer) {
1677 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1678 groupingsToGenTypes(context, containerSchema.getGroupings());
1679 addImplementedInterfaceFromUses(containerSchema, it);
1686 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1687 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1688 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1690 * @param packageName string with the package name to which returning generated type builder belongs
1691 * @param schemaNode schema node which provide data about the schema node name
1692 * @param prefix return type name prefix
1693 * @return generated type builder for <code>schemaNode</code>
1694 * @throws IllegalArgumentException
1696 * <li>if <code>schemaNode</code> is null</li>
1697 * <li>if <code>packageName</code> is null</li>
1698 * <li>if QName of schema node is null</li>
1699 * <li>if schemaNode name is null</li>
1702 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1703 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1704 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1705 final String schemaNodeName = schemaNode.getQName().getLocalName();
1706 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1708 // FIXME: Validation of name conflict
1709 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1710 final Module module = findParentModule(schemaContext, schemaNode);
1711 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1712 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1714 addCodegenInformation(newType, module, schemaNode);
1715 newType.setSchemaPath(schemaNode.getPath());
1716 newType.setModuleName(module.getName());
1718 final String packageName = identifier.packageName();
1719 final String simpleName = identifier.simpleName();
1720 if (!genTypeBuilders.containsKey(packageName)) {
1721 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1722 builders.put(simpleName, newType);
1723 genTypeBuilders.put(packageName, builders);
1725 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1726 if (!builders.containsKey(simpleName)) {
1727 builders.put(simpleName, newType);
1734 * Creates the name of the getter method name from <code>localName</code>.
1736 * @param localName string with the name of the getter method
1737 * @param returnType return type
1738 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1740 public static String getterMethodName(final String localName, final Type returnType) {
1741 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1745 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1746 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1747 * and <code>returnType</code> information are added to the builder.
1749 * @param interfaceBuilder generated type builder for which the getter method should be created
1750 * @param returnType type which represents the return type of the getter method
1751 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1752 * @param comment string with comment for the getter method
1753 * @param status status from yang file, for deprecated annotation
1754 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1756 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1757 final SchemaNode node) {
1758 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1759 getterMethodName(node.getQName().getLocalName(), returnType));
1760 getMethod.setReturnType(returnType);
1762 annotateDeprecatedIfNecessary(node, getMethod);
1763 addComment(getMethod, node);
1768 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1769 final ListSchemaNode node) {
1770 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1771 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1772 getMethod.setReturnType(returnType).setDefault(true);
1773 annotateDeprecatedIfNecessary(node, getMethod);
1777 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1780 * @param basePackageName string contains the module package name
1781 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1782 * or as a property to <code>genTOBuilder</code> if is part of the list key
1783 * @param typeBuilder generated type builder for the list schema node
1784 * @param genTOBuilder generated TO builder for the list keys
1785 * @param listKeys list of string which contains names of the list keys
1786 * @param module current module
1787 * @throws IllegalArgumentException
1789 * <li>if <code>schemaNode</code> equals null</li>
1790 * <li>if <code>typeBuilder</code> equals null</li>
1793 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1794 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1795 final List<String> listKeys, final boolean inGrouping) {
1796 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1797 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1799 if (schemaNode instanceof LeafSchemaNode) {
1800 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1801 final String leafName = leaf.getQName().getLocalName();
1802 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1803 if (listKeys.contains(leafName)) {
1805 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1807 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1810 } else if (!schemaNode.isAddedByUses()) {
1811 if (schemaNode instanceof LeafListSchemaNode) {
1812 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1813 } else if (schemaNode instanceof ContainerSchemaNode) {
1814 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1815 (ContainerSchemaNode) schemaNode, inGrouping);
1816 } else if (schemaNode instanceof ChoiceSchemaNode) {
1817 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1818 } else if (schemaNode instanceof ListSchemaNode) {
1819 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1820 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1821 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1826 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1827 final GeneratedTOBuilder genTOBuilder) {
1828 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1830 if (genTOBuilder != null) {
1831 final GeneratedTransferObject genTO = genTOBuilder.build();
1832 // Add Identifiable.getKey() for items
1833 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1834 .addAnnotation(OVERRIDE_ANNOTATION);
1835 context.addGeneratedTOBuilder(genTOBuilder);
1840 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1842 * @param list of string with names of the list keys
1843 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1844 * an empty list is returned.
1846 private static List<String> listKeys(final ListSchemaNode list) {
1847 final List<QName> keyDefinition = list.getKeyDefinition();
1848 switch (keyDefinition.size()) {
1850 return Collections.emptyList();
1852 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1854 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1855 for (final QName keyDef : keyDefinition) {
1856 listKeys.add(keyDef.getLocalName());
1863 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1864 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1865 * enclosing transfer objects.
1867 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1868 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1869 * @param leaf string with name for generated TO builder
1870 * @param parentModule parent module
1871 * @return generated TO builder for <code>typeDef</code>
1873 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1874 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1875 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1876 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1878 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1879 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1880 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1881 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1882 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1884 for (GeneratedTOBuilder builder : types) {
1885 if (builder.isUnion()) {
1886 final GeneratedTransferObject type = builder.build();
1887 createUnionBuilder(builder, typeBuilder, type, parentModule);
1891 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1895 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1896 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1897 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1900 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1901 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1902 * @param leaf string with name for generated TO builder
1903 * @param parentModule parent module
1904 * @return generated TO builder for <code>typeDef</code>
1906 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1907 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1908 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1909 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1910 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1911 return genTOBuilder;
1915 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1916 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1917 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1918 * to <code>builder</code>
1920 * @param dataNodeContainer element which contains the list of used YANG groupings
1921 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1922 * @return generated type builder with all implemented types
1924 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1925 final GeneratedTypeBuilder builder) {
1926 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1927 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1928 if (genType == null) {
1929 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1930 + builder.getName());
1933 builder.addImplementsType(genType.build());
1938 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1939 for (final ModuleContext ctx : genCtx.values()) {
1940 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1941 if (result != null) {
1948 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1949 for (final ModuleContext ctx : genCtx.values()) {
1950 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1951 if (result != null) {
1958 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1959 for (final ModuleContext ctx : genCtx.values()) {
1960 final GeneratedTypeBuilder result = ctx.getCase(path);
1961 if (result != null) {
1968 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
1969 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
1970 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
1973 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
1974 switch (node.getStatus()) {
1976 // FIXME: we really want to use a pre-made annotation
1977 builder.addAnnotation(DEPRECATED_ANNOTATION);
1980 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
1986 throw new IllegalStateException("Unhandled status in " + node);
1990 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
1991 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
1994 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
1995 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
1999 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2000 final Type classType) {
2001 final MethodSignatureBuilder ret = typeBuilder
2002 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2003 .setAccessModifier(AccessModifier.PUBLIC)
2004 .setReturnType(classType(classType));
2005 ret.addAnnotation(OVERRIDE_ANNOTATION);