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.primitiveBooleanType;
46 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveIntType;
47 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
48 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
49 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
50 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
51 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
53 import com.google.common.base.Splitter;
54 import com.google.common.collect.Iterables;
55 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
56 import java.util.AbstractMap.SimpleImmutableEntry;
57 import java.util.ArrayList;
58 import java.util.Collection;
59 import java.util.Collections;
60 import java.util.Comparator;
61 import java.util.HashMap;
62 import java.util.HashSet;
63 import java.util.Iterator;
64 import java.util.List;
66 import java.util.Optional;
67 import org.eclipse.jdt.annotation.NonNull;
68 import org.eclipse.jdt.annotation.Nullable;
69 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
70 import org.opendaylight.mdsal.binding.model.api.Constant;
71 import org.opendaylight.mdsal.binding.model.api.DefaultType;
72 import org.opendaylight.mdsal.binding.model.api.Enumeration;
73 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
74 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
75 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
76 import org.opendaylight.mdsal.binding.model.api.MethodSignature.ValueMechanics;
77 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
78 import org.opendaylight.mdsal.binding.model.api.Restrictions;
79 import org.opendaylight.mdsal.binding.model.api.Type;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
83 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
84 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
85 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
86 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
87 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
88 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
89 import org.opendaylight.mdsal.binding.model.util.BaseYangTypes;
90 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
91 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
92 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
93 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
94 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
95 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
96 import org.opendaylight.yangtools.yang.common.QName;
97 import org.opendaylight.yangtools.yang.common.QNameModule;
98 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
99 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
100 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
106 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
108 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
111 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
112 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
113 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
114 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.InputSchemaNode;
116 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
117 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
118 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
119 import org.opendaylight.yangtools.yang.model.api.Module;
120 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
121 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
122 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
123 import org.opendaylight.yangtools.yang.model.api.OutputSchemaNode;
124 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
125 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
126 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
127 import org.opendaylight.yangtools.yang.model.api.Status;
128 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
129 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
130 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
131 import org.opendaylight.yangtools.yang.model.api.UsesNode;
132 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
133 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
134 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
135 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
136 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
137 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
138 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
139 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
140 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
141 import org.slf4j.Logger;
142 import org.slf4j.LoggerFactory;
144 abstract class AbstractTypeGenerator {
145 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
146 private static final Splitter COLON_SPLITTER = Splitter.on(':');
147 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
148 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
149 private static final JavaTypeName CHECK_RETURN_VALUE_ANNOTATION =
150 // Do not refer to annotation class, as it may not be available at runtime
151 JavaTypeName.create("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
152 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
155 * Comparator based on augment target path.
157 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
158 final Iterator<QName> thisIt = o1.getTargetPath().getNodeIdentifiers().iterator();
159 final Iterator<QName> otherIt = o2.getTargetPath().getNodeIdentifiers().iterator();
161 while (thisIt.hasNext()) {
162 if (!otherIt.hasNext()) {
166 final int comp = thisIt.next().compareTo(otherIt.next());
172 return otherIt.hasNext() ? -1 : 0;
176 * Constant with the concrete name of identifier.
178 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
181 * Constant with the concrete name of namespace.
183 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
185 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
188 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
189 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
190 * for schema node specified in key part.
192 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
195 * Provide methods for converting YANG types to JAVA types.
197 private final AbstractTypeProvider typeProvider;
200 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
202 private final @NonNull EffectiveModelContext schemaContext;
205 * Holds renamed elements.
207 private final Map<SchemaNode, JavaTypeName> renames;
209 AbstractTypeGenerator(final EffectiveModelContext context, final AbstractTypeProvider typeProvider,
210 final Map<SchemaNode, JavaTypeName> renames) {
211 this.schemaContext = requireNonNull(context);
212 this.typeProvider = requireNonNull(typeProvider);
213 this.renames = requireNonNull(renames);
215 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
216 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
217 for (final Module contextModule : contextModules) {
218 contexts.add(moduleToGenTypes(contextModule));
221 contexts.forEach(this::allAugmentsToGenTypes);
224 final @NonNull EffectiveModelContext schemaContext() {
225 return schemaContext;
228 final Collection<ModuleContext> moduleContexts() {
229 return genCtx.values();
232 final ModuleContext moduleContext(final QNameModule module) {
233 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
236 final AbstractTypeProvider typeProvider() {
240 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
242 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
244 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
245 Collection<? extends SchemaNode> nodes);
247 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
249 abstract void addRpcMethodComment(TypeMemberBuilder<?> genType, RpcDefinition node);
251 private ModuleContext moduleToGenTypes(final Module module) {
252 final ModuleContext context = new ModuleContext(module);
253 genCtx.put(module.getQNameModule(), context);
254 allTypeDefinitionsToGenTypes(context);
255 groupingsToGenTypes(context, module.getGroupings());
256 allIdentitiesToGenTypes(context);
258 if (!module.getChildNodes().isEmpty()) {
259 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
260 context.addModuleNode(moduleType);
261 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
264 // Resolve RPCs and notifications only after we have created instantiated tree
265 rpcMethodsToGenType(context);
266 notificationsToGenType(context);
271 * Converts all extended type definitions of module to the list of
272 * <code>Type</code> objects.
275 * module from which is obtained set of type definitions
276 * @throws IllegalArgumentException
278 * <li>if module is null</li>
279 * <li>if name of module is null</li>
281 * @throws IllegalStateException
282 * if set of type definitions from module is null
284 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
285 final Module module = context.module();
286 checkArgument(module.getName() != null, "Module name cannot be NULL.");
288 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
289 if (typedef != null) {
290 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
292 context.addTypedefType(typedef, type);
293 context.addTypeToSchema(type,typedef);
299 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
300 final DataSchemaNode node, final boolean inGrouping) {
301 if (node.isAugmenting() || node.isAddedByUses()) {
304 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
305 addConcreteInterfaceMethods(genType);
306 annotateDeprecatedIfNecessary(node, genType);
308 final Module module = context.module();
309 genType.setModuleName(module.getName());
310 addCodegenInformation(genType, module, node);
311 genType.setSchemaPath(node.getPath());
312 if (node instanceof DataNodeContainer) {
313 context.addChildNodeType(node, genType);
314 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
315 processUsesAugments((DataNodeContainer) node, context, inGrouping);
320 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
321 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
322 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
323 if (genType != null) {
324 constructGetter(parent, genType, node);
325 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
326 actionsToGenType(context, genType, node, null, inGrouping);
327 notificationsToGenType(context, genType, node, null, inGrouping);
331 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
332 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
333 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
334 if (genType != null) {
335 final List<String> listKeys = listKeys(node);
336 final GeneratedTOBuilder keyTypeBuilder;
337 if (!listKeys.isEmpty()) {
338 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
339 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
340 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
341 .addImplementsType(identifier(genType));
342 genType.addImplementsType(identifiable(keyTypeBuilder));
344 keyTypeBuilder = null;
347 // Decide whether to generate a List or a Map
348 final ParameterizedType listType;
349 if (keyTypeBuilder != null && !node.isUserOrdered()) {
350 listType = mapTypeFor(keyTypeBuilder, genType);
352 listType = listTypeFor(genType);
355 constructGetter(parent, listType, node).setMechanics(ValueMechanics.NULLIFY_EMPTY);
356 constructNonnull(parent, listType, node);
358 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
359 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
361 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
362 if (!schemaNode.isAugmenting()) {
363 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
368 if (keyTypeBuilder != null) {
369 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
370 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
371 keyTypeBuilder.setSUID(prop);
374 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
378 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
379 final boolean inGrouping) {
380 for (final UsesNode usesNode : node.getUses()) {
381 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
382 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
383 processUsesAugments(augment, context, inGrouping);
389 * Converts all <b>augmentation</b> of the module to the list
390 * <code>Type</code> objects.
393 * module from which is obtained list of all augmentation objects
394 * to iterate over them
395 * @throws IllegalArgumentException
397 * <li>if the module is null</li>
398 * <li>if the name of module is null</li>
400 * @throws IllegalStateException
401 * if set of augmentations from module is null
403 private void allAugmentsToGenTypes(final ModuleContext context) {
404 final Module module = context.module();
405 checkArgument(module != null, "Module reference cannot be NULL.");
406 checkArgument(module.getName() != null, "Module name cannot be NULL.");
407 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
409 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
410 augmentationToGenTypes(context, augment);
415 * Returns list of <code>AugmentationSchema</code> objects. The objects are
416 * sorted according to the length of their target path from the shortest to
420 * module from which is obtained list of all augmentation objects
421 * @return list of sorted <code>AugmentationSchema</code> objects obtained
422 * from <code>module</code>
423 * @throws IllegalArgumentException
425 * @throws IllegalStateException
426 * if set of module augmentations is null
428 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
429 checkArgument(module != null, "Module reference cannot be NULL.");
430 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
432 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(module.getAugmentations());
433 sortedAugmentations.sort(AUGMENT_COMP);
435 return sortedAugmentations;
439 * Create GeneratedTypeBuilder object from module argument.
442 * Module object from which builder will be created
443 * @return <code>GeneratedTypeBuilder</code> which is internal
444 * representation of the module
445 * @throws IllegalArgumentException
448 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
449 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
450 final Module module = context.module();
451 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
452 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
453 // if we have more than 2 top level uses statements we need to define getImplementedInterface() on the
454 // top level DataRoot object
455 if (module.getUses().size() > 1) {
456 narrowImplementedInterface(moduleDataTypeBuilder);
459 addCodegenInformation(moduleDataTypeBuilder, module);
460 return moduleDataTypeBuilder;
463 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
464 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
465 for (final ActionDefinition action : parentSchema.getActions()) {
466 if (action.isAugmenting()) {
470 final GeneratedType input;
471 final GeneratedType output;
472 if (action.isAddedByUses()) {
473 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
474 // Original definition may live in a different module, make sure we account for that
475 final ModuleContext origContext = moduleContext(
476 orig.getPath().getPathFromRoot().iterator().next().getModule());
477 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
478 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
480 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
481 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
484 if (!(parentSchema instanceof GroupingDefinition)) {
485 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
486 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
487 // and do not capture an actual instantiation.
488 final QName qname = action.getQName();
489 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
490 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
491 BindingMapping.getClassName(qname)));
492 qnameConstant(builder, context.moduleInfoType(), qname.getLocalName());
494 annotateDeprecatedIfNecessary(action, builder);
495 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
496 : action(parent, input, output));
498 addCodegenInformation(builder, context.module(), action);
499 context.addChildNodeType(action, builder);
504 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
505 final QName qname = action.getQName();
506 for (UsesNode uses : parent.getUses()) {
507 final GroupingDefinition grp = uses.getSourceGrouping();
508 // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
510 final Optional<ActionDefinition> found = grp.findAction(qname.bindTo(grp.getQName().getModule()));
511 if (found.isPresent()) {
512 final ActionDefinition result = found.get();
513 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
517 return Optional.empty();
520 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
521 final ContainerLike schema, final boolean inGrouping) {
522 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
523 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
524 return genType.build();
528 * Converts all <b>RPCs</b> input and output substatements of the module
529 * to the list of <code>Type</code> objects. In addition are to containers
530 * and lists which belong to input or output also part of returning list.
533 * module from which is obtained set of all rpc objects to
535 * @throws IllegalArgumentException
537 * <li>if the module is null</li>
538 * <li>if the name of module is null</li>
540 * @throws IllegalStateException
541 * if set of rpcs from module is null
543 private void rpcMethodsToGenType(final ModuleContext context) {
544 final Module module = context.module();
545 checkArgument(module.getName() != null, "Module name cannot be NULL.");
546 final Collection<? extends RpcDefinition> rpcDefinitions = module.getRpcs();
547 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
548 if (rpcDefinitions.isEmpty()) {
552 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
553 interfaceBuilder.addImplementsType(RPC_SERVICE);
555 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
557 for (final RpcDefinition rpc : rpcDefinitions) {
559 final String rpcName = BindingMapping.getClassName(rpc.getQName());
560 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
561 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
563 // Do not refer to annotation class, as it may not be available at runtime
564 method.addAnnotation(CHECK_RETURN_VALUE_ANNOTATION);
565 addRpcMethodComment(method, rpc);
567 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
568 method.setReturnType(listenableFutureTypeFor(
569 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
573 context.addTopLevelNodeType(interfaceBuilder);
576 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
577 final ContainerLike schema, final Type type) {
578 processUsesAugments(schema, context, false);
579 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(context,
580 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
582 addImplementedInterfaceFromUses(schema, outType);
583 outType.addImplementsType(type);
584 outType.addImplementsType(augmentable(outType));
585 addConcreteInterfaceMethods(outType);
586 annotateDeprecatedIfNecessary(rpc, outType);
587 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
588 context.addChildNodeType(schema, outType);
589 return outType.build();
593 * Converts all <b>notifications</b> of the module to the list of
594 * <code>Type</code> objects. In addition are to this list added containers
595 * and lists which are part of this notification.
598 * module from which is obtained set of all notification objects
599 * to iterate over them
600 * @throws IllegalArgumentException
602 * <li>if the module equals null</li>
603 * <li>if the name of module equals null</li>
605 * @throws IllegalStateException
606 * if set of notifications from module is null
608 private void notificationsToGenType(final ModuleContext context) {
609 final Module module = context.module();
610 checkArgument(module.getName() != null, "Module name cannot be NULL.");
611 final Collection<? extends NotificationDefinition> notifications = module.getNotifications();
612 if (notifications.isEmpty()) {
616 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
617 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
619 for (final NotificationDefinition notification : notifications) {
620 if (notification != null) {
621 processUsesAugments(notification, context, false);
623 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
624 context.modulePackageName(), notification, DATA_OBJECT, context);
625 addConcreteInterfaceMethods(notificationInterface);
626 annotateDeprecatedIfNecessary(notification, notificationInterface);
627 notificationInterface.addImplementsType(NOTIFICATION);
628 context.addChildNodeType(notification, notificationInterface);
630 // Notification object
631 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
632 notification.getChildNodes(), false);
634 final MethodSignatureBuilder notificationMethod =
635 listenerInterface.addMethod("on" + notificationInterface.getName())
636 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
637 .setReturnType(primitiveVoidType());
639 annotateDeprecatedIfNecessary(notification, notificationMethod);
640 if (notification.getStatus().equals(Status.OBSOLETE)) {
641 notificationMethod.setDefault(true);
643 addComment(notificationMethod, notification);
647 addCodegenInformation(listenerInterface, module, "notifications", notifications);
648 context.addTopLevelNodeType(listenerInterface);
651 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
652 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
653 final boolean inGrouping) {
654 final Collection<? extends NotificationDefinition> notifications = parentSchema.getNotifications();
655 if (notifications.isEmpty()) {
659 for (NotificationDefinition notif : notifications) {
660 if (notif.isAugmenting()) {
663 if (parentSchema instanceof GroupingDefinition) {
664 // Notifications cannot be really established, as they lack instantiation context, which would be
665 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
669 processUsesAugments(notif, context, false);
671 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
672 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
673 addConcreteInterfaceMethods(notifInterface);
674 annotateDeprecatedIfNecessary(notif, notifInterface);
676 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
677 : instanceNotification(notifInterface, parent));
678 context.addChildNodeType(notif, notifInterface);
680 // Notification object
681 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
686 * Converts all <b>identities</b> of the module to the list of
687 * <code>Type</code> objects.
690 * module from which is obtained set of all identity objects to
692 * @param schemaContext
693 * schema context only used as input parameter for method
694 * {@link BindingGeneratorImpl#identityToGenType}
697 private void allIdentitiesToGenTypes(final ModuleContext context) {
698 final Collection<? extends IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
700 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
701 for (final IdentitySchemaNode identity : schemaIdentities) {
702 identityToGenType(context, identity);
708 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
709 * created transport object builder. If identity contains base identity then
710 * reference to base identity is added to superior identity as its extend.
711 * If identity doesn't contain base identity then only reference to abstract
712 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
713 * BaseIdentity} is added
717 * @param basePackageName
718 * string contains the module package name
720 * IdentitySchemaNode which contains data about identity
722 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
723 if (identity == null) {
727 JavaTypeName name = renames.get(identity);
729 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
730 BindingMapping.getClassName(identity.getQName()));
733 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
734 final Collection<? extends IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
735 if (!baseIdentities.isEmpty()) {
736 for (IdentitySchemaNode baseIdentity : baseIdentities) {
737 JavaTypeName base = renames.get(baseIdentity);
739 final QName qname = baseIdentity.getQName();
740 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
741 BindingMapping.getClassName(qname));
744 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
745 newType.addImplementsType(gto);
748 newType.addImplementsType(BASE_IDENTITY);
751 final Module module = context.module();
752 addCodegenInformation(newType, module, identity);
753 newType.setModuleName(module.getName());
754 newType.setSchemaPath(identity.getPath());
756 qnameConstant(newType, context.moduleInfoType(), identity.getQName().getLocalName());
758 context.addIdentityType(identity, newType);
761 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
762 final JavaTypeName yangModuleInfo, final String localName) {
763 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
764 new SimpleImmutableEntry<>(yangModuleInfo, localName));
768 * Converts all <b>groupings</b> of the module to the list of
769 * <code>Type</code> objects. Firstly are groupings sorted according mutual
770 * dependencies. At least dependent (independent) groupings are in the list
771 * saved at first positions. For every grouping the record is added to map
772 * {@link ModuleContext#groupings allGroupings}
777 * collection of groupings from which types will be generated
780 private void groupingsToGenTypes(final ModuleContext context,
781 final Collection<? extends GroupingDefinition> groupings) {
782 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
783 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
784 // node of grouping is resolved to the method.
785 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
786 narrowImplementedInterface(genType);
787 annotateDeprecatedIfNecessary(grouping, genType);
788 context.addGroupingType(grouping, genType);
789 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
790 groupingsToGenTypes(context, grouping.getGroupings());
791 processUsesAugments(grouping, context, true);
792 actionsToGenType(context, genType, grouping, null, true);
793 notificationsToGenType(context, genType, grouping, null, true);
798 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
799 * <code>enumTypeDef</code> item is added to builder with its name and value.
801 * @param enumTypeDef EnumTypeDefinition contains enum data
802 * @param enumName string contains name which will be assigned to enumeration builder
803 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
804 * @param module Module in which type should be generated
805 * @return enumeration builder which contains data from <code>enumTypeDef</code>
807 private Enumeration resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
808 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
809 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
810 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
811 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
812 final Enumeration ret = enumBuilder.toInstance(typeBuilder);
813 context.addTypeToSchema(ret, enumTypeDef);
814 context.addInnerTypedefType(enumTypeDef.getPath(), ret);
819 * Generates type builder for <code>module</code>.
821 * @param module Module which is source of package name for generated type builder
822 * @param postfix string which is added to the module class name representation as suffix
823 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
824 * @throws IllegalArgumentException if <code>module</code> is null
826 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
827 final Module module = context.module();
828 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
829 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
830 JavaTypeName.create(context.modulePackageName(), moduleName));
832 moduleBuilder.setModuleName(moduleName);
833 addCodegenInformation(moduleBuilder, module);
834 return moduleBuilder;
838 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
839 * In addition there are also generated types for all containers, list and choices which are child of
840 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
842 * @param augmentPackageName string with the name of the package to which the augmentation belongs
843 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
844 * @param module current module
845 * @throws IllegalArgumentException
847 * <li>if <code>augmentPackageName</code> equals null</li>
848 * <li>if <code>augSchema</code> equals null</li>
850 * @throws IllegalStateException
851 * if augment target path is null
853 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
854 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
855 checkState(augSchema.getTargetPath() != null,
856 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
858 processUsesAugments(augSchema, context, false);
859 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
860 SchemaNode targetSchemaNode = null;
862 // FIXME: can we use findDataSchemaNode() instead?
863 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath.getNodeIdentifiers());
864 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
865 if (targetSchemaNode instanceof DerivableSchemaNode) {
866 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
868 if (targetSchemaNode == null) {
869 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
870 + " in module " + context.module().getName());
873 if (targetSchemaNode == null) {
874 throw new IllegalArgumentException("augment target not found: " + targetPath);
877 if (targetSchemaNode instanceof ChoiceSchemaNode) {
878 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
879 checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
880 generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
881 augSchema.getChildNodes(), null, false);
885 final JavaTypeName targetName;
886 if (targetSchemaNode instanceof CaseSchemaNode) {
887 final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
888 checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
889 targetName = builder.getIdentifier();
891 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
892 if (builder == null) {
893 targetName = findAliasByPath(targetSchemaNode.getPath());
894 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
896 targetName = builder.getIdentifier();
900 addRawAugmentGenTypeDefinition(context, DefaultType.of(targetName), augSchema, false);
903 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
904 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
905 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
906 checkState(augSchema.getTargetPath() != null,
907 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
909 processUsesAugments(augSchema, context, inGrouping);
910 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
911 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
912 if (targetSchemaNode == null) {
913 throw new IllegalArgumentException("augment target not found: " + targetPath);
916 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
917 if (targetTypeBuilder == null) {
918 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
920 if (targetTypeBuilder == null) {
921 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
924 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
925 if (usesNodeParent instanceof SchemaNode) {
926 addRawAugmentGenTypeDefinition(context,
927 packageNameForAugmentedGeneratedType(context.modulePackageName(),
928 ((SchemaNode) usesNodeParent).getPath()),
929 targetTypeBuilder.build(), augSchema, inGrouping);
931 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
934 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
935 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
940 * Convenient method to find node added by uses statement.
942 * @param targetPath node path
943 * @param parentUsesNode parent of uses node
944 * @return node from its original location in grouping
946 private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaNodeIdentifier targetPath,
947 final UsesNode parentUsesNode) {
948 SchemaNode result = parentUsesNode.getSourceGrouping();
949 for (final QName node : targetPath.getNodeIdentifiers()) {
950 // FIXME: this dispatch is rather ugly, we probably want to refactor it a bit
951 if (result instanceof DataNodeContainer) {
952 final QName resultNode = node.bindTo(result.getQName().getModule());
954 SchemaNode found = ((DataNodeContainer) result).getDataChildByName(resultNode);
956 if (result instanceof ActionNodeContainer) {
957 found = ((ActionNodeContainer) result).findAction(resultNode).orElse(null);
959 if (found == null && result instanceof NotificationNodeContainer) {
960 found = ((NotificationNodeContainer) result).findNotification(resultNode).orElse(null);
964 } else if (result instanceof ChoiceSchemaNode) {
965 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
966 } else if (result instanceof ActionDefinition) {
967 final ActionDefinition action = (ActionDefinition) result;
968 final QName resultNode = node.bindTo(result.getQName().getModule());
970 final InputSchemaNode input = action.getInput();
971 final OutputSchemaNode output = action.getOutput();
972 if (resultNode.equals(input.getQName())) {
974 } else if (resultNode.equals(output.getQName())) {
979 } else if (result != null) {
980 throw new IllegalStateException("Cannot handle " + result);
983 if (result == null) {
987 if (result instanceof DerivableSchemaNode) {
988 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
989 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
990 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
991 result = originalNode.get();
995 if (result instanceof DataSchemaNode) {
996 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
997 if (resultDataSchemaNode.isAddedByUses()) {
998 // The original node is required, but we have only the copy of
999 // the original node.
1000 // Maybe this indicates a bug in Yang parser.
1001 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
1004 return resultDataSchemaNode;
1007 throw new IllegalStateException(
1008 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
1013 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
1014 * of augmented node with serial number as suffix.
1016 * @param context current module
1017 * @param augmentPackageName string with contains the package name to which the augment belongs
1018 * @param basePackageName string with the package name to which the augmented node belongs
1019 * @param targetTypeRef target type
1020 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
1021 * @return generated type builder for augment
1023 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
1024 final String augmentPackageName, final Type targetTypeRef,
1025 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1026 Map<String, GeneratedTypeBuilder> augmentBuilders =
1027 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
1028 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
1031 if (augIdentifier != null) {
1032 augTypeName = BindingMapping.getClassName(augIdentifier);
1034 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1037 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
1038 JavaTypeName.create(augmentPackageName, augTypeName));
1040 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
1041 addConcreteInterfaceMethods(augTypeBuilder);
1043 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
1044 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1046 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
1047 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1048 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1050 augmentBuilders.put(augTypeName, augTypeBuilder);
1052 if (!augSchema.getChildNodes().isEmpty()) {
1053 context.addTypeToAugmentation(augTypeBuilder, augSchema);
1056 context.addAugmentType(augTypeBuilder);
1057 return augTypeBuilder;
1060 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1061 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1062 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1066 private static String getAugmentIdentifier(final Collection<? extends UnknownSchemaNode> unknownSchemaNodes) {
1067 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1068 final QName nodeType = unknownSchemaNode.getNodeType();
1069 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1070 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1071 return unknownSchemaNode.getNodeParameter();
1078 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1079 * consists from name of augmented node and serial number of its augmentation.
1081 * @param builders map of builders which were created in the package to which the augmentation belongs
1082 * @param genTypeName string with name of augmented node
1083 * @return string with unique name for augmentation builder
1085 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1087 if (builders != null) {
1088 while (builders.containsKey(genTypeName + index)) {
1092 return genTypeName + index;
1096 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1097 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1098 * already part of them).
1100 * @param module current module
1101 * @param parent generated type builder which represents any node. The subnodes of this node are added
1102 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1103 * container, choice.
1104 * @param childOf parent type
1105 * @param schemaNodes set of data schema nodes which are the children of the node for which
1106 * <code>typeBuilder</code> was created
1107 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1108 * child nodes) could be added to it.
1110 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1111 final @Nullable Type childOf, final Iterable<? extends DataSchemaNode> schemaNodes,
1112 final boolean inGrouping) {
1113 if (schemaNodes != null && parent != null) {
1114 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1115 for (final DataSchemaNode schemaNode : schemaNodes) {
1116 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1117 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1125 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1128 * @param module current module
1129 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1130 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1131 * container, choice.
1132 * @param childOf parent type
1133 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1135 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1136 * The getter method could be added to it.
1138 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1139 final GeneratedTypeBuilder typeBuilder, final Iterable<? extends DataSchemaNode> schemaNodes,
1140 final boolean inGrouping) {
1141 if (schemaNodes != null && typeBuilder != null) {
1142 final Type baseInterface = childOf(typeBuilder);
1143 for (final DataSchemaNode schemaNode : schemaNodes) {
1144 if (!schemaNode.isAugmenting()) {
1145 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1153 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1155 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1156 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1157 * @param childOf parent type
1158 * @param module current module
1160 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1161 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1162 if (node != null && typeBuilder != null) {
1163 if (node instanceof LeafSchemaNode) {
1164 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1165 } else if (node instanceof LeafListSchemaNode) {
1166 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1167 } else if (node instanceof ContainerSchemaNode) {
1168 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1169 } else if (node instanceof ListSchemaNode) {
1170 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1171 } else if (node instanceof ChoiceSchemaNode) {
1172 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1173 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1174 opaqueToGeneratedType(context, typeBuilder, node);
1176 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1177 typeBuilder.getFullyQualifiedName());
1183 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1184 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1185 * and names of all parents node.
1187 * @param context current module
1188 * @param basePackageName string with the module package name
1189 * @param parent parent type
1190 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1192 * @throws IllegalArgumentException
1194 * <li>if <code>basePackageName</code> is null</li>
1195 * <li>if <code>choiceNode</code> is null</li>
1198 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1199 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1200 if (!choiceNode.isAddedByUses()) {
1201 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(context,
1202 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1203 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1204 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1205 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1206 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1208 final GeneratedType choiceType = choiceTypeBuilder.build();
1209 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1211 constructGetter(parent, choiceType, choiceNode);
1215 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1216 final DataSchemaNode anyNode) {
1217 if (!anyNode.isAddedByUses()) {
1218 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(context,
1219 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1220 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1221 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1222 defaultImplementedInterace(anyxmlTypeBuilder);
1223 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1224 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1226 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1231 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1232 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1233 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1234 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1236 * @param context current module context
1237 * @param refChoiceType type which represents superior <i>case</i>
1238 * @param choiceNode choice case node which is mapped to generated type
1239 * @throws IllegalArgumentException
1241 * <li>if <code>refChoiceType</code> equals null</li>
1242 * <li>if <code>caseNodes</code> equals null</li>
1245 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1246 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1247 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1248 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1250 for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
1251 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1252 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1253 caseTypeBuilder.addImplementsType(refChoiceType);
1254 addConcreteInterfaceMethods(caseTypeBuilder);
1255 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1256 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1257 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1258 final Iterable<? extends DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1259 if (caseChildNodes != null) {
1260 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1262 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1263 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1265 if (parent instanceof AugmentationSchemaNode) {
1266 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1267 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
1268 // FIXME: can we use findDataSchemaNode?
1269 SchemaNode targetSchemaNode = findNodeInSchemaContext(schemaContext,
1270 targetPath.getNodeIdentifiers());
1271 if (targetSchemaNode instanceof DataSchemaNode
1272 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1273 if (targetSchemaNode instanceof DerivableSchemaNode) {
1274 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1277 if (targetSchemaNode == null) {
1278 throw new IllegalStateException(
1279 "Failed to find target node from grouping for augmentation " + augSchema
1280 + " in module " + context.module().getName());
1283 parent = targetSchemaNode;
1286 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1287 Type childOfType = findChildNodeByPath(parent.getPath());
1288 if (childOfType == null) {
1289 childOfType = findGroupingByPath(parent.getPath());
1291 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1293 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1298 processUsesAugments(caseNode, context, inGrouping);
1303 * Generates list of generated types for all the cases of a choice which are added to the choice through
1306 * @param module current module
1307 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1308 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1309 * of the augmenting choice will belong to pcg2.
1310 * @param targetType Type which represents target choice
1311 * @param targetNode node which represents target choice
1312 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1314 * @throws IllegalArgumentException
1316 * <li>if <code>basePackageName</code> is null</li>
1317 * <li>if <code>targetType</code> is null</li>
1318 * <li>if <code>augmentedNodes</code> is null</li>
1321 // FIXME: nullness rules need to untangled in this method
1322 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1323 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1324 final Type targetType, final ChoiceSchemaNode targetNode,
1325 final Iterable<? extends DataSchemaNode> augmentedNodes,
1326 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1327 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1328 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1330 for (final DataSchemaNode caseNode : augmentedNodes) {
1331 if (caseNode != null) {
1332 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1333 caseTypeBuilder.addImplementsType(targetType);
1334 addConcreteInterfaceMethods(caseTypeBuilder);
1336 CaseSchemaNode node = null;
1337 final String caseLocalName = caseNode.getQName().getLocalName();
1338 if (caseNode instanceof CaseSchemaNode) {
1339 node = (CaseSchemaNode) caseNode;
1340 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1341 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1342 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1343 if (dataSchemaNode instanceof ChoiceSchemaNode
1344 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1345 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1350 node = findNamedCase(targetNode, caseLocalName);
1352 final Iterable<? extends DataSchemaNode> childNodes = node.getChildNodes();
1353 if (childNodes != null) {
1354 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1357 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1358 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1363 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1364 final SchemaPath nodePath = targetNode.getPath();
1365 final SchemaPath parentSp = nodePath.getParent();
1366 if (parentSp.getParent() == null) {
1367 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1370 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1371 GeneratedTypeBuilder childOfType = null;
1372 if (parent instanceof CaseSchemaNode) {
1373 childOfType = findCaseByPath(parent.getPath());
1374 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1375 childOfType = findChildNodeByPath(parent.getPath());
1376 } else if (parent instanceof GroupingDefinition) {
1377 childOfType = findGroupingByPath(parent.getPath());
1380 if (childOfType == null) {
1381 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1387 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1388 final List<? extends CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1389 return cases.isEmpty() ? null : cases.get(0);
1392 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1393 // New parser with encapsulated type
1394 if (leaf.getPath().equals(type.getPath())) {
1398 // Embedded type definition with new parser. Also takes care of the old parser with bits
1399 if (leaf.getPath().equals(type.getPath().getParent())) {
1406 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1407 final List<PatternConstraint> patternConstraints) {
1408 if (!patternConstraints.isEmpty()) {
1409 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1410 .append(BindingMapping.getPropertyName(leafName));
1411 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1412 typeProvider.resolveRegExpressions(patternConstraints));
1417 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1419 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1420 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1421 * @param module Module in which type was defined
1422 * @return boolean value
1424 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1426 * <li>true - in other cases</li>
1429 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1430 final ModuleContext context, final boolean inGrouping) {
1431 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1435 final Module parentModule = findParentModule(schemaContext, leaf);
1436 Type returnType = null;
1438 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1439 if (isInnerType(leaf, typeDef)) {
1440 if (typeDef instanceof EnumTypeDefinition) {
1441 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1442 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(), typeBuilder, context);
1443 typeProvider.putReferencedType(leaf.getPath(), returnType);
1444 } else if (typeDef instanceof UnionTypeDefinition) {
1445 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1446 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1447 // Store the inner type within the union so that we can find the reference for it
1448 context.addInnerTypedefType(typeDef.getPath(), returnType);
1449 } else if (typeDef instanceof BitsTypeDefinition) {
1450 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1452 if (genTOBuilder != null) {
1453 returnType = genTOBuilder.build();
1456 // It is constrained version of already declared type (inner declared type exists, only for special
1457 // cases (Enum, Union, Bits), which were already checked.
1458 // In order to get proper class we need to look up closest derived type and apply restrictions from leaf
1460 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1461 final TypeDefinition<?> baseOrDeclaredType = getBaseOrDeclaredType(typeDef);
1462 // we need to try to lookup an already generated type in case the leafref is targetting a generated type
1463 if (baseOrDeclaredType instanceof LeafrefTypeDefinition) {
1464 final SchemaNode leafrefTarget =
1465 typeProvider.getTargetForLeafref((LeafrefTypeDefinition) baseOrDeclaredType, leaf);
1466 if (leafrefTarget instanceof TypedDataSchemaNode) {
1467 returnType = context.getInnerType(((TypedDataSchemaNode) leafrefTarget).getType().getPath());
1470 if (returnType == null) {
1471 returnType = typeProvider.javaTypeForSchemaDefinitionType(baseOrDeclaredType, leaf,
1472 restrictions, inGrouping);
1475 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1478 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1479 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1480 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1483 if (returnType == null) {
1487 if (typeDef instanceof EnumTypeDefinition) {
1488 typeProvider.putReferencedType(leaf.getPath(), returnType);
1491 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1492 processContextRefExtension(leaf, getter, parentModule);
1496 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1497 // Returns DerivedType in case of new parser.
1498 final TypeDefinition<?> baseType = typeDef.getBaseType();
1499 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1502 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1503 final Module module) {
1504 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1505 final QName nodeType = node.getNodeType();
1506 if ("context-reference".equals(nodeType.getLocalName())) {
1507 final String nodeParam = node.getNodeParameter();
1508 IdentitySchemaNode identity = null;
1509 String basePackageName = null;
1510 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1511 final Iterator<String> iterator = splittedElement.iterator();
1512 final int length = Iterables.size(splittedElement);
1514 identity = findIdentityByName(module.getIdentities(), iterator.next());
1515 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1516 } else if (length == 2) {
1517 final String prefix = iterator.next();
1518 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1519 if (dependentModule == null) {
1520 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1523 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1524 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1526 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1529 if (identity == null) {
1530 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1534 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1535 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1536 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1537 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1542 private static IdentitySchemaNode findIdentityByName(final Collection<? extends IdentitySchemaNode> identities,
1543 final String name) {
1544 for (final IdentitySchemaNode id : identities) {
1545 if (id.getQName().getLocalName().equals(name)) {
1552 private Module findModuleFromImports(final Collection<? extends ModuleImport> imports, final String prefix) {
1553 for (final ModuleImport imp : imports) {
1554 if (imp.getPrefix().equals(prefix)) {
1555 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1561 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1562 final boolean isReadOnly) {
1563 if (leaf != null && toBuilder != null) {
1565 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1566 if (typeDef instanceof UnionTypeDefinition) {
1567 // GeneratedType for this type definition should have be already created
1568 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1569 returnType = mc.getTypedefs().get(typeDef.getPath());
1570 if (returnType == null) {
1571 // This may still be an inner type, try to find it
1572 returnType = mc.getInnerType(typeDef.getPath());
1574 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1575 // Annonymous enumeration (already generated, since it is inherited via uses).
1576 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1577 QName qname = originalLeaf.getQName();
1578 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1580 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1582 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1588 * Converts <code>leaf</code> schema node to property of generated TO builder.
1590 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1591 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1592 * @param returnType property type
1593 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1594 * @return boolean value
1596 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1597 * name equals null or if leaf is added by <i>uses</i>.</li>
1598 * <li>true - other cases</li>
1601 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1602 final Type returnType, final boolean isReadOnly) {
1603 if (returnType == null) {
1606 final String leafName = leaf.getQName().getLocalName();
1607 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1608 propBuilder.setReadOnly(isReadOnly);
1609 propBuilder.setReturnType(returnType);
1610 addComment(propBuilder, leaf);
1612 toBuilder.addEqualsIdentity(propBuilder);
1613 toBuilder.addHashIdentity(propBuilder);
1614 toBuilder.addToStringProperty(propBuilder);
1619 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1621 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1622 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1623 * @param module module
1624 * @return boolean value
1626 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1627 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1628 * <li>false - other cases</li>
1631 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1632 final ModuleContext context, final boolean inGrouping) {
1633 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1637 final QName nodeName = node.getQName();
1639 final TypeDefinition<?> typeDef = node.getType();
1640 final Module parentModule = findParentModule(schemaContext, node);
1642 Type returnType = null;
1643 if (typeDef.getBaseType() == null) {
1644 if (typeDef instanceof EnumTypeDefinition) {
1645 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1646 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName, typeBuilder, context);
1647 typeProvider.putReferencedType(node.getPath(), returnType);
1648 } else if (typeDef instanceof UnionTypeDefinition) {
1649 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1650 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1651 } else if (typeDef instanceof BitsTypeDefinition) {
1652 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1653 node, parentModule);
1654 returnType = genTOBuilder.build();
1656 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1657 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1658 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1661 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1662 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1663 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1666 constructGetter(typeBuilder, listTypeFor(returnType), node);
1670 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1671 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1672 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1673 returnTypeBuilder.setIsUnion(true);
1674 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1675 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1676 returnTypeBuilder.setModuleName(parentModule.getName());
1677 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1679 genTOBuilder.setTypedef(true);
1680 genTOBuilder.setIsUnion(true);
1681 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1683 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1687 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1688 final GeneratedTransferObject returnType, final Module parentModule) {
1689 // Append enclosing path hierarchy without dots
1690 final StringBuilder sb = new StringBuilder();
1691 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1692 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1693 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1694 unionBuilder.setIsUnionBuilder(true);
1696 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1697 method.setReturnType(returnType);
1698 method.addParameter(STRING, "defaultValue");
1699 method.setAccessModifier(AccessModifier.PUBLIC);
1700 method.setStatic(true);
1702 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1703 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1706 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1707 final SchemaNode schemaNode) {
1708 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1711 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1712 final SchemaNode schemaNode, final Type baseInterface) {
1713 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1714 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1718 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1719 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1720 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1721 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1722 * If <code>schemaNode</code> is instance of
1723 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1724 * which are specified in <i>uses</i>.
1726 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1727 * @param schemaNode schema node for which is created generated type builder
1728 * @param parent parent type (can be null)
1729 * @return generated type builder <code>schemaNode</code>
1731 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1732 final Type baseInterface, final ModuleContext context) {
1733 JavaTypeName name = renames.get(schemaNode);
1735 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1738 final GeneratedTypeBuilder it = addRawInterfaceDefinition(context, name, schemaNode);
1739 it.addImplementsType(baseInterface);
1740 if (!(schemaNode instanceof GroupingDefinition)) {
1741 it.addImplementsType(augmentable(it));
1743 if (schemaNode instanceof DataNodeContainer) {
1744 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1745 groupingsToGenTypes(context, containerSchema.getGroupings());
1746 addImplementedInterfaceFromUses(containerSchema, it);
1753 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1754 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1755 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1757 * @param packageName string with the package name to which returning generated type builder belongs
1758 * @param schemaNode schema node which provide data about the schema node name
1759 * @param prefix return type name prefix
1760 * @return generated type builder for <code>schemaNode</code>
1761 * @throws IllegalArgumentException
1763 * <li>if <code>schemaNode</code> is null</li>
1764 * <li>if <code>packageName</code> is null</li>
1765 * <li>if QName of schema node is null</li>
1766 * <li>if schemaNode name is null</li>
1769 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final JavaTypeName identifier,
1770 final SchemaNode schemaNode) {
1771 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1772 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1773 final String schemaNodeName = schemaNode.getQName().getLocalName();
1774 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1776 // FIXME: Validation of name conflict
1777 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1778 qnameConstant(newType, context.moduleInfoType(), schemaNode.getQName().getLocalName());
1780 final Module module = context.module();
1781 addCodegenInformation(newType, module, schemaNode);
1782 newType.setSchemaPath(schemaNode.getPath());
1783 newType.setModuleName(module.getName());
1785 final String packageName = identifier.packageName();
1786 final String simpleName = identifier.simpleName();
1787 if (!genTypeBuilders.containsKey(packageName)) {
1788 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1789 builders.put(simpleName, newType);
1790 genTypeBuilders.put(packageName, builders);
1792 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1793 if (!builders.containsKey(simpleName)) {
1794 builders.put(simpleName, newType);
1801 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1802 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1803 * and <code>returnType</code> information are added to the builder.
1805 * @param interfaceBuilder generated type builder for which the getter method should be created
1806 * @param returnType type which represents the return type of the getter method
1807 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1808 * @param comment string with comment for the getter method
1809 * @param status status from yang file, for deprecated annotation
1810 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1812 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1813 final SchemaNode node) {
1814 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1815 BindingMapping.getGetterMethodName(node.getQName().getLocalName()));
1816 getMethod.setReturnType(returnType);
1818 annotateDeprecatedIfNecessary(node, getMethod);
1819 addComment(getMethod, node);
1821 if (BOOLEAN.equals(returnType)) {
1822 // Construct a default 'isFoo()' method for compatibility
1823 interfaceBuilder.addMethod(BindingMapping.getGetterMethodName(node.getQName().getLocalName(), true))
1824 .setAccessModifier(AccessModifier.PUBLIC)
1826 .setReturnType(BOOLEAN);
1832 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1833 final ListSchemaNode node) {
1834 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1835 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1836 getMethod.setReturnType(returnType).setDefault(true);
1837 annotateDeprecatedIfNecessary(node, getMethod);
1841 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1844 * @param basePackageName string contains the module package name
1845 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1846 * or as a property to <code>genTOBuilder</code> if is part of the list key
1847 * @param typeBuilder generated type builder for the list schema node
1848 * @param genTOBuilder generated TO builder for the list keys
1849 * @param listKeys list of string which contains names of the list keys
1850 * @param module current module
1851 * @throws IllegalArgumentException
1853 * <li>if <code>schemaNode</code> equals null</li>
1854 * <li>if <code>typeBuilder</code> equals null</li>
1857 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1858 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1859 final List<String> listKeys, final boolean inGrouping) {
1860 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1861 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1863 if (schemaNode instanceof LeafSchemaNode) {
1864 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1865 final String leafName = leaf.getQName().getLocalName();
1866 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1867 if (listKeys.contains(leafName)) {
1869 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1871 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1874 } else if (!schemaNode.isAddedByUses()) {
1875 if (schemaNode instanceof LeafListSchemaNode) {
1876 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1877 } else if (schemaNode instanceof ContainerSchemaNode) {
1878 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1879 (ContainerSchemaNode) schemaNode, inGrouping);
1880 } else if (schemaNode instanceof ChoiceSchemaNode) {
1881 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1882 } else if (schemaNode instanceof ListSchemaNode) {
1883 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1884 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1885 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1890 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1891 final GeneratedTOBuilder genTOBuilder) {
1892 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1894 if (genTOBuilder != null) {
1895 final GeneratedTransferObject genTO = genTOBuilder.build();
1896 // Add Identifiable.getKey() for items
1897 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1898 .addAnnotation(OVERRIDE_ANNOTATION);
1899 context.addGeneratedTOBuilder(genTOBuilder);
1904 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1906 * @param list of string with names of the list keys
1907 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1908 * an empty list is returned.
1910 private static List<String> listKeys(final ListSchemaNode list) {
1911 final List<QName> keyDefinition = list.getKeyDefinition();
1912 switch (keyDefinition.size()) {
1914 return Collections.emptyList();
1916 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1918 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1919 for (final QName keyDef : keyDefinition) {
1920 listKeys.add(keyDef.getLocalName());
1927 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1928 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1929 * enclosing transfer objects.
1931 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1932 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1933 * @param leaf string with name for generated TO builder
1934 * @param parentModule parent module
1935 * @return generated TO builder for <code>typeDef</code>
1937 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1938 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1939 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1940 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1942 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1943 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1944 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1945 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1946 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1948 for (GeneratedTOBuilder builder : types) {
1949 if (builder.isUnion()) {
1950 final GeneratedTransferObject type = builder.build();
1951 createUnionBuilder(builder, typeBuilder, type, parentModule);
1955 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1959 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1960 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1961 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1964 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1965 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1966 * @param leaf string with name for generated TO builder
1967 * @param parentModule parent module
1968 * @return generated TO builder for <code>typeDef</code>
1970 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1971 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1972 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1973 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1974 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1975 return genTOBuilder;
1979 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1980 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1981 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1982 * to <code>builder</code>
1984 * @param dataNodeContainer element which contains the list of used YANG groupings
1985 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1986 * @return generated type builder with all implemented types
1988 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1989 final GeneratedTypeBuilder builder) {
1990 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1991 final GeneratedTypeBuilder genType = findGrouping(usesNode.getSourceGrouping());
1992 if (genType == null) {
1993 throw new IllegalStateException("Grouping " + usesNode.getSourceGrouping().getQName()
1994 + " is not resolved for " + builder.getFullyQualifiedName());
1997 builder.addImplementsType(genType.build());
2002 private JavaTypeName findAliasByPath(final SchemaPath path) {
2003 for (final ModuleContext ctx : genCtx.values()) {
2004 final JavaTypeName result = ctx.getAlias(path);
2005 if (result != null) {
2012 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2013 for (final ModuleContext ctx : genCtx.values()) {
2014 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2015 if (result != null) {
2022 private GeneratedTypeBuilder findGrouping(final GroupingDefinition grouping) {
2023 for (final ModuleContext ctx : genCtx.values()) {
2024 final GeneratedTypeBuilder result = ctx.getGrouping(grouping.getPath());
2025 if (result != null) {
2032 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2033 for (final ModuleContext ctx : genCtx.values()) {
2034 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2035 if (result != null) {
2042 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2043 for (final ModuleContext ctx : genCtx.values()) {
2044 final GeneratedTypeBuilder result = ctx.getCase(path);
2045 if (result != null) {
2052 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
2053 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
2054 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
2057 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
2058 switch (node.getStatus()) {
2060 // FIXME: we really want to use a pre-made annotation
2061 builder.addAnnotation(DEPRECATED_ANNOTATION);
2064 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
2070 throw new IllegalStateException("Unhandled status in " + node);
2074 private static void addConcreteInterfaceMethods(final GeneratedTypeBuilder typeBuilder) {
2075 defaultImplementedInterace(typeBuilder);
2077 typeBuilder.addMethod(BindingMapping.BINDING_HASHCODE_NAME)
2078 .setAccessModifier(AccessModifier.PUBLIC)
2080 .setReturnType(primitiveIntType());
2081 typeBuilder.addMethod(BindingMapping.BINDING_EQUALS_NAME)
2082 .setAccessModifier(AccessModifier.PUBLIC)
2084 .setReturnType(primitiveBooleanType());
2085 typeBuilder.addMethod(BindingMapping.BINDING_TO_STRING_NAME)
2086 .setAccessModifier(AccessModifier.PUBLIC)
2088 .setReturnType(STRING);
2091 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2092 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2095 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2096 defineImplementedInterfaceMethod(typeBuilder, DefaultType.of(typeBuilder)).setDefault(true);
2099 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2100 final Type classType) {
2101 final MethodSignatureBuilder ret = typeBuilder
2102 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2103 .setAccessModifier(AccessModifier.PUBLIC)
2104 .setReturnType(classType(classType));
2105 ret.addAnnotation(OVERRIDE_ANNOTATION);