2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.mdsal.binding.generator.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
15 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.BASE_IDENTITY;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.QNAME;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentation;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
34 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.instanceNotification;
35 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
36 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListNotification;
37 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.opaqueObject;
38 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
39 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
40 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
41 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
42 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
43 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
44 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
45 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
46 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
47 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
48 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
50 import com.google.common.base.Splitter;
51 import com.google.common.collect.Iterables;
52 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
53 import java.util.AbstractMap.SimpleImmutableEntry;
54 import java.util.ArrayList;
55 import java.util.Collection;
56 import java.util.Collections;
57 import java.util.Comparator;
58 import java.util.HashMap;
59 import java.util.HashSet;
60 import java.util.Iterator;
61 import java.util.List;
63 import java.util.Optional;
65 import org.eclipse.jdt.annotation.Nullable;
66 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
67 import org.opendaylight.mdsal.binding.model.api.Constant;
68 import org.opendaylight.mdsal.binding.model.api.Enumeration;
69 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
70 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
71 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
72 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
73 import org.opendaylight.mdsal.binding.model.api.Restrictions;
74 import org.opendaylight.mdsal.binding.model.api.Type;
75 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
76 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
83 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
84 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
85 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
86 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
87 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
88 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
89 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
90 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
91 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
92 import org.opendaylight.yangtools.yang.common.QName;
93 import org.opendaylight.yangtools.yang.common.QNameModule;
94 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
95 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
96 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
103 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
106 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
107 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
108 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
112 import org.opendaylight.yangtools.yang.model.api.Module;
113 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
114 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
115 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
116 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
117 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
118 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
119 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
120 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
121 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
122 import org.opendaylight.yangtools.yang.model.api.UsesNode;
123 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
124 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
125 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
126 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
127 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
128 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
129 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
130 import org.slf4j.Logger;
131 import org.slf4j.LoggerFactory;
133 abstract class AbstractTypeGenerator {
134 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
135 private static final Splitter COLON_SPLITTER = Splitter.on(':');
136 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
137 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
138 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
141 * Comparator based on augment target path.
143 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
144 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
145 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
147 while (thisIt.hasNext()) {
148 if (!otherIt.hasNext()) {
152 final int comp = thisIt.next().compareTo(otherIt.next());
158 return otherIt.hasNext() ? -1 : 0;
162 * Constant with the concrete name of identifier.
164 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
167 * Constant with the concrete name of namespace.
169 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
171 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
174 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
175 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
176 * for schema node specified in key part.
178 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
181 * Provide methods for converting YANG types to JAVA types.
183 private final AbstractTypeProvider typeProvider;
186 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
188 private final SchemaContext schemaContext;
191 * Holds renamed elements.
193 private final Map<SchemaNode, JavaTypeName> renames;
195 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
196 final Map<SchemaNode, JavaTypeName> renames) {
197 this.schemaContext = requireNonNull(context);
198 this.typeProvider = requireNonNull(typeProvider);
199 this.renames = requireNonNull(renames);
201 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
202 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
203 for (final Module contextModule : contextModules) {
204 contexts.add(moduleToGenTypes(contextModule));
207 contexts.forEach(this::allAugmentsToGenTypes);
210 final Collection<ModuleContext> moduleContexts() {
211 return genCtx.values();
214 final ModuleContext moduleContext(final QNameModule module) {
215 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
218 final AbstractTypeProvider typeProvider() {
222 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
224 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
226 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
227 Set<? extends SchemaNode> nodes);
229 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
231 private ModuleContext moduleToGenTypes(final Module module) {
232 final ModuleContext context = new ModuleContext(module);
233 genCtx.put(module.getQNameModule(), context);
234 allTypeDefinitionsToGenTypes(context);
235 groupingsToGenTypes(context, module.getGroupings());
236 allIdentitiesToGenTypes(context);
238 if (!module.getChildNodes().isEmpty()) {
239 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
240 context.addModuleNode(moduleType);
241 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
244 // Resolve RPCs and notifications only after we have created instantiated tree
245 rpcMethodsToGenType(context);
246 notificationsToGenType(context);
251 * Converts all extended type definitions of module to the list of
252 * <code>Type</code> objects.
255 * module from which is obtained set of type definitions
256 * @throws IllegalArgumentException
258 * <li>if module is null</li>
259 * <li>if name of module is null</li>
261 * @throws IllegalStateException
262 * if set of type definitions from module is null
264 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
265 final Module module = context.module();
266 checkArgument(module.getName() != null, "Module name cannot be NULL.");
268 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
269 if (typedef != null) {
270 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
272 context.addTypedefType(typedef, type);
273 context.addTypeToSchema(type,typedef);
279 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
280 final DataSchemaNode node, final boolean inGrouping) {
281 if (node.isAugmenting() || node.isAddedByUses()) {
284 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
285 defaultImplementedInterace(genType);
286 annotateDeprecatedIfNecessary(node, genType);
288 final Module module = context.module();
289 genType.setModuleName(module.getName());
290 addCodegenInformation(genType, module, node);
291 genType.setSchemaPath(node.getPath());
292 if (node instanceof DataNodeContainer) {
293 context.addChildNodeType(node, genType);
294 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
295 processUsesAugments((DataNodeContainer) node, context, inGrouping);
300 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
301 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
302 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
303 if (genType != null) {
304 constructGetter(parent, genType, node);
305 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
306 actionsToGenType(context, genType, node, null, inGrouping);
307 notificationsToGenType(context, genType, node, null, inGrouping);
311 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
312 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
313 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
314 if (genType != null) {
315 final List<String> listKeys = listKeys(node);
316 final GeneratedTOBuilder keyTypeBuilder;
317 if (!listKeys.isEmpty()) {
318 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
319 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
320 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
321 .addImplementsType(identifier(genType));
322 genType.addImplementsType(identifiable(keyTypeBuilder));
324 keyTypeBuilder = null;
327 final ParameterizedType listType = listTypeFor(genType);
328 constructGetter(parent, listType, node);
329 constructNonnull(parent, listType, node);
331 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
332 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
334 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
335 if (!schemaNode.isAugmenting()) {
336 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
341 if (keyTypeBuilder != null) {
342 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
343 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
344 keyTypeBuilder.setSUID(prop);
347 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
351 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
352 final boolean inGrouping) {
353 for (final UsesNode usesNode : node.getUses()) {
354 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
355 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
356 processUsesAugments(augment, context, inGrouping);
362 * Converts all <b>augmentation</b> of the module to the list
363 * <code>Type</code> objects.
366 * module from which is obtained list of all augmentation objects
367 * to iterate over them
368 * @throws IllegalArgumentException
370 * <li>if the module is null</li>
371 * <li>if the name of module is null</li>
373 * @throws IllegalStateException
374 * if set of augmentations from module is null
376 private void allAugmentsToGenTypes(final ModuleContext context) {
377 final Module module = context.module();
378 checkArgument(module != null, "Module reference cannot be NULL.");
379 checkArgument(module.getName() != null, "Module name cannot be NULL.");
380 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
382 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
383 augmentationToGenTypes(context, augment);
388 * Returns list of <code>AugmentationSchema</code> objects. The objects are
389 * sorted according to the length of their target path from the shortest to
393 * module from which is obtained list of all augmentation objects
394 * @return list of sorted <code>AugmentationSchema</code> objects obtained
395 * from <code>module</code>
396 * @throws IllegalArgumentException
398 * @throws IllegalStateException
399 * if set of module augmentations is null
401 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
402 checkArgument(module != null, "Module reference cannot be NULL.");
403 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
405 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
406 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
407 sortedAugmentations.sort(AUGMENT_COMP);
409 return sortedAugmentations;
413 * Create GeneratedTypeBuilder object from module argument.
416 * Module object from which builder will be created
417 * @return <code>GeneratedTypeBuilder</code> which is internal
418 * representation of the module
419 * @throws IllegalArgumentException
422 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
423 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
424 final Module module = context.module();
425 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
426 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
428 addCodegenInformation(moduleDataTypeBuilder, module);
429 return moduleDataTypeBuilder;
432 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
433 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
434 for (final ActionDefinition action : parentSchema.getActions()) {
435 if (action.isAugmenting()) {
439 final GeneratedType input;
440 final GeneratedType output;
441 if (action.isAddedByUses()) {
442 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
443 // Original definition may live in a different module, make sure we account for that
444 final ModuleContext origContext = moduleContext(
445 orig.getPath().getPathFromRoot().iterator().next().getModule());
446 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
447 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
449 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
450 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
453 if (!(parentSchema instanceof GroupingDefinition)) {
454 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
455 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
456 // and do not capture an actual instantiation.
457 final QName qname = action.getQName();
458 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
459 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
460 BindingMapping.getClassName(qname)));
461 qnameConstant(builder, context.moduleInfoType(), qname.getLocalName());
463 annotateDeprecatedIfNecessary(action, builder);
464 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
465 : action(parent, input, output));
467 addCodegenInformation(builder, context.module(), action);
468 context.addChildNodeType(action, builder);
473 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
474 final QName qname = action.getQName();
475 for (UsesNode uses : parent.getUses()) {
476 final GroupingDefinition grp = findUsedGrouping(uses);
477 // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
479 final Optional<ActionDefinition> found = grp.findAction(qname.withModule(grp.getQName().getModule()));
480 if (found.isPresent()) {
481 final ActionDefinition result = found.get();
482 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
486 return Optional.empty();
489 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
490 final ContainerSchemaNode schema, final boolean inGrouping) {
491 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
492 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
493 return genType.build();
497 * Converts all <b>RPCs</b> input and output substatements of the module
498 * to the list of <code>Type</code> objects. In addition are to containers
499 * and lists which belong to input or output also part of returning list.
502 * module from which is obtained set of all rpc objects to
504 * @throws IllegalArgumentException
506 * <li>if the module is null</li>
507 * <li>if the name of module is null</li>
509 * @throws IllegalStateException
510 * if set of rpcs from module is null
512 private void rpcMethodsToGenType(final ModuleContext context) {
513 final Module module = context.module();
514 checkArgument(module.getName() != null, "Module name cannot be NULL.");
515 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
516 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
517 if (rpcDefinitions.isEmpty()) {
521 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
522 interfaceBuilder.addImplementsType(RPC_SERVICE);
524 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
526 for (final RpcDefinition rpc : rpcDefinitions) {
528 final String rpcName = BindingMapping.getClassName(rpc.getQName());
529 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
530 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
532 // Do not refer to annotation class, as it may not be available at runtime
533 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
534 addComment(method, rpc);
536 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
537 method.setReturnType(listenableFutureTypeFor(
538 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
542 context.addTopLevelNodeType(interfaceBuilder);
545 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
546 final ContainerSchemaNode schema, final Type type) {
547 processUsesAugments(schema, context, false);
548 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(context,
549 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
551 addImplementedInterfaceFromUses(schema, outType);
552 outType.addImplementsType(type);
553 outType.addImplementsType(augmentable(outType));
554 defaultImplementedInterace(outType);
555 annotateDeprecatedIfNecessary(rpc, outType);
556 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
557 context.addChildNodeType(schema, outType);
558 return outType.build();
562 * Converts all <b>notifications</b> of the module to the list of
563 * <code>Type</code> objects. In addition are to this list added containers
564 * and lists which are part of this notification.
567 * module from which is obtained set of all notification objects
568 * to iterate over them
569 * @throws IllegalArgumentException
571 * <li>if the module equals null</li>
572 * <li>if the name of module equals null</li>
574 * @throws IllegalStateException
575 * if set of notifications from module is null
577 private void notificationsToGenType(final ModuleContext context) {
578 final Module module = context.module();
579 checkArgument(module.getName() != null, "Module name cannot be NULL.");
580 final Set<NotificationDefinition> notifications = module.getNotifications();
581 if (notifications.isEmpty()) {
585 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
586 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
588 for (final NotificationDefinition notification : notifications) {
589 if (notification != null) {
590 processUsesAugments(notification, context, false);
592 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
593 context.modulePackageName(), notification, DATA_OBJECT, context);
594 defaultImplementedInterace(notificationInterface);
595 annotateDeprecatedIfNecessary(notification, notificationInterface);
596 notificationInterface.addImplementsType(NOTIFICATION);
597 context.addChildNodeType(notification, notificationInterface);
599 // Notification object
600 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
601 notification.getChildNodes(), false);
603 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
604 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
605 .setReturnType(primitiveVoidType()), notification);
609 addCodegenInformation(listenerInterface, module, "notifications", notifications);
610 context.addTopLevelNodeType(listenerInterface);
613 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
614 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
615 final boolean inGrouping) {
616 final Set<NotificationDefinition> notifications = parentSchema.getNotifications();
617 if (notifications.isEmpty()) {
621 for (NotificationDefinition notif : notifications) {
622 if (notif.isAugmenting()) {
625 if (parentSchema instanceof GroupingDefinition) {
626 // Notifications cannot be really established, as they lack instantiation context, which would be
627 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
631 processUsesAugments(notif, context, false);
633 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
634 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
635 defaultImplementedInterace(notifInterface);
636 annotateDeprecatedIfNecessary(notif, notifInterface);
638 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
639 : instanceNotification(notifInterface, parent));
640 context.addChildNodeType(notif, notifInterface);
642 // Notification object
643 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
648 * Converts all <b>identities</b> of the module to the list of
649 * <code>Type</code> objects.
652 * module from which is obtained set of all identity objects to
654 * @param schemaContext
655 * schema context only used as input parameter for method
656 * {@link BindingGeneratorImpl#identityToGenType}
659 private void allIdentitiesToGenTypes(final ModuleContext context) {
660 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
662 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
663 for (final IdentitySchemaNode identity : schemaIdentities) {
664 identityToGenType(context, identity);
670 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
671 * created transport object builder. If identity contains base identity then
672 * reference to base identity is added to superior identity as its extend.
673 * If identity doesn't contain base identity then only reference to abstract
674 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
675 * BaseIdentity} is added
679 * @param basePackageName
680 * string contains the module package name
682 * IdentitySchemaNode which contains data about identity
684 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
685 if (identity == null) {
689 JavaTypeName name = renames.get(identity);
691 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
692 BindingMapping.getClassName(identity.getQName()));
695 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
696 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
697 if (!baseIdentities.isEmpty()) {
698 for (IdentitySchemaNode baseIdentity : baseIdentities) {
699 JavaTypeName base = renames.get(baseIdentity);
701 final QName qname = baseIdentity.getQName();
702 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
703 BindingMapping.getClassName(qname));
706 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
707 newType.addImplementsType(gto);
710 newType.addImplementsType(BASE_IDENTITY);
713 final Module module = context.module();
714 addCodegenInformation(newType, module, identity);
715 newType.setModuleName(module.getName());
716 newType.setSchemaPath(identity.getPath());
718 qnameConstant(newType, context.moduleInfoType(), identity.getQName().getLocalName());
720 context.addIdentityType(identity, newType);
723 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
724 final JavaTypeName yangModuleInfo, final String localName) {
725 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
726 new SimpleImmutableEntry<>(yangModuleInfo, localName));
730 * Converts all <b>groupings</b> of the module to the list of
731 * <code>Type</code> objects. Firstly are groupings sorted according mutual
732 * dependencies. At least dependent (independent) groupings are in the list
733 * saved at first positions. For every grouping the record is added to map
734 * {@link ModuleContext#groupings allGroupings}
739 * collection of groupings from which types will be generated
742 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
743 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
744 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
745 // node of grouping is resolved to the method.
746 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
747 narrowImplementedInterface(genType);
748 annotateDeprecatedIfNecessary(grouping, genType);
749 context.addGroupingType(grouping, genType);
750 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
751 groupingsToGenTypes(context, grouping.getGroupings());
752 processUsesAugments(grouping, context, true);
753 actionsToGenType(context, genType, grouping, null, true);
754 notificationsToGenType(context, genType, grouping, null, true);
759 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
760 * <code>enumTypeDef</code> item is added to builder with its name and value.
762 * @param enumTypeDef EnumTypeDefinition contains enum data
763 * @param enumName string contains name which will be assigned to enumeration builder
764 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
765 * @param module Module in which type should be generated
766 * @return enumeration builder which contains data from <code>enumTypeDef</code>
768 private Enumeration resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
769 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
770 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
771 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
772 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
773 final Enumeration ret = enumBuilder.toInstance(typeBuilder);
774 context.addTypeToSchema(ret, enumTypeDef);
775 context.addInnerTypedefType(enumTypeDef.getPath(), ret);
780 * Generates type builder for <code>module</code>.
782 * @param module Module which is source of package name for generated type builder
783 * @param postfix string which is added to the module class name representation as suffix
784 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
785 * @throws IllegalArgumentException if <code>module</code> is null
787 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
788 final Module module = context.module();
789 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
790 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
791 JavaTypeName.create(context.modulePackageName(), moduleName));
793 moduleBuilder.setModuleName(moduleName);
794 addCodegenInformation(moduleBuilder, module);
795 return moduleBuilder;
799 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
800 * In addition there are also generated types for all containers, list and choices which are child of
801 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
803 * @param augmentPackageName string with the name of the package to which the augmentation belongs
804 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
805 * @param module current module
806 * @throws IllegalArgumentException
808 * <li>if <code>augmentPackageName</code> equals null</li>
809 * <li>if <code>augSchema</code> equals null</li>
811 * @throws IllegalStateException
812 * if augment target path is null
814 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
815 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
816 checkState(augSchema.getTargetPath() != null,
817 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
819 processUsesAugments(augSchema, context, false);
820 final SchemaPath targetPath = augSchema.getTargetPath();
821 SchemaNode targetSchemaNode = null;
823 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
824 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
825 if (targetSchemaNode instanceof DerivableSchemaNode) {
826 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
828 if (targetSchemaNode == null) {
829 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
830 + " in module " + context.module().getName());
833 if (targetSchemaNode == null) {
834 throw new IllegalArgumentException("augment target not found: " + targetPath);
837 if (targetSchemaNode instanceof ChoiceSchemaNode) {
838 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
839 checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
840 generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
841 augSchema.getChildNodes(), null, false);
845 final JavaTypeName targetName;
846 if (targetSchemaNode instanceof CaseSchemaNode) {
847 final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
848 checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
849 targetName = builder.getIdentifier();
851 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
852 if (builder == null) {
853 targetName = findAliasByPath(targetSchemaNode.getPath());
854 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
856 targetName = builder.getIdentifier();
860 addRawAugmentGenTypeDefinition(context, new ReferencedTypeImpl(targetName), augSchema, false);
863 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
864 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
865 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
866 checkState(augSchema.getTargetPath() != null,
867 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
869 processUsesAugments(augSchema, context, inGrouping);
870 final SchemaPath targetPath = augSchema.getTargetPath();
871 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
872 if (targetSchemaNode == null) {
873 throw new IllegalArgumentException("augment target not found: " + targetPath);
876 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
877 if (targetTypeBuilder == null) {
878 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
880 if (targetTypeBuilder == null) {
881 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
884 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
885 if (usesNodeParent instanceof SchemaNode) {
886 addRawAugmentGenTypeDefinition(context,
887 packageNameForAugmentedGeneratedType(context.modulePackageName(),
888 ((SchemaNode) usesNodeParent).getPath()),
889 targetTypeBuilder.build(), augSchema, inGrouping);
891 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
894 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
895 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
899 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
900 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
902 if (targetGrouping instanceof GroupingDefinition) {
903 return (GroupingDefinition) targetGrouping;
906 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
910 * Convenient method to find node added by uses statement.
912 * @param targetPath node path
913 * @param parentUsesNode parent of uses node
914 * @return node from its original location in grouping
916 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
917 SchemaNode result = findUsedGrouping(parentUsesNode);
918 for (final QName node : targetPath.getPathFromRoot()) {
919 // FIXME: this dispatch is rather ugly, we probably want to refactor it a bit
920 if (result instanceof DataNodeContainer) {
921 final QName resultNode = node.withModule(result.getQName().getModule());
923 SchemaNode found = ((DataNodeContainer) result).getDataChildByName(resultNode);
925 if (result instanceof ActionNodeContainer) {
926 found = ((ActionNodeContainer) result).findAction(resultNode).orElse(null);
928 if (found == null && result instanceof NotificationNodeContainer) {
929 found = ((NotificationNodeContainer) result).findNotification(resultNode).orElse(null);
933 } else if (result instanceof ChoiceSchemaNode) {
934 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
935 } else if (result instanceof ActionDefinition) {
936 final ActionDefinition action = (ActionDefinition) result;
937 final QName resultNode = node.withModule(result.getQName().getModule());
939 final ContainerSchemaNode input = action.getInput();
940 final ContainerSchemaNode output = action.getOutput();
941 if (resultNode.equals(input.getQName())) {
943 } else if (resultNode.equals(output.getQName())) {
948 } else if (result != null) {
949 throw new IllegalStateException("Cannot handle " + result);
952 if (result == null) {
956 if (result instanceof DerivableSchemaNode) {
957 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
958 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
959 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
960 result = originalNode.get();
964 if (result instanceof DataSchemaNode) {
965 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
966 if (resultDataSchemaNode.isAddedByUses()) {
967 // The original node is required, but we have only the copy of
968 // the original node.
969 // Maybe this indicates a bug in Yang parser.
970 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
973 return resultDataSchemaNode;
976 throw new IllegalStateException(
977 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
982 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
983 * of augmented node with serial number as suffix.
985 * @param context current module
986 * @param augmentPackageName string with contains the package name to which the augment belongs
987 * @param basePackageName string with the package name to which the augmented node belongs
988 * @param targetTypeRef target type
989 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
990 * @return generated type builder for augment
992 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
993 final String augmentPackageName, final Type targetTypeRef,
994 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
995 Map<String, GeneratedTypeBuilder> augmentBuilders =
996 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
997 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
1000 if (augIdentifier != null) {
1001 augTypeName = BindingMapping.getClassName(augIdentifier);
1003 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1006 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
1007 JavaTypeName.create(augmentPackageName, augTypeName));
1009 augTypeBuilder.addImplementsType(DATA_OBJECT);
1010 defaultImplementedInterace(augTypeBuilder);
1012 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
1013 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
1014 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1016 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
1017 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1018 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1020 augmentBuilders.put(augTypeName, augTypeBuilder);
1022 if (!augSchema.getChildNodes().isEmpty()) {
1023 context.addTypeToAugmentation(augTypeBuilder, augSchema);
1026 context.addAugmentType(augTypeBuilder);
1027 return augTypeBuilder;
1030 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1031 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1032 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1036 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1037 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1038 final QName nodeType = unknownSchemaNode.getNodeType();
1039 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1040 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1041 return unknownSchemaNode.getNodeParameter();
1048 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1049 * consists from name of augmented node and serial number of its augmentation.
1051 * @param builders map of builders which were created in the package to which the augmentation belongs
1052 * @param genTypeName string with name of augmented node
1053 * @return string with unique name for augmentation builder
1055 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1057 if (builders != null) {
1058 while (builders.containsKey(genTypeName + index)) {
1062 return genTypeName + index;
1066 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1067 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1068 * already part of them).
1070 * @param module current module
1071 * @param parent generated type builder which represents any node. The subnodes of this node are added
1072 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1073 * container, choice.
1074 * @param childOf parent type
1075 * @param schemaNodes set of data schema nodes which are the children of the node for which
1076 * <code>typeBuilder</code> was created
1077 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1078 * child nodes) could be added to it.
1080 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1081 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
1082 if (schemaNodes != null && parent != null) {
1083 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1084 for (final DataSchemaNode schemaNode : schemaNodes) {
1085 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1086 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1094 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1097 * @param module current module
1098 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1099 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1100 * container, choice.
1101 * @param childOf parent type
1102 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1104 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1105 * The getter method could be added to it.
1107 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1108 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1109 final boolean inGrouping) {
1110 if (schemaNodes != null && typeBuilder != null) {
1111 final Type baseInterface = childOf(typeBuilder);
1112 for (final DataSchemaNode schemaNode : schemaNodes) {
1113 if (!schemaNode.isAugmenting()) {
1114 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1122 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1124 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1125 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1126 * @param childOf parent type
1127 * @param module current module
1129 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1130 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1131 if (node != null && typeBuilder != null) {
1132 if (node instanceof LeafSchemaNode) {
1133 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1134 } else if (node instanceof LeafListSchemaNode) {
1135 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1136 } else if (node instanceof ContainerSchemaNode) {
1137 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1138 } else if (node instanceof ListSchemaNode) {
1139 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1140 } else if (node instanceof ChoiceSchemaNode) {
1141 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1142 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1143 opaqueToGeneratedType(context, typeBuilder, node);
1145 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1146 typeBuilder.getFullyQualifiedName());
1152 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1153 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1154 * and names of all parents node.
1156 * @param context current module
1157 * @param basePackageName string with the module package name
1158 * @param parent parent type
1159 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1161 * @throws IllegalArgumentException
1163 * <li>if <code>basePackageName</code> is null</li>
1164 * <li>if <code>choiceNode</code> is null</li>
1167 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1168 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1169 if (!choiceNode.isAddedByUses()) {
1170 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(context,
1171 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1172 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1173 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1174 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1175 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1177 final GeneratedType choiceType = choiceTypeBuilder.build();
1178 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1180 constructGetter(parent, choiceType, choiceNode);
1184 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1185 final DataSchemaNode anyNode) {
1186 if (!anyNode.isAddedByUses()) {
1187 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(context,
1188 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1189 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1190 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1191 defaultImplementedInterace(anyxmlTypeBuilder);
1192 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1193 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1195 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1200 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1201 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1202 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1203 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1205 * @param context current module context
1206 * @param refChoiceType type which represents superior <i>case</i>
1207 * @param choiceNode choice case node which is mapped to generated type
1208 * @throws IllegalArgumentException
1210 * <li>if <code>refChoiceType</code> equals null</li>
1211 * <li>if <code>caseNodes</code> equals null</li>
1214 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1215 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1216 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1217 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1219 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1220 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1221 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1222 caseTypeBuilder.addImplementsType(refChoiceType);
1223 defaultImplementedInterace(caseTypeBuilder);
1224 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1225 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1226 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1227 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1228 if (caseChildNodes != null) {
1229 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1231 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1232 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1234 if (parent instanceof AugmentationSchemaNode) {
1235 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1236 final SchemaPath targetPath = augSchema.getTargetPath();
1237 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1238 if (targetSchemaNode instanceof DataSchemaNode
1239 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1240 if (targetSchemaNode instanceof DerivableSchemaNode) {
1241 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1244 if (targetSchemaNode == null) {
1245 throw new IllegalStateException(
1246 "Failed to find target node from grouping for augmentation " + augSchema
1247 + " in module " + context.module().getName());
1250 parent = targetSchemaNode;
1253 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1254 Type childOfType = findChildNodeByPath(parent.getPath());
1255 if (childOfType == null) {
1256 childOfType = findGroupingByPath(parent.getPath());
1258 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1260 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1265 processUsesAugments(caseNode, context, inGrouping);
1270 * Generates list of generated types for all the cases of a choice which are added to the choice through
1273 * @param module current module
1274 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1275 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1276 * of the augmenting choice will belong to pcg2.
1277 * @param targetType Type which represents target choice
1278 * @param targetNode node which represents target choice
1279 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1281 * @throws IllegalArgumentException
1283 * <li>if <code>basePackageName</code> is null</li>
1284 * <li>if <code>targetType</code> is null</li>
1285 * <li>if <code>augmentedNodes</code> is null</li>
1288 // FIXME: nullness rules need to untangled in this method
1289 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1290 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1291 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1292 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1293 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1294 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1296 for (final DataSchemaNode caseNode : augmentedNodes) {
1297 if (caseNode != null) {
1298 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1299 caseTypeBuilder.addImplementsType(targetType);
1300 defaultImplementedInterace(caseTypeBuilder);
1302 CaseSchemaNode node = null;
1303 final String caseLocalName = caseNode.getQName().getLocalName();
1304 if (caseNode instanceof CaseSchemaNode) {
1305 node = (CaseSchemaNode) caseNode;
1306 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1307 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1308 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1309 if (dataSchemaNode instanceof ChoiceSchemaNode
1310 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1311 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1316 node = findNamedCase(targetNode, caseLocalName);
1318 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1319 if (childNodes != null) {
1320 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1323 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1324 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1329 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1330 final SchemaPath nodePath = targetNode.getPath();
1331 final SchemaPath parentSp = nodePath.getParent();
1332 if (parentSp.getParent() == null) {
1333 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1336 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1337 GeneratedTypeBuilder childOfType = null;
1338 if (parent instanceof CaseSchemaNode) {
1339 childOfType = findCaseByPath(parent.getPath());
1340 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1341 childOfType = findChildNodeByPath(parent.getPath());
1342 } else if (parent instanceof GroupingDefinition) {
1343 childOfType = findGroupingByPath(parent.getPath());
1346 if (childOfType == null) {
1347 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1353 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1354 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1355 return cases.isEmpty() ? null : cases.get(0);
1358 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1359 // New parser with encapsulated type
1360 if (leaf.getPath().equals(type.getPath())) {
1364 // Embedded type definition with new parser. Also takes care of the old parser with bits
1365 if (leaf.getPath().equals(type.getPath().getParent())) {
1372 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1373 final List<PatternConstraint> patternConstraints) {
1374 if (!patternConstraints.isEmpty()) {
1375 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1376 .append(BindingMapping.getPropertyName(leafName));
1377 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1378 typeProvider.resolveRegExpressions(patternConstraints));
1383 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1385 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1386 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1387 * @param module Module in which type was defined
1388 * @return boolean value
1390 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1392 * <li>true - in other cases</li>
1395 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1396 final ModuleContext context, final boolean inGrouping) {
1397 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1401 final Module parentModule = findParentModule(schemaContext, leaf);
1402 Type returnType = null;
1404 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1405 if (isInnerType(leaf, typeDef)) {
1406 if (typeDef instanceof EnumTypeDefinition) {
1407 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1408 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(), typeBuilder, context);
1409 typeProvider.putReferencedType(leaf.getPath(), returnType);
1410 } else if (typeDef instanceof UnionTypeDefinition) {
1411 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1412 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1413 // Store the inner type within the union so that we can find the reference for it
1414 context.addInnerTypedefType(typeDef.getPath(), returnType);
1415 } else if (typeDef instanceof BitsTypeDefinition) {
1416 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1418 if (genTOBuilder != null) {
1419 returnType = genTOBuilder.build();
1422 // It is constrained version of already declared type (inner declared type exists,
1423 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1424 // In order to get proper class we need to look up closest derived type
1425 // and apply restrictions from leaf type
1426 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1427 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1428 restrictions, inGrouping);
1429 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1432 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1433 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1434 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1437 if (returnType == null) {
1441 if (typeDef instanceof EnumTypeDefinition) {
1442 typeProvider.putReferencedType(leaf.getPath(), returnType);
1445 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1446 processContextRefExtension(leaf, getter, parentModule);
1450 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1451 // Returns DerivedType in case of new parser.
1452 final TypeDefinition<?> baseType = typeDef.getBaseType();
1453 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1456 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1457 final Module module) {
1458 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1459 final QName nodeType = node.getNodeType();
1460 if ("context-reference".equals(nodeType.getLocalName())) {
1461 final String nodeParam = node.getNodeParameter();
1462 IdentitySchemaNode identity = null;
1463 String basePackageName = null;
1464 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1465 final Iterator<String> iterator = splittedElement.iterator();
1466 final int length = Iterables.size(splittedElement);
1468 identity = findIdentityByName(module.getIdentities(), iterator.next());
1469 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1470 } else if (length == 2) {
1471 final String prefix = iterator.next();
1472 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1473 if (dependentModule == null) {
1474 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1477 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1478 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1480 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1483 if (identity == null) {
1484 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1488 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1489 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1490 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1491 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1496 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1497 for (final IdentitySchemaNode id : identities) {
1498 if (id.getQName().getLocalName().equals(name)) {
1505 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1506 for (final ModuleImport imp : imports) {
1507 if (imp.getPrefix().equals(prefix)) {
1508 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1514 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1515 final boolean isReadOnly) {
1516 if (leaf != null && toBuilder != null) {
1518 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1519 if (typeDef instanceof UnionTypeDefinition) {
1520 // GeneratedType for this type definition should have be already created
1521 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1522 returnType = mc.getTypedefs().get(typeDef.getPath());
1523 if (returnType == null) {
1524 // This may still be an inner type, try to find it
1525 returnType = mc.getInnerType(typeDef.getPath());
1527 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1528 // Annonymous enumeration (already generated, since it is inherited via uses).
1529 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1530 QName qname = originalLeaf.getQName();
1531 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1533 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1535 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1541 * Converts <code>leaf</code> schema node to property of generated TO builder.
1543 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1544 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1545 * @param returnType property type
1546 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1547 * @return boolean value
1549 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1550 * name equals null or if leaf is added by <i>uses</i>.</li>
1551 * <li>true - other cases</li>
1554 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1555 final Type returnType, final boolean isReadOnly) {
1556 if (returnType == null) {
1559 final String leafName = leaf.getQName().getLocalName();
1560 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1561 propBuilder.setReadOnly(isReadOnly);
1562 propBuilder.setReturnType(returnType);
1563 addComment(propBuilder, leaf);
1565 toBuilder.addEqualsIdentity(propBuilder);
1566 toBuilder.addHashIdentity(propBuilder);
1567 toBuilder.addToStringProperty(propBuilder);
1572 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1574 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1575 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1576 * @param module module
1577 * @return boolean value
1579 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1580 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1581 * <li>false - other cases</li>
1584 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1585 final ModuleContext context, final boolean inGrouping) {
1586 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1590 final QName nodeName = node.getQName();
1592 final TypeDefinition<?> typeDef = node.getType();
1593 final Module parentModule = findParentModule(schemaContext, node);
1595 Type returnType = null;
1596 if (typeDef.getBaseType() == null) {
1597 if (typeDef instanceof EnumTypeDefinition) {
1598 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1599 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName, typeBuilder, context);
1600 typeProvider.putReferencedType(node.getPath(), returnType);
1601 } else if (typeDef instanceof UnionTypeDefinition) {
1602 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1603 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1604 } else if (typeDef instanceof BitsTypeDefinition) {
1605 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1606 node, parentModule);
1607 returnType = genTOBuilder.build();
1609 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1610 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1611 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1614 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1615 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1616 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1619 constructGetter(typeBuilder, listTypeFor(returnType), node);
1623 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1624 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1625 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1626 returnTypeBuilder.setIsUnion(true);
1627 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1628 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1629 returnTypeBuilder.setModuleName(parentModule.getName());
1630 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1632 genTOBuilder.setTypedef(true);
1633 genTOBuilder.setIsUnion(true);
1634 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1636 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1640 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1641 final GeneratedTransferObject returnType, final Module parentModule) {
1642 // Append enclosing path hierarchy without dots
1643 final StringBuilder sb = new StringBuilder();
1644 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1645 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1646 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1647 unionBuilder.setIsUnionBuilder(true);
1649 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1650 method.setReturnType(returnType);
1651 method.addParameter(STRING, "defaultValue");
1652 method.setAccessModifier(AccessModifier.PUBLIC);
1653 method.setStatic(true);
1655 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1656 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1659 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1660 final SchemaNode schemaNode) {
1661 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1664 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1665 final SchemaNode schemaNode, final Type baseInterface) {
1666 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1667 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1671 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1672 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1673 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1674 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1675 * If <code>schemaNode</code> is instance of
1676 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1677 * which are specified in <i>uses</i>.
1679 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1680 * @param schemaNode schema node for which is created generated type builder
1681 * @param parent parent type (can be null)
1682 * @return generated type builder <code>schemaNode</code>
1684 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1685 final Type baseInterface, final ModuleContext context) {
1686 JavaTypeName name = renames.get(schemaNode);
1688 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1691 final GeneratedTypeBuilder it = addRawInterfaceDefinition(context, name, schemaNode);
1692 it.addImplementsType(baseInterface);
1693 if (!(schemaNode instanceof GroupingDefinition)) {
1694 it.addImplementsType(augmentable(it));
1696 if (schemaNode instanceof DataNodeContainer) {
1697 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1698 groupingsToGenTypes(context, containerSchema.getGroupings());
1699 addImplementedInterfaceFromUses(containerSchema, it);
1706 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1707 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1708 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1710 * @param packageName string with the package name to which returning generated type builder belongs
1711 * @param schemaNode schema node which provide data about the schema node name
1712 * @param prefix return type name prefix
1713 * @return generated type builder for <code>schemaNode</code>
1714 * @throws IllegalArgumentException
1716 * <li>if <code>schemaNode</code> is null</li>
1717 * <li>if <code>packageName</code> is null</li>
1718 * <li>if QName of schema node is null</li>
1719 * <li>if schemaNode name is null</li>
1722 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final JavaTypeName identifier,
1723 final SchemaNode schemaNode) {
1724 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1725 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1726 final String schemaNodeName = schemaNode.getQName().getLocalName();
1727 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1729 // FIXME: Validation of name conflict
1730 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1731 qnameConstant(newType, context.moduleInfoType(), schemaNode.getQName().getLocalName());
1733 final Module module = context.module();
1734 addCodegenInformation(newType, module, schemaNode);
1735 newType.setSchemaPath(schemaNode.getPath());
1736 newType.setModuleName(module.getName());
1738 final String packageName = identifier.packageName();
1739 final String simpleName = identifier.simpleName();
1740 if (!genTypeBuilders.containsKey(packageName)) {
1741 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1742 builders.put(simpleName, newType);
1743 genTypeBuilders.put(packageName, builders);
1745 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1746 if (!builders.containsKey(simpleName)) {
1747 builders.put(simpleName, newType);
1754 * Creates the name of the getter method name from <code>localName</code>.
1756 * @param localName string with the name of the getter method
1757 * @param returnType return type
1758 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1760 public static String getterMethodName(final String localName, final Type returnType) {
1761 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1765 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1766 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1767 * and <code>returnType</code> information are added to the builder.
1769 * @param interfaceBuilder generated type builder for which the getter method should be created
1770 * @param returnType type which represents the return type of the getter method
1771 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1772 * @param comment string with comment for the getter method
1773 * @param status status from yang file, for deprecated annotation
1774 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1776 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1777 final SchemaNode node) {
1778 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1779 getterMethodName(node.getQName().getLocalName(), returnType));
1780 getMethod.setReturnType(returnType);
1782 annotateDeprecatedIfNecessary(node, getMethod);
1783 addComment(getMethod, node);
1788 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1789 final ListSchemaNode node) {
1790 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1791 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1792 getMethod.setReturnType(returnType).setDefault(true);
1793 annotateDeprecatedIfNecessary(node, getMethod);
1797 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1800 * @param basePackageName string contains the module package name
1801 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1802 * or as a property to <code>genTOBuilder</code> if is part of the list key
1803 * @param typeBuilder generated type builder for the list schema node
1804 * @param genTOBuilder generated TO builder for the list keys
1805 * @param listKeys list of string which contains names of the list keys
1806 * @param module current module
1807 * @throws IllegalArgumentException
1809 * <li>if <code>schemaNode</code> equals null</li>
1810 * <li>if <code>typeBuilder</code> equals null</li>
1813 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1814 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1815 final List<String> listKeys, final boolean inGrouping) {
1816 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1817 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1819 if (schemaNode instanceof LeafSchemaNode) {
1820 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1821 final String leafName = leaf.getQName().getLocalName();
1822 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1823 if (listKeys.contains(leafName)) {
1825 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1827 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1830 } else if (!schemaNode.isAddedByUses()) {
1831 if (schemaNode instanceof LeafListSchemaNode) {
1832 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1833 } else if (schemaNode instanceof ContainerSchemaNode) {
1834 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1835 (ContainerSchemaNode) schemaNode, inGrouping);
1836 } else if (schemaNode instanceof ChoiceSchemaNode) {
1837 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1838 } else if (schemaNode instanceof ListSchemaNode) {
1839 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1840 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1841 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1846 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1847 final GeneratedTOBuilder genTOBuilder) {
1848 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1850 if (genTOBuilder != null) {
1851 final GeneratedTransferObject genTO = genTOBuilder.build();
1852 // Add Identifiable.getKey() for items
1853 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1854 .addAnnotation(OVERRIDE_ANNOTATION);
1855 context.addGeneratedTOBuilder(genTOBuilder);
1860 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1862 * @param list of string with names of the list keys
1863 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1864 * an empty list is returned.
1866 private static List<String> listKeys(final ListSchemaNode list) {
1867 final List<QName> keyDefinition = list.getKeyDefinition();
1868 switch (keyDefinition.size()) {
1870 return Collections.emptyList();
1872 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1874 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1875 for (final QName keyDef : keyDefinition) {
1876 listKeys.add(keyDef.getLocalName());
1883 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1884 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1885 * enclosing transfer objects.
1887 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1888 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1889 * @param leaf string with name for generated TO builder
1890 * @param parentModule parent module
1891 * @return generated TO builder for <code>typeDef</code>
1893 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1894 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1895 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1896 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1898 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1899 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1900 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1901 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1902 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1904 for (GeneratedTOBuilder builder : types) {
1905 if (builder.isUnion()) {
1906 final GeneratedTransferObject type = builder.build();
1907 createUnionBuilder(builder, typeBuilder, type, parentModule);
1911 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1915 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1916 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1917 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1920 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1921 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1922 * @param leaf string with name for generated TO builder
1923 * @param parentModule parent module
1924 * @return generated TO builder for <code>typeDef</code>
1926 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1927 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1928 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1929 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1930 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1931 return genTOBuilder;
1935 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1936 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1937 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1938 * to <code>builder</code>
1940 * @param dataNodeContainer element which contains the list of used YANG groupings
1941 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1942 * @return generated type builder with all implemented types
1944 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1945 final GeneratedTypeBuilder builder) {
1946 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1947 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1948 if (genType == null) {
1949 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + " is not resolved for "
1950 + builder.getFullyQualifiedName());
1953 builder.addImplementsType(genType.build());
1958 private JavaTypeName findAliasByPath(final SchemaPath path) {
1959 for (final ModuleContext ctx : genCtx.values()) {
1960 final JavaTypeName result = ctx.getAlias(path);
1961 if (result != null) {
1968 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1969 for (final ModuleContext ctx : genCtx.values()) {
1970 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1971 if (result != null) {
1978 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1979 for (final ModuleContext ctx : genCtx.values()) {
1980 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1981 if (result != null) {
1988 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1989 for (final ModuleContext ctx : genCtx.values()) {
1990 final GeneratedTypeBuilder result = ctx.getCase(path);
1991 if (result != null) {
1998 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
1999 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
2000 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
2003 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
2004 switch (node.getStatus()) {
2006 // FIXME: we really want to use a pre-made annotation
2007 builder.addAnnotation(DEPRECATED_ANNOTATION);
2010 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
2016 throw new IllegalStateException("Unhandled status in " + node);
2020 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2021 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2024 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2025 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
2029 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2030 final Type classType) {
2031 final MethodSignatureBuilder ret = typeBuilder
2032 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2033 .setAccessModifier(AccessModifier.PUBLIC)
2034 .setReturnType(classType(classType));
2035 ret.addAnnotation(OVERRIDE_ANNOTATION);