2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.mdsal.binding.generator.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
15 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.BASE_IDENTITY;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.QNAME;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentation;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
34 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.instanceNotification;
35 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
36 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListNotification;
37 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.opaqueObject;
38 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
39 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
40 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
41 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
42 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
43 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
44 import static org.opendaylight.mdsal.binding.model.util.Types.mapTypeFor;
45 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
46 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
47 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
48 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
49 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
51 import com.google.common.base.Splitter;
52 import com.google.common.collect.Iterables;
53 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
54 import java.util.AbstractMap.SimpleImmutableEntry;
55 import java.util.ArrayList;
56 import java.util.Collection;
57 import java.util.Collections;
58 import java.util.Comparator;
59 import java.util.HashMap;
60 import java.util.HashSet;
61 import java.util.Iterator;
62 import java.util.List;
64 import java.util.Optional;
65 import org.eclipse.jdt.annotation.NonNull;
66 import org.eclipse.jdt.annotation.Nullable;
67 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
68 import org.opendaylight.mdsal.binding.model.api.Constant;
69 import org.opendaylight.mdsal.binding.model.api.DefaultType;
70 import org.opendaylight.mdsal.binding.model.api.Enumeration;
71 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
72 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
73 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
74 import org.opendaylight.mdsal.binding.model.api.MethodSignature.ValueMechanics;
75 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
76 import org.opendaylight.mdsal.binding.model.api.Restrictions;
77 import org.opendaylight.mdsal.binding.model.api.Type;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
83 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
84 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
85 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
86 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
87 import org.opendaylight.mdsal.binding.model.util.BaseYangTypes;
88 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
89 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
90 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
91 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
92 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
93 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
94 import org.opendaylight.yangtools.yang.common.QName;
95 import org.opendaylight.yangtools.yang.common.QNameModule;
96 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
97 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
98 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
105 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
108 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
109 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
110 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
111 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
112 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
113 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
114 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.Module;
116 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
117 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
118 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
119 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
120 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
121 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
122 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
123 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
124 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
125 import org.opendaylight.yangtools.yang.model.api.UsesNode;
126 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
127 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
128 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
129 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
130 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
131 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
132 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
133 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
134 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
135 import org.slf4j.Logger;
136 import org.slf4j.LoggerFactory;
138 abstract class AbstractTypeGenerator {
139 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
140 private static final Splitter COLON_SPLITTER = Splitter.on(':');
141 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
142 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
143 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
146 * Comparator based on augment target path.
148 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
149 final Iterator<QName> thisIt = o1.getTargetPath().getNodeIdentifiers().iterator();
150 final Iterator<QName> otherIt = o2.getTargetPath().getNodeIdentifiers().iterator();
152 while (thisIt.hasNext()) {
153 if (!otherIt.hasNext()) {
157 final int comp = thisIt.next().compareTo(otherIt.next());
163 return otherIt.hasNext() ? -1 : 0;
167 * Constant with the concrete name of identifier.
169 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
172 * Constant with the concrete name of namespace.
174 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
176 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
179 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
180 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
181 * for schema node specified in key part.
183 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
186 * Provide methods for converting YANG types to JAVA types.
188 private final AbstractTypeProvider typeProvider;
191 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
193 private final @NonNull EffectiveModelContext schemaContext;
196 * Holds renamed elements.
198 private final Map<SchemaNode, JavaTypeName> renames;
200 AbstractTypeGenerator(final EffectiveModelContext context, final AbstractTypeProvider typeProvider,
201 final Map<SchemaNode, JavaTypeName> renames) {
202 this.schemaContext = requireNonNull(context);
203 this.typeProvider = requireNonNull(typeProvider);
204 this.renames = requireNonNull(renames);
206 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
207 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
208 for (final Module contextModule : contextModules) {
209 contexts.add(moduleToGenTypes(contextModule));
212 contexts.forEach(this::allAugmentsToGenTypes);
215 final @NonNull EffectiveModelContext schemaContext() {
216 return schemaContext;
219 final Collection<ModuleContext> moduleContexts() {
220 return genCtx.values();
223 final ModuleContext moduleContext(final QNameModule module) {
224 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
227 final AbstractTypeProvider typeProvider() {
231 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
233 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
235 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
236 Collection<? extends SchemaNode> nodes);
238 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
240 private ModuleContext moduleToGenTypes(final Module module) {
241 final ModuleContext context = new ModuleContext(module);
242 genCtx.put(module.getQNameModule(), context);
243 allTypeDefinitionsToGenTypes(context);
244 groupingsToGenTypes(context, module.getGroupings());
245 allIdentitiesToGenTypes(context);
247 if (!module.getChildNodes().isEmpty()) {
248 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
249 context.addModuleNode(moduleType);
250 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
253 // Resolve RPCs and notifications only after we have created instantiated tree
254 rpcMethodsToGenType(context);
255 notificationsToGenType(context);
260 * Converts all extended type definitions of module to the list of
261 * <code>Type</code> objects.
264 * module from which is obtained set of type definitions
265 * @throws IllegalArgumentException
267 * <li>if module is null</li>
268 * <li>if name of module is null</li>
270 * @throws IllegalStateException
271 * if set of type definitions from module is null
273 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
274 final Module module = context.module();
275 checkArgument(module.getName() != null, "Module name cannot be NULL.");
277 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
278 if (typedef != null) {
279 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
281 context.addTypedefType(typedef, type);
282 context.addTypeToSchema(type,typedef);
288 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
289 final DataSchemaNode node, final boolean inGrouping) {
290 if (node.isAugmenting() || node.isAddedByUses()) {
293 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
294 addConcreteInterfaceMethods(genType);
295 annotateDeprecatedIfNecessary(node, genType);
297 final Module module = context.module();
298 genType.setModuleName(module.getName());
299 addCodegenInformation(genType, module, node);
300 genType.setSchemaPath(node.getPath());
301 if (node instanceof DataNodeContainer) {
302 context.addChildNodeType(node, genType);
303 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
304 processUsesAugments((DataNodeContainer) node, context, inGrouping);
309 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
310 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
311 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
312 if (genType != null) {
313 constructGetter(parent, genType, node);
314 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
315 actionsToGenType(context, genType, node, null, inGrouping);
316 notificationsToGenType(context, genType, node, null, inGrouping);
320 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
321 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
322 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
323 if (genType != null) {
324 final List<String> listKeys = listKeys(node);
325 final GeneratedTOBuilder keyTypeBuilder;
326 if (!listKeys.isEmpty()) {
327 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
328 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
329 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
330 .addImplementsType(identifier(genType));
331 genType.addImplementsType(identifiable(keyTypeBuilder));
333 keyTypeBuilder = null;
336 // Decide whether to generate a List or a Map
337 final ParameterizedType listType;
338 if (keyTypeBuilder != null && !node.isUserOrdered()) {
339 listType = mapTypeFor(keyTypeBuilder, genType);
341 listType = listTypeFor(genType);
344 constructGetter(parent, listType, node).setMechanics(ValueMechanics.NULLIFY_EMPTY);
345 constructNonnull(parent, listType, node);
347 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
348 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
350 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
351 if (!schemaNode.isAugmenting()) {
352 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
357 if (keyTypeBuilder != null) {
358 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
359 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
360 keyTypeBuilder.setSUID(prop);
363 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
367 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
368 final boolean inGrouping) {
369 for (final UsesNode usesNode : node.getUses()) {
370 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
371 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
372 processUsesAugments(augment, context, inGrouping);
378 * Converts all <b>augmentation</b> of the module to the list
379 * <code>Type</code> objects.
382 * module from which is obtained list of all augmentation objects
383 * to iterate over them
384 * @throws IllegalArgumentException
386 * <li>if the module is null</li>
387 * <li>if the name of module is null</li>
389 * @throws IllegalStateException
390 * if set of augmentations from module is null
392 private void allAugmentsToGenTypes(final ModuleContext context) {
393 final Module module = context.module();
394 checkArgument(module != null, "Module reference cannot be NULL.");
395 checkArgument(module.getName() != null, "Module name cannot be NULL.");
396 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
398 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
399 augmentationToGenTypes(context, augment);
404 * Returns list of <code>AugmentationSchema</code> objects. The objects are
405 * sorted according to the length of their target path from the shortest to
409 * module from which is obtained list of all augmentation objects
410 * @return list of sorted <code>AugmentationSchema</code> objects obtained
411 * from <code>module</code>
412 * @throws IllegalArgumentException
414 * @throws IllegalStateException
415 * if set of module augmentations is null
417 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
418 checkArgument(module != null, "Module reference cannot be NULL.");
419 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
421 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(module.getAugmentations());
422 sortedAugmentations.sort(AUGMENT_COMP);
424 return sortedAugmentations;
428 * Create GeneratedTypeBuilder object from module argument.
431 * Module object from which builder will be created
432 * @return <code>GeneratedTypeBuilder</code> which is internal
433 * representation of the module
434 * @throws IllegalArgumentException
437 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
438 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
439 final Module module = context.module();
440 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
441 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
442 // if we have more than 2 top level uses statements we need to define getImplementedInterface() on the
443 // top level DataRoot object
444 if (module.getUses().size() > 1) {
445 narrowImplementedInterface(moduleDataTypeBuilder);
448 addCodegenInformation(moduleDataTypeBuilder, module);
449 return moduleDataTypeBuilder;
452 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
453 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
454 for (final ActionDefinition action : parentSchema.getActions()) {
455 if (action.isAugmenting()) {
459 final GeneratedType input;
460 final GeneratedType output;
461 if (action.isAddedByUses()) {
462 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
463 // Original definition may live in a different module, make sure we account for that
464 final ModuleContext origContext = moduleContext(
465 orig.getPath().getPathFromRoot().iterator().next().getModule());
466 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
467 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
469 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
470 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
473 if (!(parentSchema instanceof GroupingDefinition)) {
474 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
475 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
476 // and do not capture an actual instantiation.
477 final QName qname = action.getQName();
478 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
479 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
480 BindingMapping.getClassName(qname)));
481 qnameConstant(builder, context.moduleInfoType(), qname.getLocalName());
483 annotateDeprecatedIfNecessary(action, builder);
484 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
485 : action(parent, input, output));
487 addCodegenInformation(builder, context.module(), action);
488 context.addChildNodeType(action, builder);
493 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
494 final QName qname = action.getQName();
495 for (UsesNode uses : parent.getUses()) {
496 final GroupingDefinition grp = uses.getSourceGrouping();
497 // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
499 final Optional<ActionDefinition> found = grp.findAction(qname.bindTo(grp.getQName().getModule()));
500 if (found.isPresent()) {
501 final ActionDefinition result = found.get();
502 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
506 return Optional.empty();
509 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
510 final ContainerSchemaNode schema, final boolean inGrouping) {
511 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
512 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
513 return genType.build();
517 * Converts all <b>RPCs</b> input and output substatements of the module
518 * to the list of <code>Type</code> objects. In addition are to containers
519 * and lists which belong to input or output also part of returning list.
522 * module from which is obtained set of all rpc objects to
524 * @throws IllegalArgumentException
526 * <li>if the module is null</li>
527 * <li>if the name of module is null</li>
529 * @throws IllegalStateException
530 * if set of rpcs from module is null
532 private void rpcMethodsToGenType(final ModuleContext context) {
533 final Module module = context.module();
534 checkArgument(module.getName() != null, "Module name cannot be NULL.");
535 final Collection<? extends RpcDefinition> rpcDefinitions = module.getRpcs();
536 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
537 if (rpcDefinitions.isEmpty()) {
541 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
542 interfaceBuilder.addImplementsType(RPC_SERVICE);
544 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
546 for (final RpcDefinition rpc : rpcDefinitions) {
548 final String rpcName = BindingMapping.getClassName(rpc.getQName());
549 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
550 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
552 // Do not refer to annotation class, as it may not be available at runtime
553 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
554 addComment(method, rpc);
556 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
557 method.setReturnType(listenableFutureTypeFor(
558 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
562 context.addTopLevelNodeType(interfaceBuilder);
565 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
566 final ContainerSchemaNode schema, final Type type) {
567 processUsesAugments(schema, context, false);
568 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(context,
569 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
571 addImplementedInterfaceFromUses(schema, outType);
572 outType.addImplementsType(type);
573 outType.addImplementsType(augmentable(outType));
574 addConcreteInterfaceMethods(outType);
575 annotateDeprecatedIfNecessary(rpc, outType);
576 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
577 context.addChildNodeType(schema, outType);
578 return outType.build();
582 * Converts all <b>notifications</b> of the module to the list of
583 * <code>Type</code> objects. In addition are to this list added containers
584 * and lists which are part of this notification.
587 * module from which is obtained set of all notification objects
588 * to iterate over them
589 * @throws IllegalArgumentException
591 * <li>if the module equals null</li>
592 * <li>if the name of module equals null</li>
594 * @throws IllegalStateException
595 * if set of notifications from module is null
597 private void notificationsToGenType(final ModuleContext context) {
598 final Module module = context.module();
599 checkArgument(module.getName() != null, "Module name cannot be NULL.");
600 final Collection<? extends NotificationDefinition> notifications = module.getNotifications();
601 if (notifications.isEmpty()) {
605 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
606 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
608 for (final NotificationDefinition notification : notifications) {
609 if (notification != null) {
610 processUsesAugments(notification, context, false);
612 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
613 context.modulePackageName(), notification, DATA_OBJECT, context);
614 addConcreteInterfaceMethods(notificationInterface);
615 annotateDeprecatedIfNecessary(notification, notificationInterface);
616 notificationInterface.addImplementsType(NOTIFICATION);
617 context.addChildNodeType(notification, notificationInterface);
619 // Notification object
620 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
621 notification.getChildNodes(), false);
623 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
624 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
625 .setReturnType(primitiveVoidType()), notification);
629 addCodegenInformation(listenerInterface, module, "notifications", notifications);
630 context.addTopLevelNodeType(listenerInterface);
633 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
634 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
635 final boolean inGrouping) {
636 final Collection<? extends NotificationDefinition> notifications = parentSchema.getNotifications();
637 if (notifications.isEmpty()) {
641 for (NotificationDefinition notif : notifications) {
642 if (notif.isAugmenting()) {
645 if (parentSchema instanceof GroupingDefinition) {
646 // Notifications cannot be really established, as they lack instantiation context, which would be
647 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
651 processUsesAugments(notif, context, false);
653 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
654 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
655 addConcreteInterfaceMethods(notifInterface);
656 annotateDeprecatedIfNecessary(notif, notifInterface);
658 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
659 : instanceNotification(notifInterface, parent));
660 context.addChildNodeType(notif, notifInterface);
662 // Notification object
663 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
668 * Converts all <b>identities</b> of the module to the list of
669 * <code>Type</code> objects.
672 * module from which is obtained set of all identity objects to
674 * @param schemaContext
675 * schema context only used as input parameter for method
676 * {@link BindingGeneratorImpl#identityToGenType}
679 private void allIdentitiesToGenTypes(final ModuleContext context) {
680 final Collection<? extends IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
682 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
683 for (final IdentitySchemaNode identity : schemaIdentities) {
684 identityToGenType(context, identity);
690 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
691 * created transport object builder. If identity contains base identity then
692 * reference to base identity is added to superior identity as its extend.
693 * If identity doesn't contain base identity then only reference to abstract
694 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
695 * BaseIdentity} is added
699 * @param basePackageName
700 * string contains the module package name
702 * IdentitySchemaNode which contains data about identity
704 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
705 if (identity == null) {
709 JavaTypeName name = renames.get(identity);
711 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
712 BindingMapping.getClassName(identity.getQName()));
715 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
716 final Collection<? extends IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
717 if (!baseIdentities.isEmpty()) {
718 for (IdentitySchemaNode baseIdentity : baseIdentities) {
719 JavaTypeName base = renames.get(baseIdentity);
721 final QName qname = baseIdentity.getQName();
722 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
723 BindingMapping.getClassName(qname));
726 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
727 newType.addImplementsType(gto);
730 newType.addImplementsType(BASE_IDENTITY);
733 final Module module = context.module();
734 addCodegenInformation(newType, module, identity);
735 newType.setModuleName(module.getName());
736 newType.setSchemaPath(identity.getPath());
738 qnameConstant(newType, context.moduleInfoType(), identity.getQName().getLocalName());
740 context.addIdentityType(identity, newType);
743 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
744 final JavaTypeName yangModuleInfo, final String localName) {
745 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
746 new SimpleImmutableEntry<>(yangModuleInfo, localName));
750 * Converts all <b>groupings</b> of the module to the list of
751 * <code>Type</code> objects. Firstly are groupings sorted according mutual
752 * dependencies. At least dependent (independent) groupings are in the list
753 * saved at first positions. For every grouping the record is added to map
754 * {@link ModuleContext#groupings allGroupings}
759 * collection of groupings from which types will be generated
762 private void groupingsToGenTypes(final ModuleContext context,
763 final Collection<? extends GroupingDefinition> groupings) {
764 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
765 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
766 // node of grouping is resolved to the method.
767 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
768 narrowImplementedInterface(genType);
769 annotateDeprecatedIfNecessary(grouping, genType);
770 context.addGroupingType(grouping, genType);
771 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
772 groupingsToGenTypes(context, grouping.getGroupings());
773 processUsesAugments(grouping, context, true);
774 actionsToGenType(context, genType, grouping, null, true);
775 notificationsToGenType(context, genType, grouping, null, true);
780 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
781 * <code>enumTypeDef</code> item is added to builder with its name and value.
783 * @param enumTypeDef EnumTypeDefinition contains enum data
784 * @param enumName string contains name which will be assigned to enumeration builder
785 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
786 * @param module Module in which type should be generated
787 * @return enumeration builder which contains data from <code>enumTypeDef</code>
789 private Enumeration resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
790 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
791 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
792 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
793 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
794 final Enumeration ret = enumBuilder.toInstance(typeBuilder);
795 context.addTypeToSchema(ret, enumTypeDef);
796 context.addInnerTypedefType(enumTypeDef.getPath(), ret);
801 * Generates type builder for <code>module</code>.
803 * @param module Module which is source of package name for generated type builder
804 * @param postfix string which is added to the module class name representation as suffix
805 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
806 * @throws IllegalArgumentException if <code>module</code> is null
808 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
809 final Module module = context.module();
810 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
811 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
812 JavaTypeName.create(context.modulePackageName(), moduleName));
814 moduleBuilder.setModuleName(moduleName);
815 addCodegenInformation(moduleBuilder, module);
816 return moduleBuilder;
820 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
821 * In addition there are also generated types for all containers, list and choices which are child of
822 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
824 * @param augmentPackageName string with the name of the package to which the augmentation belongs
825 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
826 * @param module current module
827 * @throws IllegalArgumentException
829 * <li>if <code>augmentPackageName</code> equals null</li>
830 * <li>if <code>augSchema</code> equals null</li>
832 * @throws IllegalStateException
833 * if augment target path is null
835 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
836 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
837 checkState(augSchema.getTargetPath() != null,
838 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
840 processUsesAugments(augSchema, context, false);
841 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
842 SchemaNode targetSchemaNode = null;
844 // FIXME: can we use findDataSchemaNode() instead?
845 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath.getNodeIdentifiers());
846 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
847 if (targetSchemaNode instanceof DerivableSchemaNode) {
848 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
850 if (targetSchemaNode == null) {
851 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
852 + " in module " + context.module().getName());
855 if (targetSchemaNode == null) {
856 throw new IllegalArgumentException("augment target not found: " + targetPath);
859 if (targetSchemaNode instanceof ChoiceSchemaNode) {
860 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
861 checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
862 generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
863 augSchema.getChildNodes(), null, false);
867 final JavaTypeName targetName;
868 if (targetSchemaNode instanceof CaseSchemaNode) {
869 final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
870 checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
871 targetName = builder.getIdentifier();
873 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
874 if (builder == null) {
875 targetName = findAliasByPath(targetSchemaNode.getPath());
876 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
878 targetName = builder.getIdentifier();
882 addRawAugmentGenTypeDefinition(context, DefaultType.of(targetName), augSchema, false);
885 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
886 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
887 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
888 checkState(augSchema.getTargetPath() != null,
889 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
891 processUsesAugments(augSchema, context, inGrouping);
892 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
893 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
894 if (targetSchemaNode == null) {
895 throw new IllegalArgumentException("augment target not found: " + targetPath);
898 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
899 if (targetTypeBuilder == null) {
900 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
902 if (targetTypeBuilder == null) {
903 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
906 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
907 if (usesNodeParent instanceof SchemaNode) {
908 addRawAugmentGenTypeDefinition(context,
909 packageNameForAugmentedGeneratedType(context.modulePackageName(),
910 ((SchemaNode) usesNodeParent).getPath()),
911 targetTypeBuilder.build(), augSchema, inGrouping);
913 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
916 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
917 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
922 * Convenient method to find node added by uses statement.
924 * @param targetPath node path
925 * @param parentUsesNode parent of uses node
926 * @return node from its original location in grouping
928 private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaNodeIdentifier targetPath,
929 final UsesNode parentUsesNode) {
930 SchemaNode result = parentUsesNode.getSourceGrouping();
931 for (final QName node : targetPath.getNodeIdentifiers()) {
932 // FIXME: this dispatch is rather ugly, we probably want to refactor it a bit
933 if (result instanceof DataNodeContainer) {
934 final QName resultNode = node.bindTo(result.getQName().getModule());
936 SchemaNode found = ((DataNodeContainer) result).getDataChildByName(resultNode);
938 if (result instanceof ActionNodeContainer) {
939 found = ((ActionNodeContainer) result).findAction(resultNode).orElse(null);
941 if (found == null && result instanceof NotificationNodeContainer) {
942 found = ((NotificationNodeContainer) result).findNotification(resultNode).orElse(null);
946 } else if (result instanceof ChoiceSchemaNode) {
947 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
948 } else if (result instanceof ActionDefinition) {
949 final ActionDefinition action = (ActionDefinition) result;
950 final QName resultNode = node.bindTo(result.getQName().getModule());
952 final ContainerSchemaNode input = action.getInput();
953 final ContainerSchemaNode output = action.getOutput();
954 if (resultNode.equals(input.getQName())) {
956 } else if (resultNode.equals(output.getQName())) {
961 } else if (result != null) {
962 throw new IllegalStateException("Cannot handle " + result);
965 if (result == null) {
969 if (result instanceof DerivableSchemaNode) {
970 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
971 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
972 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
973 result = originalNode.get();
977 if (result instanceof DataSchemaNode) {
978 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
979 if (resultDataSchemaNode.isAddedByUses()) {
980 // The original node is required, but we have only the copy of
981 // the original node.
982 // Maybe this indicates a bug in Yang parser.
983 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
986 return resultDataSchemaNode;
989 throw new IllegalStateException(
990 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
995 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
996 * of augmented node with serial number as suffix.
998 * @param context current module
999 * @param augmentPackageName string with contains the package name to which the augment belongs
1000 * @param basePackageName string with the package name to which the augmented node belongs
1001 * @param targetTypeRef target type
1002 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
1003 * @return generated type builder for augment
1005 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
1006 final String augmentPackageName, final Type targetTypeRef,
1007 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1008 Map<String, GeneratedTypeBuilder> augmentBuilders =
1009 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
1010 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
1013 if (augIdentifier != null) {
1014 augTypeName = BindingMapping.getClassName(augIdentifier);
1016 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1019 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
1020 JavaTypeName.create(augmentPackageName, augTypeName));
1022 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
1023 addConcreteInterfaceMethods(augTypeBuilder);
1025 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
1026 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1028 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
1029 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1030 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1032 augmentBuilders.put(augTypeName, augTypeBuilder);
1034 if (!augSchema.getChildNodes().isEmpty()) {
1035 context.addTypeToAugmentation(augTypeBuilder, augSchema);
1038 context.addAugmentType(augTypeBuilder);
1039 return augTypeBuilder;
1042 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1043 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1044 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1048 private static String getAugmentIdentifier(final Collection<? extends UnknownSchemaNode> unknownSchemaNodes) {
1049 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1050 final QName nodeType = unknownSchemaNode.getNodeType();
1051 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1052 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1053 return unknownSchemaNode.getNodeParameter();
1060 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1061 * consists from name of augmented node and serial number of its augmentation.
1063 * @param builders map of builders which were created in the package to which the augmentation belongs
1064 * @param genTypeName string with name of augmented node
1065 * @return string with unique name for augmentation builder
1067 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1069 if (builders != null) {
1070 while (builders.containsKey(genTypeName + index)) {
1074 return genTypeName + index;
1078 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1079 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1080 * already part of them).
1082 * @param module current module
1083 * @param parent generated type builder which represents any node. The subnodes of this node are added
1084 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1085 * container, choice.
1086 * @param childOf parent type
1087 * @param schemaNodes set of data schema nodes which are the children of the node for which
1088 * <code>typeBuilder</code> was created
1089 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1090 * child nodes) could be added to it.
1092 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1093 final @Nullable Type childOf, final Iterable<? extends DataSchemaNode> schemaNodes,
1094 final boolean inGrouping) {
1095 if (schemaNodes != null && parent != null) {
1096 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1097 for (final DataSchemaNode schemaNode : schemaNodes) {
1098 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1099 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1107 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1110 * @param module current module
1111 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1112 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1113 * container, choice.
1114 * @param childOf parent type
1115 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1117 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1118 * The getter method could be added to it.
1120 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1121 final GeneratedTypeBuilder typeBuilder, final Iterable<? extends DataSchemaNode> schemaNodes,
1122 final boolean inGrouping) {
1123 if (schemaNodes != null && typeBuilder != null) {
1124 final Type baseInterface = childOf(typeBuilder);
1125 for (final DataSchemaNode schemaNode : schemaNodes) {
1126 if (!schemaNode.isAugmenting()) {
1127 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1135 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1137 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1138 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1139 * @param childOf parent type
1140 * @param module current module
1142 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1143 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1144 if (node != null && typeBuilder != null) {
1145 if (node instanceof LeafSchemaNode) {
1146 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1147 } else if (node instanceof LeafListSchemaNode) {
1148 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1149 } else if (node instanceof ContainerSchemaNode) {
1150 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1151 } else if (node instanceof ListSchemaNode) {
1152 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1153 } else if (node instanceof ChoiceSchemaNode) {
1154 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1155 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1156 opaqueToGeneratedType(context, typeBuilder, node);
1158 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1159 typeBuilder.getFullyQualifiedName());
1165 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1166 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1167 * and names of all parents node.
1169 * @param context current module
1170 * @param basePackageName string with the module package name
1171 * @param parent parent type
1172 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1174 * @throws IllegalArgumentException
1176 * <li>if <code>basePackageName</code> is null</li>
1177 * <li>if <code>choiceNode</code> is null</li>
1180 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1181 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1182 if (!choiceNode.isAddedByUses()) {
1183 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(context,
1184 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1185 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1186 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1187 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1188 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1190 final GeneratedType choiceType = choiceTypeBuilder.build();
1191 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1193 constructGetter(parent, choiceType, choiceNode);
1197 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1198 final DataSchemaNode anyNode) {
1199 if (!anyNode.isAddedByUses()) {
1200 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(context,
1201 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1202 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1203 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1204 defaultImplementedInterace(anyxmlTypeBuilder);
1205 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1206 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1208 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1213 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1214 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1215 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1216 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1218 * @param context current module context
1219 * @param refChoiceType type which represents superior <i>case</i>
1220 * @param choiceNode choice case node which is mapped to generated type
1221 * @throws IllegalArgumentException
1223 * <li>if <code>refChoiceType</code> equals null</li>
1224 * <li>if <code>caseNodes</code> equals null</li>
1227 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1228 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1229 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1230 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1232 for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
1233 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1234 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1235 caseTypeBuilder.addImplementsType(refChoiceType);
1236 addConcreteInterfaceMethods(caseTypeBuilder);
1237 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1238 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1239 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1240 final Iterable<? extends DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1241 if (caseChildNodes != null) {
1242 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1244 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1245 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1247 if (parent instanceof AugmentationSchemaNode) {
1248 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1249 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
1250 // FIXME: can we use findDataSchemaNode?
1251 SchemaNode targetSchemaNode = findNodeInSchemaContext(schemaContext,
1252 targetPath.getNodeIdentifiers());
1253 if (targetSchemaNode instanceof DataSchemaNode
1254 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1255 if (targetSchemaNode instanceof DerivableSchemaNode) {
1256 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1259 if (targetSchemaNode == null) {
1260 throw new IllegalStateException(
1261 "Failed to find target node from grouping for augmentation " + augSchema
1262 + " in module " + context.module().getName());
1265 parent = targetSchemaNode;
1268 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1269 Type childOfType = findChildNodeByPath(parent.getPath());
1270 if (childOfType == null) {
1271 childOfType = findGroupingByPath(parent.getPath());
1273 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1275 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1280 processUsesAugments(caseNode, context, inGrouping);
1285 * Generates list of generated types for all the cases of a choice which are added to the choice through
1288 * @param module current module
1289 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1290 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1291 * of the augmenting choice will belong to pcg2.
1292 * @param targetType Type which represents target choice
1293 * @param targetNode node which represents target choice
1294 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1296 * @throws IllegalArgumentException
1298 * <li>if <code>basePackageName</code> is null</li>
1299 * <li>if <code>targetType</code> is null</li>
1300 * <li>if <code>augmentedNodes</code> is null</li>
1303 // FIXME: nullness rules need to untangled in this method
1304 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1305 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1306 final Type targetType, final ChoiceSchemaNode targetNode,
1307 final Iterable<? extends DataSchemaNode> augmentedNodes,
1308 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1309 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1310 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1312 for (final DataSchemaNode caseNode : augmentedNodes) {
1313 if (caseNode != null) {
1314 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1315 caseTypeBuilder.addImplementsType(targetType);
1316 addConcreteInterfaceMethods(caseTypeBuilder);
1318 CaseSchemaNode node = null;
1319 final String caseLocalName = caseNode.getQName().getLocalName();
1320 if (caseNode instanceof CaseSchemaNode) {
1321 node = (CaseSchemaNode) caseNode;
1322 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1323 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1324 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1325 if (dataSchemaNode instanceof ChoiceSchemaNode
1326 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1327 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1332 node = findNamedCase(targetNode, caseLocalName);
1334 final Iterable<? extends DataSchemaNode> childNodes = node.getChildNodes();
1335 if (childNodes != null) {
1336 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1339 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1340 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1345 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1346 final SchemaPath nodePath = targetNode.getPath();
1347 final SchemaPath parentSp = nodePath.getParent();
1348 if (parentSp.getParent() == null) {
1349 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1352 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1353 GeneratedTypeBuilder childOfType = null;
1354 if (parent instanceof CaseSchemaNode) {
1355 childOfType = findCaseByPath(parent.getPath());
1356 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1357 childOfType = findChildNodeByPath(parent.getPath());
1358 } else if (parent instanceof GroupingDefinition) {
1359 childOfType = findGroupingByPath(parent.getPath());
1362 if (childOfType == null) {
1363 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1369 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1370 final List<? extends CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1371 return cases.isEmpty() ? null : cases.get(0);
1374 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1375 // New parser with encapsulated type
1376 if (leaf.getPath().equals(type.getPath())) {
1380 // Embedded type definition with new parser. Also takes care of the old parser with bits
1381 if (leaf.getPath().equals(type.getPath().getParent())) {
1388 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1389 final List<PatternConstraint> patternConstraints) {
1390 if (!patternConstraints.isEmpty()) {
1391 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1392 .append(BindingMapping.getPropertyName(leafName));
1393 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1394 typeProvider.resolveRegExpressions(patternConstraints));
1399 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1401 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1402 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1403 * @param module Module in which type was defined
1404 * @return boolean value
1406 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1408 * <li>true - in other cases</li>
1411 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1412 final ModuleContext context, final boolean inGrouping) {
1413 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1417 final Module parentModule = findParentModule(schemaContext, leaf);
1418 Type returnType = null;
1420 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1421 if (isInnerType(leaf, typeDef)) {
1422 if (typeDef instanceof EnumTypeDefinition) {
1423 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1424 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(), typeBuilder, context);
1425 typeProvider.putReferencedType(leaf.getPath(), returnType);
1426 } else if (typeDef instanceof UnionTypeDefinition) {
1427 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1428 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1429 // Store the inner type within the union so that we can find the reference for it
1430 context.addInnerTypedefType(typeDef.getPath(), returnType);
1431 } else if (typeDef instanceof BitsTypeDefinition) {
1432 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1434 if (genTOBuilder != null) {
1435 returnType = genTOBuilder.build();
1438 // It is constrained version of already declared type (inner declared type exists, only for special
1439 // cases (Enum, Union, Bits), which were already checked.
1440 // In order to get proper class we need to look up closest derived type and apply restrictions from leaf
1442 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1443 final TypeDefinition<?> baseOrDeclaredType = getBaseOrDeclaredType(typeDef);
1444 // we need to try to lookup an already generated type in case the leafref is targetting a generated type
1445 if (baseOrDeclaredType instanceof LeafrefTypeDefinition) {
1446 final SchemaNode leafrefTarget =
1447 typeProvider.getTargetForLeafref((LeafrefTypeDefinition) baseOrDeclaredType, leaf);
1448 if (leafrefTarget instanceof TypedDataSchemaNode) {
1449 returnType = context.getInnerType(((TypedDataSchemaNode) leafrefTarget).getType().getPath());
1452 if (returnType == null) {
1453 returnType = typeProvider.javaTypeForSchemaDefinitionType(baseOrDeclaredType, leaf,
1454 restrictions, inGrouping);
1457 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1460 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1461 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1462 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1465 if (returnType == null) {
1469 if (typeDef instanceof EnumTypeDefinition) {
1470 typeProvider.putReferencedType(leaf.getPath(), returnType);
1473 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1474 processContextRefExtension(leaf, getter, parentModule);
1478 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1479 // Returns DerivedType in case of new parser.
1480 final TypeDefinition<?> baseType = typeDef.getBaseType();
1481 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1484 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1485 final Module module) {
1486 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1487 final QName nodeType = node.getNodeType();
1488 if ("context-reference".equals(nodeType.getLocalName())) {
1489 final String nodeParam = node.getNodeParameter();
1490 IdentitySchemaNode identity = null;
1491 String basePackageName = null;
1492 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1493 final Iterator<String> iterator = splittedElement.iterator();
1494 final int length = Iterables.size(splittedElement);
1496 identity = findIdentityByName(module.getIdentities(), iterator.next());
1497 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1498 } else if (length == 2) {
1499 final String prefix = iterator.next();
1500 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1501 if (dependentModule == null) {
1502 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1505 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1506 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1508 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1511 if (identity == null) {
1512 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1516 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1517 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1518 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1519 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1524 private static IdentitySchemaNode findIdentityByName(final Collection<? extends IdentitySchemaNode> identities,
1525 final String name) {
1526 for (final IdentitySchemaNode id : identities) {
1527 if (id.getQName().getLocalName().equals(name)) {
1534 private Module findModuleFromImports(final Collection<? extends ModuleImport> imports, final String prefix) {
1535 for (final ModuleImport imp : imports) {
1536 if (imp.getPrefix().equals(prefix)) {
1537 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1543 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1544 final boolean isReadOnly) {
1545 if (leaf != null && toBuilder != null) {
1547 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1548 if (typeDef instanceof UnionTypeDefinition) {
1549 // GeneratedType for this type definition should have be already created
1550 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1551 returnType = mc.getTypedefs().get(typeDef.getPath());
1552 if (returnType == null) {
1553 // This may still be an inner type, try to find it
1554 returnType = mc.getInnerType(typeDef.getPath());
1556 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1557 // Annonymous enumeration (already generated, since it is inherited via uses).
1558 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1559 QName qname = originalLeaf.getQName();
1560 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1562 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1564 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1570 * Converts <code>leaf</code> schema node to property of generated TO builder.
1572 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1573 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1574 * @param returnType property type
1575 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1576 * @return boolean value
1578 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1579 * name equals null or if leaf is added by <i>uses</i>.</li>
1580 * <li>true - other cases</li>
1583 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1584 final Type returnType, final boolean isReadOnly) {
1585 if (returnType == null) {
1588 final String leafName = leaf.getQName().getLocalName();
1589 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1590 propBuilder.setReadOnly(isReadOnly);
1591 propBuilder.setReturnType(returnType);
1592 addComment(propBuilder, leaf);
1594 toBuilder.addEqualsIdentity(propBuilder);
1595 toBuilder.addHashIdentity(propBuilder);
1596 toBuilder.addToStringProperty(propBuilder);
1601 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1603 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1604 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1605 * @param module module
1606 * @return boolean value
1608 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1609 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1610 * <li>false - other cases</li>
1613 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1614 final ModuleContext context, final boolean inGrouping) {
1615 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1619 final QName nodeName = node.getQName();
1621 final TypeDefinition<?> typeDef = node.getType();
1622 final Module parentModule = findParentModule(schemaContext, node);
1624 Type returnType = null;
1625 if (typeDef.getBaseType() == null) {
1626 if (typeDef instanceof EnumTypeDefinition) {
1627 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1628 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName, typeBuilder, context);
1629 typeProvider.putReferencedType(node.getPath(), returnType);
1630 } else if (typeDef instanceof UnionTypeDefinition) {
1631 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1632 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1633 } else if (typeDef instanceof BitsTypeDefinition) {
1634 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1635 node, parentModule);
1636 returnType = genTOBuilder.build();
1638 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1639 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1640 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1643 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1644 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1645 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1648 constructGetter(typeBuilder, listTypeFor(returnType), node);
1652 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1653 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1654 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1655 returnTypeBuilder.setIsUnion(true);
1656 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1657 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1658 returnTypeBuilder.setModuleName(parentModule.getName());
1659 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1661 genTOBuilder.setTypedef(true);
1662 genTOBuilder.setIsUnion(true);
1663 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1665 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1669 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1670 final GeneratedTransferObject returnType, final Module parentModule) {
1671 // Append enclosing path hierarchy without dots
1672 final StringBuilder sb = new StringBuilder();
1673 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1674 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1675 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1676 unionBuilder.setIsUnionBuilder(true);
1678 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1679 method.setReturnType(returnType);
1680 method.addParameter(STRING, "defaultValue");
1681 method.setAccessModifier(AccessModifier.PUBLIC);
1682 method.setStatic(true);
1684 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1685 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1688 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1689 final SchemaNode schemaNode) {
1690 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1693 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1694 final SchemaNode schemaNode, final Type baseInterface) {
1695 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1696 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1700 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1701 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1702 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1703 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1704 * If <code>schemaNode</code> is instance of
1705 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1706 * which are specified in <i>uses</i>.
1708 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1709 * @param schemaNode schema node for which is created generated type builder
1710 * @param parent parent type (can be null)
1711 * @return generated type builder <code>schemaNode</code>
1713 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1714 final Type baseInterface, final ModuleContext context) {
1715 JavaTypeName name = renames.get(schemaNode);
1717 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1720 final GeneratedTypeBuilder it = addRawInterfaceDefinition(context, name, schemaNode);
1721 it.addImplementsType(baseInterface);
1722 if (!(schemaNode instanceof GroupingDefinition)) {
1723 it.addImplementsType(augmentable(it));
1725 if (schemaNode instanceof DataNodeContainer) {
1726 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1727 groupingsToGenTypes(context, containerSchema.getGroupings());
1728 addImplementedInterfaceFromUses(containerSchema, it);
1735 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1736 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1737 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1739 * @param packageName string with the package name to which returning generated type builder belongs
1740 * @param schemaNode schema node which provide data about the schema node name
1741 * @param prefix return type name prefix
1742 * @return generated type builder for <code>schemaNode</code>
1743 * @throws IllegalArgumentException
1745 * <li>if <code>schemaNode</code> is null</li>
1746 * <li>if <code>packageName</code> is null</li>
1747 * <li>if QName of schema node is null</li>
1748 * <li>if schemaNode name is null</li>
1751 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final JavaTypeName identifier,
1752 final SchemaNode schemaNode) {
1753 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1754 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1755 final String schemaNodeName = schemaNode.getQName().getLocalName();
1756 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1758 // FIXME: Validation of name conflict
1759 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1760 qnameConstant(newType, context.moduleInfoType(), schemaNode.getQName().getLocalName());
1762 final Module module = context.module();
1763 addCodegenInformation(newType, module, schemaNode);
1764 newType.setSchemaPath(schemaNode.getPath());
1765 newType.setModuleName(module.getName());
1767 final String packageName = identifier.packageName();
1768 final String simpleName = identifier.simpleName();
1769 if (!genTypeBuilders.containsKey(packageName)) {
1770 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1771 builders.put(simpleName, newType);
1772 genTypeBuilders.put(packageName, builders);
1774 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1775 if (!builders.containsKey(simpleName)) {
1776 builders.put(simpleName, newType);
1783 * Creates the name of the getter method name from <code>localName</code>.
1785 * @param localName string with the name of the getter method
1786 * @param returnType return type
1787 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1789 public static String getterMethodName(final String localName, final Type returnType) {
1790 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1794 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1795 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1796 * and <code>returnType</code> information are added to the builder.
1798 * @param interfaceBuilder generated type builder for which the getter method should be created
1799 * @param returnType type which represents the return type of the getter method
1800 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1801 * @param comment string with comment for the getter method
1802 * @param status status from yang file, for deprecated annotation
1803 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1805 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1806 final SchemaNode node) {
1807 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1808 getterMethodName(node.getQName().getLocalName(), returnType));
1809 getMethod.setReturnType(returnType);
1811 annotateDeprecatedIfNecessary(node, getMethod);
1812 addComment(getMethod, node);
1817 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1818 final ListSchemaNode node) {
1819 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1820 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1821 getMethod.setReturnType(returnType).setDefault(true);
1822 annotateDeprecatedIfNecessary(node, getMethod);
1826 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1829 * @param basePackageName string contains the module package name
1830 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1831 * or as a property to <code>genTOBuilder</code> if is part of the list key
1832 * @param typeBuilder generated type builder for the list schema node
1833 * @param genTOBuilder generated TO builder for the list keys
1834 * @param listKeys list of string which contains names of the list keys
1835 * @param module current module
1836 * @throws IllegalArgumentException
1838 * <li>if <code>schemaNode</code> equals null</li>
1839 * <li>if <code>typeBuilder</code> equals null</li>
1842 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1843 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1844 final List<String> listKeys, final boolean inGrouping) {
1845 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1846 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1848 if (schemaNode instanceof LeafSchemaNode) {
1849 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1850 final String leafName = leaf.getQName().getLocalName();
1851 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1852 if (listKeys.contains(leafName)) {
1854 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1856 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1859 } else if (!schemaNode.isAddedByUses()) {
1860 if (schemaNode instanceof LeafListSchemaNode) {
1861 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1862 } else if (schemaNode instanceof ContainerSchemaNode) {
1863 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1864 (ContainerSchemaNode) schemaNode, inGrouping);
1865 } else if (schemaNode instanceof ChoiceSchemaNode) {
1866 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1867 } else if (schemaNode instanceof ListSchemaNode) {
1868 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1869 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1870 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1875 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1876 final GeneratedTOBuilder genTOBuilder) {
1877 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1879 if (genTOBuilder != null) {
1880 final GeneratedTransferObject genTO = genTOBuilder.build();
1881 // Add Identifiable.getKey() for items
1882 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1883 .addAnnotation(OVERRIDE_ANNOTATION);
1884 context.addGeneratedTOBuilder(genTOBuilder);
1889 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1891 * @param list of string with names of the list keys
1892 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1893 * an empty list is returned.
1895 private static List<String> listKeys(final ListSchemaNode list) {
1896 final List<QName> keyDefinition = list.getKeyDefinition();
1897 switch (keyDefinition.size()) {
1899 return Collections.emptyList();
1901 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1903 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1904 for (final QName keyDef : keyDefinition) {
1905 listKeys.add(keyDef.getLocalName());
1912 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1913 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1914 * enclosing transfer objects.
1916 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1917 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1918 * @param leaf string with name for generated TO builder
1919 * @param parentModule parent module
1920 * @return generated TO builder for <code>typeDef</code>
1922 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1923 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1924 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1925 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1927 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1928 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1929 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1930 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1931 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1933 for (GeneratedTOBuilder builder : types) {
1934 if (builder.isUnion()) {
1935 final GeneratedTransferObject type = builder.build();
1936 createUnionBuilder(builder, typeBuilder, type, parentModule);
1940 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1944 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1945 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1946 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1949 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1950 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1951 * @param leaf string with name for generated TO builder
1952 * @param parentModule parent module
1953 * @return generated TO builder for <code>typeDef</code>
1955 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1956 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1957 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1958 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1959 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1960 return genTOBuilder;
1964 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1965 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1966 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1967 * to <code>builder</code>
1969 * @param dataNodeContainer element which contains the list of used YANG groupings
1970 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1971 * @return generated type builder with all implemented types
1973 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1974 final GeneratedTypeBuilder builder) {
1975 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1976 final GeneratedTypeBuilder genType = findGrouping(usesNode.getSourceGrouping());
1977 if (genType == null) {
1978 throw new IllegalStateException("Grouping " + usesNode.getSourceGrouping().getQName()
1979 + " is not resolved for " + builder.getFullyQualifiedName());
1982 builder.addImplementsType(genType.build());
1987 private JavaTypeName findAliasByPath(final SchemaPath path) {
1988 for (final ModuleContext ctx : genCtx.values()) {
1989 final JavaTypeName result = ctx.getAlias(path);
1990 if (result != null) {
1997 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1998 for (final ModuleContext ctx : genCtx.values()) {
1999 final GeneratedTypeBuilder result = ctx.getChildNode(path);
2000 if (result != null) {
2007 private GeneratedTypeBuilder findGrouping(final GroupingDefinition grouping) {
2008 for (final ModuleContext ctx : genCtx.values()) {
2009 final GeneratedTypeBuilder result = ctx.getGrouping(grouping.getPath());
2010 if (result != null) {
2017 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2018 for (final ModuleContext ctx : genCtx.values()) {
2019 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2020 if (result != null) {
2027 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2028 for (final ModuleContext ctx : genCtx.values()) {
2029 final GeneratedTypeBuilder result = ctx.getCase(path);
2030 if (result != null) {
2037 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
2038 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
2039 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
2042 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
2043 switch (node.getStatus()) {
2045 // FIXME: we really want to use a pre-made annotation
2046 builder.addAnnotation(DEPRECATED_ANNOTATION);
2049 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
2055 throw new IllegalStateException("Unhandled status in " + node);
2059 private static void addConcreteInterfaceMethods(final GeneratedTypeBuilder typeBuilder) {
2060 defaultImplementedInterace(typeBuilder);
2062 typeBuilder.addMethod(BindingMapping.BINDING_TO_STRING_NAME)
2063 .setAccessModifier(AccessModifier.PUBLIC)
2065 .setReturnType(STRING);
2068 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2069 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2072 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2073 defineImplementedInterfaceMethod(typeBuilder, DefaultType.of(typeBuilder)).setDefault(true);
2076 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2077 final Type classType) {
2078 final MethodSignatureBuilder ret = typeBuilder
2079 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2080 .setAccessModifier(AccessModifier.PUBLIC)
2081 .setReturnType(classType(classType));
2082 ret.addAnnotation(OVERRIDE_ANNOTATION);