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.generator.util.BaseYangTypes;
68 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
69 import org.opendaylight.mdsal.binding.model.api.Constant;
70 import org.opendaylight.mdsal.binding.model.api.DefaultType;
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.ParameterizedType;
75 import org.opendaylight.mdsal.binding.model.api.Restrictions;
76 import org.opendaylight.mdsal.binding.model.api.Type;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
83 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
84 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
85 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
86 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
87 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
88 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
89 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
90 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
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.stmt.SchemaNodeIdentifier;
124 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
125 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
126 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
127 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
128 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
129 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
130 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
131 import org.slf4j.Logger;
132 import org.slf4j.LoggerFactory;
134 abstract class AbstractTypeGenerator {
135 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
136 private static final Splitter COLON_SPLITTER = Splitter.on(':');
137 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
138 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
139 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
142 * Comparator based on augment target path.
144 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
145 final Iterator<QName> thisIt = o1.getTargetPath().getNodeIdentifiers().iterator();
146 final Iterator<QName> otherIt = o2.getTargetPath().getNodeIdentifiers().iterator();
148 while (thisIt.hasNext()) {
149 if (!otherIt.hasNext()) {
153 final int comp = thisIt.next().compareTo(otherIt.next());
159 return otherIt.hasNext() ? -1 : 0;
163 * Constant with the concrete name of identifier.
165 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
168 * Constant with the concrete name of namespace.
170 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
172 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
175 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
176 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
177 * for schema node specified in key part.
179 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
182 * Provide methods for converting YANG types to JAVA types.
184 private final AbstractTypeProvider typeProvider;
187 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
189 private final @NonNull SchemaContext schemaContext;
192 * Holds renamed elements.
194 private final Map<SchemaNode, JavaTypeName> renames;
196 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
197 final Map<SchemaNode, JavaTypeName> renames) {
198 this.schemaContext = requireNonNull(context);
199 this.typeProvider = requireNonNull(typeProvider);
200 this.renames = requireNonNull(renames);
202 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
203 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
204 for (final Module contextModule : contextModules) {
205 contexts.add(moduleToGenTypes(contextModule));
208 contexts.forEach(this::allAugmentsToGenTypes);
211 final @NonNull SchemaContext schemaContext() {
212 return schemaContext;
215 final Collection<ModuleContext> moduleContexts() {
216 return genCtx.values();
219 final ModuleContext moduleContext(final QNameModule module) {
220 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
223 final AbstractTypeProvider typeProvider() {
227 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
229 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
231 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
232 Collection<? extends SchemaNode> nodes);
234 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
236 private ModuleContext moduleToGenTypes(final Module module) {
237 final ModuleContext context = new ModuleContext(module);
238 genCtx.put(module.getQNameModule(), context);
239 allTypeDefinitionsToGenTypes(context);
240 groupingsToGenTypes(context, module.getGroupings());
241 rpcMethodsToGenType(context);
242 allIdentitiesToGenTypes(context);
243 notificationsToGenType(context);
245 if (!module.getChildNodes().isEmpty()) {
246 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
247 context.addModuleNode(moduleType);
248 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
254 * Converts all extended type definitions of module to the list of
255 * <code>Type</code> objects.
258 * module from which is obtained set of type definitions
259 * @throws IllegalArgumentException
261 * <li>if module is null</li>
262 * <li>if name of module is null</li>
264 * @throws IllegalStateException
265 * if set of type definitions from module is null
267 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
268 final Module module = context.module();
269 checkArgument(module.getName() != null, "Module name cannot be NULL.");
271 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
272 if (typedef != null) {
273 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
275 context.addTypedefType(typedef, type);
276 context.addTypeToSchema(type,typedef);
282 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
283 final DataSchemaNode node, final boolean inGrouping) {
284 if (node.isAugmenting() || node.isAddedByUses()) {
287 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
288 defaultImplementedInterace(genType);
289 annotateDeprecatedIfNecessary(node, genType);
291 final Module module = context.module();
292 genType.setModuleName(module.getName());
293 addCodegenInformation(genType, module, node);
294 genType.setSchemaPath(node.getPath());
295 if (node instanceof DataNodeContainer) {
296 context.addChildNodeType(node, genType);
297 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
298 processUsesAugments((DataNodeContainer) node, context, inGrouping);
303 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
304 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
305 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
306 if (genType != null) {
307 constructGetter(parent, genType, node);
308 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
309 actionsToGenType(context, genType, node, null, inGrouping);
310 notificationsToGenType(context, genType, node, null, inGrouping);
314 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
315 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
316 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
317 if (genType != null) {
318 final List<String> listKeys = listKeys(node);
319 final GeneratedTOBuilder keyTypeBuilder;
320 if (!listKeys.isEmpty()) {
321 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
322 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
323 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
324 .addImplementsType(identifier(genType));
325 genType.addImplementsType(identifiable(keyTypeBuilder));
327 keyTypeBuilder = null;
330 // Decide whether to generate a List or a Map
331 final ParameterizedType listType;
332 if (keyTypeBuilder != null && !node.isUserOrdered()) {
333 listType = mapTypeFor(keyTypeBuilder, genType);
335 listType = listTypeFor(genType);
338 constructGetter(parent, listType, node);
339 constructNonnull(parent, listType, node);
341 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
342 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
344 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
345 if (!schemaNode.isAugmenting()) {
346 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
351 if (keyTypeBuilder != null) {
352 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
353 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
354 keyTypeBuilder.setSUID(prop);
357 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
361 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
362 final boolean inGrouping) {
363 for (final UsesNode usesNode : node.getUses()) {
364 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
365 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
366 processUsesAugments(augment, context, inGrouping);
372 * Converts all <b>augmentation</b> of the module to the list
373 * <code>Type</code> objects.
376 * module from which is obtained list of all augmentation objects
377 * to iterate over them
378 * @throws IllegalArgumentException
380 * <li>if the module is null</li>
381 * <li>if the name of module is null</li>
383 * @throws IllegalStateException
384 * if set of augmentations from module is null
386 private void allAugmentsToGenTypes(final ModuleContext context) {
387 final Module module = context.module();
388 checkArgument(module != null, "Module reference cannot be NULL.");
389 checkArgument(module.getName() != null, "Module name cannot be NULL.");
390 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
392 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
393 augmentationToGenTypes(context, augment);
398 * Returns list of <code>AugmentationSchema</code> objects. The objects are
399 * sorted according to the length of their target path from the shortest to
403 * module from which is obtained list of all augmentation objects
404 * @return list of sorted <code>AugmentationSchema</code> objects obtained
405 * from <code>module</code>
406 * @throws IllegalArgumentException
408 * @throws IllegalStateException
409 * if set of module augmentations is null
411 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
412 checkArgument(module != null, "Module reference cannot be NULL.");
413 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
415 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(module.getAugmentations());
416 sortedAugmentations.sort(AUGMENT_COMP);
418 return sortedAugmentations;
422 * Create GeneratedTypeBuilder object from module argument.
425 * Module object from which builder will be created
426 * @return <code>GeneratedTypeBuilder</code> which is internal
427 * representation of the module
428 * @throws IllegalArgumentException
431 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
432 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
433 final Module module = context.module();
434 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
435 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
437 addCodegenInformation(moduleDataTypeBuilder, module);
438 return moduleDataTypeBuilder;
441 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
442 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
443 for (final ActionDefinition action : parentSchema.getActions()) {
444 if (action.isAugmenting()) {
448 final GeneratedType input;
449 final GeneratedType output;
450 if (action.isAddedByUses()) {
451 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
452 input = context.getChildNode(orig.getInput().getPath()).build();
453 output = context.getChildNode(orig.getOutput().getPath()).build();
455 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
456 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
459 if (!(parentSchema instanceof GroupingDefinition)) {
460 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
461 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
462 // and do not capture an actual instantiation.
463 final QName qname = action.getQName();
464 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
465 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
466 BindingMapping.getClassName(qname)));
467 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
468 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
470 annotateDeprecatedIfNecessary(action, builder);
471 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
472 : action(parent, input, output));
474 addCodegenInformation(builder, context.module(), action);
475 context.addChildNodeType(action, builder);
480 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
481 for (UsesNode uses : parent.getUses()) {
482 final GroupingDefinition grp = uses.getSourceGrouping();
483 final Optional<ActionDefinition> found = grp.findAction(action.getQName());
484 if (found.isPresent()) {
485 final ActionDefinition result = found.get();
486 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
490 return Optional.empty();
493 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
494 final ContainerSchemaNode schema, final boolean inGrouping) {
495 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
496 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
497 return genType.build();
501 * Converts all <b>RPCs</b> input and output substatements of the module
502 * to the list of <code>Type</code> objects. In addition are to containers
503 * and lists which belong to input or output also part of returning list.
506 * module from which is obtained set of all rpc objects to
508 * @throws IllegalArgumentException
510 * <li>if the module is null</li>
511 * <li>if the name of module is null</li>
513 * @throws IllegalStateException
514 * if set of rpcs from module is null
516 private void rpcMethodsToGenType(final ModuleContext context) {
517 final Module module = context.module();
518 checkArgument(module.getName() != null, "Module name cannot be NULL.");
519 final Collection<? extends RpcDefinition> rpcDefinitions = module.getRpcs();
520 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
521 if (rpcDefinitions.isEmpty()) {
525 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
526 interfaceBuilder.addImplementsType(RPC_SERVICE);
528 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
530 for (final RpcDefinition rpc : rpcDefinitions) {
532 final String rpcName = BindingMapping.getClassName(rpc.getQName());
533 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
534 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
536 // Do not refer to annotation class, as it may not be available at runtime
537 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
538 addComment(method, rpc);
540 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
541 method.setReturnType(listenableFutureTypeFor(
542 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
546 context.addTopLevelNodeType(interfaceBuilder);
549 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
550 final ContainerSchemaNode schema, final Type type) {
551 processUsesAugments(schema, context, false);
552 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
553 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
555 addImplementedInterfaceFromUses(schema, outType);
556 outType.addImplementsType(type);
557 outType.addImplementsType(augmentable(outType));
558 defaultImplementedInterace(outType);
559 annotateDeprecatedIfNecessary(rpc, outType);
560 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
561 context.addChildNodeType(schema, outType);
562 return outType.build();
566 * Converts all <b>notifications</b> of the module to the list of
567 * <code>Type</code> objects. In addition are to this list added containers
568 * and lists which are part of this notification.
571 * module from which is obtained set of all notification objects
572 * to iterate over them
573 * @throws IllegalArgumentException
575 * <li>if the module equals null</li>
576 * <li>if the name of module equals null</li>
578 * @throws IllegalStateException
579 * if set of notifications from module is null
581 private void notificationsToGenType(final ModuleContext context) {
582 final Module module = context.module();
583 checkArgument(module.getName() != null, "Module name cannot be NULL.");
584 final Collection<? extends NotificationDefinition> notifications = module.getNotifications();
585 if (notifications.isEmpty()) {
589 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
590 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
592 for (final NotificationDefinition notification : notifications) {
593 if (notification != null) {
594 processUsesAugments(notification, context, false);
596 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
597 context.modulePackageName(), notification, DATA_OBJECT, context);
598 defaultImplementedInterace(notificationInterface);
599 annotateDeprecatedIfNecessary(notification, notificationInterface);
600 notificationInterface.addImplementsType(NOTIFICATION);
601 context.addChildNodeType(notification, notificationInterface);
603 // Notification object
604 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
605 notification.getChildNodes(), false);
607 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
608 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
609 .setReturnType(primitiveVoidType()), notification);
613 addCodegenInformation(listenerInterface, module, "notifications", notifications);
614 context.addTopLevelNodeType(listenerInterface);
617 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
618 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
619 final boolean inGrouping) {
620 final Collection<? extends NotificationDefinition> notifications = parentSchema.getNotifications();
621 if (notifications.isEmpty()) {
625 for (NotificationDefinition notif : notifications) {
626 if (notif.isAugmenting()) {
629 if (parentSchema instanceof GroupingDefinition) {
630 // Notifications cannot be really established, as they lack instantiation context, which would be
631 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
635 processUsesAugments(notif, context, false);
637 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
638 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
639 defaultImplementedInterace(notifInterface);
640 annotateDeprecatedIfNecessary(notif, notifInterface);
642 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
643 : instanceNotification(notifInterface, parent));
644 context.addChildNodeType(notif, notifInterface);
646 // Notification object
647 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
652 * Converts all <b>identities</b> of the module to the list of
653 * <code>Type</code> objects.
656 * module from which is obtained set of all identity objects to
658 * @param schemaContext
659 * schema context only used as input parameter for method
660 * {@link BindingGeneratorImpl#identityToGenType}
663 private void allIdentitiesToGenTypes(final ModuleContext context) {
664 final Collection<? extends IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
666 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
667 for (final IdentitySchemaNode identity : schemaIdentities) {
668 identityToGenType(context, identity);
674 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
675 * created transport object builder. If identity contains base identity then
676 * reference to base identity is added to superior identity as its extend.
677 * If identity doesn't contain base identity then only reference to abstract
678 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
679 * BaseIdentity} is added
683 * @param basePackageName
684 * string contains the module package name
686 * IdentitySchemaNode which contains data about identity
688 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
689 if (identity == null) {
693 JavaTypeName name = renames.get(identity);
695 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
696 BindingMapping.getClassName(identity.getQName()));
699 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
700 final Collection<? extends IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
701 if (!baseIdentities.isEmpty()) {
702 for (IdentitySchemaNode baseIdentity : baseIdentities) {
703 JavaTypeName base = renames.get(baseIdentity);
705 final QName qname = baseIdentity.getQName();
706 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
707 BindingMapping.getClassName(qname));
710 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
711 newType.addImplementsType(gto);
714 newType.addImplementsType(BASE_IDENTITY);
717 final Module module = context.module();
718 addCodegenInformation(newType, module, identity);
719 newType.setModuleName(module.getName());
720 newType.setSchemaPath(identity.getPath());
722 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
723 identity.getQName().getLocalName());
725 context.addIdentityType(identity, newType);
728 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
729 final JavaTypeName yangModuleInfo, final String localName) {
730 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
731 new SimpleImmutableEntry<>(yangModuleInfo, localName));
735 * Converts all <b>groupings</b> of the module to the list of
736 * <code>Type</code> objects. Firstly are groupings sorted according mutual
737 * dependencies. At least dependent (independent) groupings are in the list
738 * saved at first positions. For every grouping the record is added to map
739 * {@link ModuleContext#groupings allGroupings}
744 * collection of groupings from which types will be generated
747 private void groupingsToGenTypes(final ModuleContext context,
748 final Collection<? extends GroupingDefinition> groupings) {
749 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
750 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
751 // node of grouping is resolved to the method.
752 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
753 narrowImplementedInterface(genType);
754 annotateDeprecatedIfNecessary(grouping, genType);
755 context.addGroupingType(grouping, genType);
756 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
757 groupingsToGenTypes(context, grouping.getGroupings());
758 processUsesAugments(grouping, context, true);
759 actionsToGenType(context, genType, grouping, null, true);
760 notificationsToGenType(context, genType, grouping, null, true);
765 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
766 * <code>enumTypeDef</code> item is added to builder with its name and value.
768 * @param enumTypeDef EnumTypeDefinition contains enum data
769 * @param enumName string contains name which will be assigned to enumeration builder
770 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
771 * @param module Module in which type should be generated
772 * @return enumeration builder which contains data from <code>enumTypeDef</code>
774 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
775 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
776 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
777 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
778 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
779 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
780 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
787 * Generates type builder for <code>module</code>.
789 * @param module Module which is source of package name for generated type builder
790 * @param postfix string which is added to the module class name representation as suffix
791 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
792 * @throws IllegalArgumentException if <code>module</code> is null
794 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
795 final Module module = context.module();
796 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
797 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
798 JavaTypeName.create(context.modulePackageName(), moduleName));
800 moduleBuilder.setModuleName(moduleName);
801 addCodegenInformation(moduleBuilder, module);
802 return moduleBuilder;
806 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
807 * In addition there are also generated types for all containers, list and choices which are child of
808 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
810 * @param augmentPackageName string with the name of the package to which the augmentation belongs
811 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
812 * @param module current module
813 * @throws IllegalArgumentException
815 * <li>if <code>augmentPackageName</code> equals null</li>
816 * <li>if <code>augSchema</code> equals null</li>
818 * @throws IllegalStateException
819 * if augment target path is null
821 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
822 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
823 checkState(augSchema.getTargetPath() != null,
824 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
826 processUsesAugments(augSchema, context, false);
827 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
828 SchemaNode targetSchemaNode = null;
830 // FIXME: can we use findDataSchemaNode() instead?
831 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath.getNodeIdentifiers());
832 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
833 if (targetSchemaNode instanceof DerivableSchemaNode) {
834 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
836 if (targetSchemaNode == null) {
837 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
838 + " in module " + context.module().getName());
841 if (targetSchemaNode == null) {
842 throw new IllegalArgumentException("augment target not found: " + targetPath);
845 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
846 if (targetTypeBuilder == null) {
847 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
849 if (targetTypeBuilder == null) {
850 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
853 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
854 addRawAugmentGenTypeDefinition(context, DefaultType.of(targetTypeBuilder), augSchema, false);
857 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
858 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
862 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
863 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
864 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
865 checkState(augSchema.getTargetPath() != null,
866 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
868 processUsesAugments(augSchema, context, inGrouping);
869 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
870 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
871 if (targetSchemaNode == null) {
872 throw new IllegalArgumentException("augment target not found: " + targetPath);
875 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
876 if (targetTypeBuilder == null) {
877 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
879 if (targetTypeBuilder == null) {
880 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
883 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
884 if (usesNodeParent instanceof SchemaNode) {
885 addRawAugmentGenTypeDefinition(context,
886 packageNameForAugmentedGeneratedType(context.modulePackageName(),
887 ((SchemaNode) usesNodeParent).getPath()),
888 targetTypeBuilder.build(), augSchema, inGrouping);
890 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
893 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
894 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
899 * Convenient method to find node added by uses statement.
901 * @param targetPath node path
902 * @param parentUsesNode parent of uses node
903 * @return node from its original location in grouping
905 private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaNodeIdentifier targetPath,
906 final UsesNode parentUsesNode) {
907 SchemaNode result = parentUsesNode.getSourceGrouping();
908 for (final QName node : targetPath.getNodeIdentifiers()) {
909 if (result instanceof DataNodeContainer) {
910 final QName resultNode = node.bindTo(result.getQName().getModule());
911 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
912 } else if (result instanceof ChoiceSchemaNode) {
913 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
916 if (result == null) {
920 if (result instanceof DerivableSchemaNode) {
921 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
922 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
923 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
924 result = originalNode.get();
928 if (result instanceof DataSchemaNode) {
929 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
930 if (resultDataSchemaNode.isAddedByUses()) {
931 // The original node is required, but we have only the copy of
932 // the original node.
933 // Maybe this indicates a bug in Yang parser.
934 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
937 return resultDataSchemaNode;
940 throw new IllegalStateException(
941 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
946 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
947 * of augmented node with serial number as suffix.
949 * @param context current module
950 * @param augmentPackageName string with contains the package name to which the augment belongs
951 * @param basePackageName string with the package name to which the augmented node belongs
952 * @param targetTypeRef target type
953 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
954 * @return generated type builder for augment
956 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
957 final String augmentPackageName, final Type targetTypeRef,
958 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
959 Map<String, GeneratedTypeBuilder> augmentBuilders =
960 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
961 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
964 if (augIdentifier != null) {
965 augTypeName = BindingMapping.getClassName(augIdentifier);
967 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
970 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
971 JavaTypeName.create(augmentPackageName, augTypeName));
973 augTypeBuilder.addImplementsType(DATA_OBJECT);
974 defaultImplementedInterace(augTypeBuilder);
976 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
977 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
978 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
980 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
981 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
982 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
984 augmentBuilders.put(augTypeName, augTypeBuilder);
986 if (!augSchema.getChildNodes().isEmpty()) {
987 context.addTypeToAugmentation(augTypeBuilder, augSchema);
990 context.addAugmentType(augTypeBuilder);
991 return augTypeBuilder;
994 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
995 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
996 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1000 private static String getAugmentIdentifier(final Collection<? extends UnknownSchemaNode> unknownSchemaNodes) {
1001 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1002 final QName nodeType = unknownSchemaNode.getNodeType();
1003 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1004 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1005 return unknownSchemaNode.getNodeParameter();
1012 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1013 * consists from name of augmented node and serial number of its augmentation.
1015 * @param builders map of builders which were created in the package to which the augmentation belongs
1016 * @param genTypeName string with name of augmented node
1017 * @return string with unique name for augmentation builder
1019 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1021 if (builders != null) {
1022 while (builders.containsKey(genTypeName + index)) {
1026 return genTypeName + index;
1030 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1031 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1032 * already part of them).
1034 * @param module current module
1035 * @param parent generated type builder which represents any node. The subnodes of this node are added
1036 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1037 * container, choice.
1038 * @param childOf parent type
1039 * @param schemaNodes set of data schema nodes which are the children of the node for which
1040 * <code>typeBuilder</code> was created
1041 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1042 * child nodes) could be added to it.
1044 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1045 final @Nullable Type childOf, final Iterable<? extends DataSchemaNode> schemaNodes,
1046 final boolean inGrouping) {
1047 if (schemaNodes != null && parent != null) {
1048 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1049 for (final DataSchemaNode schemaNode : schemaNodes) {
1050 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1051 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1059 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1062 * @param module current module
1063 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1064 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1065 * container, choice.
1066 * @param childOf parent type
1067 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1069 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1070 * The getter method could be added to it.
1072 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1073 final GeneratedTypeBuilder typeBuilder, final Iterable<? extends DataSchemaNode> schemaNodes,
1074 final boolean inGrouping) {
1075 if (schemaNodes != null && typeBuilder != null) {
1076 final Type baseInterface = childOf(typeBuilder);
1077 for (final DataSchemaNode schemaNode : schemaNodes) {
1078 if (!schemaNode.isAugmenting()) {
1079 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1087 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1089 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1090 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1091 * @param childOf parent type
1092 * @param module current module
1094 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1095 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1096 if (node != null && typeBuilder != null) {
1097 if (node instanceof LeafSchemaNode) {
1098 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1099 } else if (node instanceof LeafListSchemaNode) {
1100 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1101 } else if (node instanceof ContainerSchemaNode) {
1102 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1103 } else if (node instanceof ListSchemaNode) {
1104 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1105 } else if (node instanceof ChoiceSchemaNode) {
1106 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1107 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1108 opaqueToGeneratedType(context, typeBuilder, node);
1110 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1111 typeBuilder.getFullyQualifiedName());
1117 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1118 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1119 * and names of all parents node.
1121 * @param context current module
1122 * @param basePackageName string with the module package name
1123 * @param parent parent type
1124 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1126 * @throws IllegalArgumentException
1128 * <li>if <code>basePackageName</code> is null</li>
1129 * <li>if <code>choiceNode</code> is null</li>
1132 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1133 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1134 if (!choiceNode.isAddedByUses()) {
1135 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1136 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1137 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1138 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1139 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1140 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1142 final GeneratedType choiceType = choiceTypeBuilder.build();
1143 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1145 constructGetter(parent, choiceType, choiceNode);
1149 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1150 final DataSchemaNode anyNode) {
1151 if (!anyNode.isAddedByUses()) {
1152 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(
1153 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1154 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1155 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1156 defaultImplementedInterace(anyxmlTypeBuilder);
1157 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1158 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1160 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1165 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1166 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1167 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1168 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1170 * @param context current module context
1171 * @param refChoiceType type which represents superior <i>case</i>
1172 * @param choiceNode choice case node which is mapped to generated type
1173 * @throws IllegalArgumentException
1175 * <li>if <code>refChoiceType</code> equals null</li>
1176 * <li>if <code>caseNodes</code> equals null</li>
1179 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1180 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1181 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1182 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1184 for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
1185 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1186 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1187 caseTypeBuilder.addImplementsType(refChoiceType);
1188 defaultImplementedInterace(caseTypeBuilder);
1189 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1190 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1191 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1192 final Iterable<? extends DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1193 if (caseChildNodes != null) {
1194 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1196 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1197 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1199 if (parent instanceof AugmentationSchemaNode) {
1200 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1201 final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
1202 // FIXME: can we use findDataSchemaNode?
1203 SchemaNode targetSchemaNode = findNodeInSchemaContext(schemaContext,
1204 targetPath.getNodeIdentifiers());
1205 if (targetSchemaNode instanceof DataSchemaNode
1206 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1207 if (targetSchemaNode instanceof DerivableSchemaNode) {
1208 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1211 if (targetSchemaNode == null) {
1212 throw new IllegalStateException(
1213 "Failed to find target node from grouping for augmentation " + augSchema
1214 + " in module " + context.module().getName());
1217 parent = targetSchemaNode;
1220 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1221 Type childOfType = findChildNodeByPath(parent.getPath());
1222 if (childOfType == null) {
1223 childOfType = findGroupingByPath(parent.getPath());
1225 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1227 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1232 processUsesAugments(caseNode, context, inGrouping);
1237 * Generates list of generated types for all the cases of a choice which are added to the choice through
1240 * @param module current module
1241 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1242 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1243 * of the augmenting choice will belong to pcg2.
1244 * @param targetType Type which represents target choice
1245 * @param targetNode node which represents target choice
1246 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1248 * @throws IllegalArgumentException
1250 * <li>if <code>basePackageName</code> is null</li>
1251 * <li>if <code>targetType</code> is null</li>
1252 * <li>if <code>augmentedNodes</code> is null</li>
1255 // FIXME: nullness rules need to untangled in this method
1256 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1257 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1258 final Type targetType, final ChoiceSchemaNode targetNode,
1259 final Iterable<? extends DataSchemaNode> augmentedNodes,
1260 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1261 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1262 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1264 for (final DataSchemaNode caseNode : augmentedNodes) {
1265 if (caseNode != null) {
1266 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1267 caseTypeBuilder.addImplementsType(targetType);
1268 defaultImplementedInterace(caseTypeBuilder);
1270 CaseSchemaNode node = null;
1271 final String caseLocalName = caseNode.getQName().getLocalName();
1272 if (caseNode instanceof CaseSchemaNode) {
1273 node = (CaseSchemaNode) caseNode;
1274 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1275 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1276 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1277 if (dataSchemaNode instanceof ChoiceSchemaNode
1278 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1279 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1284 node = findNamedCase(targetNode, caseLocalName);
1286 final Iterable<? extends DataSchemaNode> childNodes = node.getChildNodes();
1287 if (childNodes != null) {
1288 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1291 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1292 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1297 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1298 final SchemaPath nodePath = targetNode.getPath();
1299 final SchemaPath parentSp = nodePath.getParent();
1300 if (parentSp.getParent() == null) {
1301 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1304 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1305 GeneratedTypeBuilder childOfType = null;
1306 if (parent instanceof CaseSchemaNode) {
1307 childOfType = findCaseByPath(parent.getPath());
1308 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1309 childOfType = findChildNodeByPath(parent.getPath());
1310 } else if (parent instanceof GroupingDefinition) {
1311 childOfType = findGroupingByPath(parent.getPath());
1314 if (childOfType == null) {
1315 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1321 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1322 final List<? extends CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1323 return cases.isEmpty() ? null : cases.get(0);
1326 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1327 // New parser with encapsulated type
1328 if (leaf.getPath().equals(type.getPath())) {
1332 // Embedded type definition with new parser. Also takes care of the old parser with bits
1333 if (leaf.getPath().equals(type.getPath().getParent())) {
1340 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1341 final List<PatternConstraint> patternConstraints) {
1342 if (!patternConstraints.isEmpty()) {
1343 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1344 .append(BindingMapping.getPropertyName(leafName));
1345 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1346 typeProvider.resolveRegExpressions(patternConstraints));
1351 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1353 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1354 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1355 * @param module Module in which type was defined
1356 * @return boolean value
1358 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1360 * <li>true - in other cases</li>
1363 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1364 final ModuleContext context, final boolean inGrouping) {
1365 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1369 final Module parentModule = findParentModule(schemaContext, leaf);
1370 Type returnType = null;
1372 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1373 if (isInnerType(leaf, typeDef)) {
1374 if (typeDef instanceof EnumTypeDefinition) {
1375 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1376 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1377 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1378 typeBuilder, context);
1379 if (enumBuilder != null) {
1380 returnType = enumBuilder.toInstance(typeBuilder);
1382 typeProvider.putReferencedType(leaf.getPath(), returnType);
1383 } else if (typeDef instanceof UnionTypeDefinition) {
1384 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1385 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1386 // Store the inner type within the union so that we can find the reference for it
1387 context.addInnerTypedefType(typeDef.getPath(), returnType);
1388 } else if (typeDef instanceof BitsTypeDefinition) {
1389 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1391 if (genTOBuilder != null) {
1392 returnType = genTOBuilder.build();
1395 // It is constrained version of already declared type (inner declared type exists,
1396 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1397 // In order to get proper class we need to look up closest derived type
1398 // and apply restrictions from leaf type
1399 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1400 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1401 restrictions, inGrouping);
1402 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1405 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1406 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1407 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1410 if (returnType == null) {
1414 if (typeDef instanceof EnumTypeDefinition) {
1415 typeProvider.putReferencedType(leaf.getPath(), returnType);
1418 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1419 processContextRefExtension(leaf, getter, parentModule);
1423 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1424 // Returns DerivedType in case of new parser.
1425 final TypeDefinition<?> baseType = typeDef.getBaseType();
1426 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1429 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1430 final Module module) {
1431 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1432 final QName nodeType = node.getNodeType();
1433 if ("context-reference".equals(nodeType.getLocalName())) {
1434 final String nodeParam = node.getNodeParameter();
1435 IdentitySchemaNode identity = null;
1436 String basePackageName = null;
1437 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1438 final Iterator<String> iterator = splittedElement.iterator();
1439 final int length = Iterables.size(splittedElement);
1441 identity = findIdentityByName(module.getIdentities(), iterator.next());
1442 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1443 } else if (length == 2) {
1444 final String prefix = iterator.next();
1445 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1446 if (dependentModule == null) {
1447 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1450 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1451 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1453 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1456 if (identity == null) {
1457 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1461 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1462 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1463 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1464 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1469 private static IdentitySchemaNode findIdentityByName(final Collection<? extends IdentitySchemaNode> identities,
1470 final String name) {
1471 for (final IdentitySchemaNode id : identities) {
1472 if (id.getQName().getLocalName().equals(name)) {
1479 private Module findModuleFromImports(final Collection<? extends ModuleImport> imports, final String prefix) {
1480 for (final ModuleImport imp : imports) {
1481 if (imp.getPrefix().equals(prefix)) {
1482 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1488 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1489 final boolean isReadOnly) {
1490 if (leaf != null && toBuilder != null) {
1492 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1493 if (typeDef instanceof UnionTypeDefinition) {
1494 // GeneratedType for this type definition should have be already created
1495 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1496 returnType = mc.getTypedefs().get(typeDef.getPath());
1497 if (returnType == null) {
1498 // This may still be an inner type, try to find it
1499 returnType = mc.getInnerType(typeDef.getPath());
1501 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1502 // Annonymous enumeration (already generated, since it is inherited via uses).
1503 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1504 QName qname = originalLeaf.getQName();
1505 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1507 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1509 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1515 * Converts <code>leaf</code> schema node to property of generated TO builder.
1517 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1518 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1519 * @param returnType property type
1520 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1521 * @return boolean value
1523 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1524 * name equals null or if leaf is added by <i>uses</i>.</li>
1525 * <li>true - other cases</li>
1528 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1529 final Type returnType, final boolean isReadOnly) {
1530 if (returnType == null) {
1533 final String leafName = leaf.getQName().getLocalName();
1534 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1535 propBuilder.setReadOnly(isReadOnly);
1536 propBuilder.setReturnType(returnType);
1537 addComment(propBuilder, leaf);
1539 toBuilder.addEqualsIdentity(propBuilder);
1540 toBuilder.addHashIdentity(propBuilder);
1541 toBuilder.addToStringProperty(propBuilder);
1546 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1548 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1549 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1550 * @param module module
1551 * @return boolean value
1553 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1554 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1555 * <li>false - other cases</li>
1558 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1559 final ModuleContext context, final boolean inGrouping) {
1560 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1564 final QName nodeName = node.getQName();
1566 final TypeDefinition<?> typeDef = node.getType();
1567 final Module parentModule = findParentModule(schemaContext, node);
1569 Type returnType = null;
1570 if (typeDef.getBaseType() == null) {
1571 if (typeDef instanceof EnumTypeDefinition) {
1572 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1573 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1574 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1575 typeBuilder, context);
1576 returnType = DefaultType.of(enumBuilder);
1577 typeProvider.putReferencedType(node.getPath(), returnType);
1578 } else if (typeDef instanceof UnionTypeDefinition) {
1579 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1580 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1581 } else if (typeDef instanceof BitsTypeDefinition) {
1582 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1583 node, parentModule);
1584 returnType = genTOBuilder.build();
1586 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1587 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1588 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1591 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1592 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1593 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1596 constructGetter(typeBuilder, listTypeFor(returnType), node);
1600 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1601 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1602 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1603 returnTypeBuilder.setIsUnion(true);
1604 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1605 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1606 returnTypeBuilder.setModuleName(parentModule.getName());
1607 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1609 genTOBuilder.setTypedef(true);
1610 genTOBuilder.setIsUnion(true);
1611 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1613 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1617 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1618 final GeneratedTransferObject returnType, final Module parentModule) {
1619 // Append enclosing path hierarchy without dots
1620 final StringBuilder sb = new StringBuilder();
1621 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1622 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1623 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1624 unionBuilder.setIsUnionBuilder(true);
1626 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1627 method.setReturnType(returnType);
1628 method.addParameter(STRING, "defaultValue");
1629 method.setAccessModifier(AccessModifier.PUBLIC);
1630 method.setStatic(true);
1632 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1633 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1636 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1637 final SchemaNode schemaNode) {
1638 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1641 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1642 final SchemaNode schemaNode, final Type baseInterface) {
1643 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1644 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1648 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1649 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1650 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1651 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1652 * If <code>schemaNode</code> is instance of
1653 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1654 * which are specified in <i>uses</i>.
1656 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1657 * @param schemaNode schema node for which is created generated type builder
1658 * @param parent parent type (can be null)
1659 * @return generated type builder <code>schemaNode</code>
1661 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1662 final Type baseInterface, final ModuleContext context) {
1663 JavaTypeName name = renames.get(schemaNode);
1665 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1668 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1669 it.addImplementsType(baseInterface);
1670 if (!(schemaNode instanceof GroupingDefinition)) {
1671 it.addImplementsType(augmentable(it));
1673 if (schemaNode instanceof DataNodeContainer) {
1674 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1675 groupingsToGenTypes(context, containerSchema.getGroupings());
1676 addImplementedInterfaceFromUses(containerSchema, it);
1683 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1684 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1685 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1687 * @param packageName string with the package name to which returning generated type builder belongs
1688 * @param schemaNode schema node which provide data about the schema node name
1689 * @param prefix return type name prefix
1690 * @return generated type builder for <code>schemaNode</code>
1691 * @throws IllegalArgumentException
1693 * <li>if <code>schemaNode</code> is null</li>
1694 * <li>if <code>packageName</code> is null</li>
1695 * <li>if QName of schema node is null</li>
1696 * <li>if schemaNode name is null</li>
1699 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1700 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1701 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1702 final String schemaNodeName = schemaNode.getQName().getLocalName();
1703 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1705 // FIXME: Validation of name conflict
1706 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1707 final Module module = findParentModule(schemaContext, schemaNode);
1708 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1709 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1711 addCodegenInformation(newType, module, schemaNode);
1712 newType.setSchemaPath(schemaNode.getPath());
1713 newType.setModuleName(module.getName());
1715 final String packageName = identifier.packageName();
1716 final String simpleName = identifier.simpleName();
1717 if (!genTypeBuilders.containsKey(packageName)) {
1718 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1719 builders.put(simpleName, newType);
1720 genTypeBuilders.put(packageName, builders);
1722 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1723 if (!builders.containsKey(simpleName)) {
1724 builders.put(simpleName, newType);
1731 * Creates the name of the getter method name from <code>localName</code>.
1733 * @param localName string with the name of the getter method
1734 * @param returnType return type
1735 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1737 public static String getterMethodName(final String localName, final Type returnType) {
1738 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1742 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1743 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1744 * and <code>returnType</code> information are added to the builder.
1746 * @param interfaceBuilder generated type builder for which the getter method should be created
1747 * @param returnType type which represents the return type of the getter method
1748 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1749 * @param comment string with comment for the getter method
1750 * @param status status from yang file, for deprecated annotation
1751 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1753 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1754 final SchemaNode node) {
1755 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1756 getterMethodName(node.getQName().getLocalName(), returnType));
1757 getMethod.setReturnType(returnType);
1759 annotateDeprecatedIfNecessary(node, getMethod);
1760 addComment(getMethod, node);
1765 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1766 final ListSchemaNode node) {
1767 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1768 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1769 getMethod.setReturnType(returnType).setDefault(true);
1770 annotateDeprecatedIfNecessary(node, getMethod);
1774 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1777 * @param basePackageName string contains the module package name
1778 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1779 * or as a property to <code>genTOBuilder</code> if is part of the list key
1780 * @param typeBuilder generated type builder for the list schema node
1781 * @param genTOBuilder generated TO builder for the list keys
1782 * @param listKeys list of string which contains names of the list keys
1783 * @param module current module
1784 * @throws IllegalArgumentException
1786 * <li>if <code>schemaNode</code> equals null</li>
1787 * <li>if <code>typeBuilder</code> equals null</li>
1790 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1791 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1792 final List<String> listKeys, final boolean inGrouping) {
1793 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1794 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1796 if (schemaNode instanceof LeafSchemaNode) {
1797 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1798 final String leafName = leaf.getQName().getLocalName();
1799 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1800 if (listKeys.contains(leafName)) {
1802 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1804 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1807 } else if (!schemaNode.isAddedByUses()) {
1808 if (schemaNode instanceof LeafListSchemaNode) {
1809 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1810 } else if (schemaNode instanceof ContainerSchemaNode) {
1811 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1812 (ContainerSchemaNode) schemaNode, inGrouping);
1813 } else if (schemaNode instanceof ChoiceSchemaNode) {
1814 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1815 } else if (schemaNode instanceof ListSchemaNode) {
1816 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1817 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1818 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1823 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1824 final GeneratedTOBuilder genTOBuilder) {
1825 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1827 if (genTOBuilder != null) {
1828 final GeneratedTransferObject genTO = genTOBuilder.build();
1829 // Add Identifiable.getKey() for items
1830 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1831 .addAnnotation(OVERRIDE_ANNOTATION);
1832 context.addGeneratedTOBuilder(genTOBuilder);
1837 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1839 * @param list of string with names of the list keys
1840 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1841 * an empty list is returned.
1843 private static List<String> listKeys(final ListSchemaNode list) {
1844 final List<QName> keyDefinition = list.getKeyDefinition();
1845 switch (keyDefinition.size()) {
1847 return Collections.emptyList();
1849 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1851 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1852 for (final QName keyDef : keyDefinition) {
1853 listKeys.add(keyDef.getLocalName());
1860 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1861 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1862 * enclosing transfer objects.
1864 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1865 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1866 * @param leaf string with name for generated TO builder
1867 * @param parentModule parent module
1868 * @return generated TO builder for <code>typeDef</code>
1870 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1871 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1872 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1873 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1875 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1876 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1877 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1878 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1879 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1881 for (GeneratedTOBuilder builder : types) {
1882 if (builder.isUnion()) {
1883 final GeneratedTransferObject type = builder.build();
1884 createUnionBuilder(builder, typeBuilder, type, parentModule);
1888 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1892 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1893 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1894 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1897 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1898 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1899 * @param leaf string with name for generated TO builder
1900 * @param parentModule parent module
1901 * @return generated TO builder for <code>typeDef</code>
1903 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1904 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1905 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1906 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1907 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1908 return genTOBuilder;
1912 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1913 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1914 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1915 * to <code>builder</code>
1917 * @param dataNodeContainer element which contains the list of used YANG groupings
1918 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1919 * @return generated type builder with all implemented types
1921 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1922 final GeneratedTypeBuilder builder) {
1923 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1924 final GeneratedTypeBuilder genType = findGrouping(usesNode.getSourceGrouping());
1925 if (genType == null) {
1926 throw new IllegalStateException("Grouping " + usesNode.getSourceGrouping().getQName()
1927 + " is not resolved for " + builder.getName());
1930 builder.addImplementsType(genType.build());
1935 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1936 for (final ModuleContext ctx : genCtx.values()) {
1937 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1938 if (result != null) {
1945 private GeneratedTypeBuilder findGrouping(final GroupingDefinition grouping) {
1946 for (final ModuleContext ctx : genCtx.values()) {
1947 final GeneratedTypeBuilder result = ctx.getGrouping(grouping.getPath());
1948 if (result != null) {
1955 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1956 for (final ModuleContext ctx : genCtx.values()) {
1957 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1958 if (result != null) {
1965 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1966 for (final ModuleContext ctx : genCtx.values()) {
1967 final GeneratedTypeBuilder result = ctx.getCase(path);
1968 if (result != null) {
1975 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
1976 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
1977 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
1980 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
1981 switch (node.getStatus()) {
1983 // FIXME: we really want to use a pre-made annotation
1984 builder.addAnnotation(DEPRECATED_ANNOTATION);
1987 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
1993 throw new IllegalStateException("Unhandled status in " + node);
1997 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
1998 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2001 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2002 defineImplementedInterfaceMethod(typeBuilder, DefaultType.of(typeBuilder)).setDefault(true);
2005 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2006 final Type classType) {
2007 final MethodSignatureBuilder ret = typeBuilder
2008 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2009 .setAccessModifier(AccessModifier.PUBLIC)
2010 .setReturnType(classType(classType));
2011 ret.addAnnotation(OVERRIDE_ANNOTATION);