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.ROUTING_CONTEXT;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.opaqueObject;
34 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
35 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
36 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
37 import static org.opendaylight.mdsal.binding.model.util.Types.augmentationTypeFor;
38 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
39 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
40 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
41 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
42 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
43 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
44 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
45 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
46 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
48 import com.google.common.base.Splitter;
49 import com.google.common.collect.Iterables;
50 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
51 import java.util.AbstractMap.SimpleImmutableEntry;
52 import java.util.ArrayList;
53 import java.util.Collection;
54 import java.util.Collections;
55 import java.util.Comparator;
56 import java.util.HashMap;
57 import java.util.HashSet;
58 import java.util.Iterator;
59 import java.util.List;
61 import java.util.Optional;
63 import org.eclipse.jdt.annotation.Nullable;
64 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
65 import org.opendaylight.mdsal.binding.model.api.Constant;
66 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
67 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
68 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
69 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
70 import org.opendaylight.mdsal.binding.model.api.Restrictions;
71 import org.opendaylight.mdsal.binding.model.api.Type;
72 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
73 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
74 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
75 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
76 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
81 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
82 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
83 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
84 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
85 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
86 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
87 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
88 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
89 import org.opendaylight.yangtools.yang.common.QName;
90 import org.opendaylight.yangtools.yang.common.QNameModule;
91 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
92 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
93 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
100 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
103 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
104 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
105 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.Module;
110 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
111 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
112 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
113 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
114 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
116 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
117 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
118 import org.opendaylight.yangtools.yang.model.api.UsesNode;
119 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
120 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
121 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
122 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
123 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
124 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
125 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
126 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
127 import org.slf4j.Logger;
128 import org.slf4j.LoggerFactory;
130 abstract class AbstractTypeGenerator {
131 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
132 private static final Splitter COLON_SPLITTER = Splitter.on(':');
133 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
134 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
135 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
138 * Comparator based on augment target path.
140 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
141 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
142 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
144 while (thisIt.hasNext()) {
145 if (!otherIt.hasNext()) {
149 final int comp = thisIt.next().compareTo(otherIt.next());
155 return otherIt.hasNext() ? -1 : 0;
159 * Constant with the concrete name of identifier.
161 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
164 * Constant with the concrete name of namespace.
166 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
168 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
171 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
172 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
173 * for schema node specified in key part.
175 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
178 * Provide methods for converting YANG types to JAVA types.
180 private final AbstractTypeProvider typeProvider;
183 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
185 private final SchemaContext schemaContext;
188 * Holds renamed elements.
190 private final Map<SchemaNode, JavaTypeName> renames;
192 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
193 final Map<SchemaNode, JavaTypeName> renames) {
194 this.schemaContext = requireNonNull(context);
195 this.typeProvider = requireNonNull(typeProvider);
196 this.renames = requireNonNull(renames);
198 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
199 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
200 for (final Module contextModule : contextModules) {
201 contexts.add(moduleToGenTypes(contextModule));
204 contexts.forEach(this::allAugmentsToGenTypes);
207 final Collection<ModuleContext> moduleContexts() {
208 return genCtx.values();
211 final ModuleContext moduleContext(final QNameModule module) {
212 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
215 final AbstractTypeProvider typeProvider() {
219 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
221 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
223 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
224 Set<? extends SchemaNode> nodes);
226 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
228 private ModuleContext moduleToGenTypes(final Module module) {
229 final ModuleContext context = new ModuleContext(module);
230 genCtx.put(module.getQNameModule(), context);
231 allTypeDefinitionsToGenTypes(context);
232 groupingsToGenTypes(context, module.getGroupings());
233 rpcMethodsToGenType(context);
234 allIdentitiesToGenTypes(context);
235 notificationsToGenType(context);
237 if (!module.getChildNodes().isEmpty()) {
238 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
239 context.addModuleNode(moduleType);
240 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
246 * Converts all extended type definitions of module to the list of
247 * <code>Type</code> objects.
250 * module from which is obtained set of type definitions
251 * @throws IllegalArgumentException
253 * <li>if module is null</li>
254 * <li>if name of module is null</li>
256 * @throws IllegalStateException
257 * if set of type definitions from module is null
259 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
260 final Module module = context.module();
261 checkArgument(module.getName() != null, "Module name cannot be NULL.");
262 final DataNodeIterator it = new DataNodeIterator(module);
263 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
264 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
266 for (final TypeDefinition<?> typedef : typeDefinitions) {
267 if (typedef != null) {
268 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
270 context.addTypedefType(typedef, type);
271 context.addTypeToSchema(type,typedef);
277 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
278 final DataSchemaNode node, final boolean inGrouping) {
279 if (node.isAugmenting() || node.isAddedByUses()) {
282 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
283 defaultImplementedInterace(genType);
284 annotateDeprecatedIfNecessary(node, genType);
286 final Module module = context.module();
287 genType.setModuleName(module.getName());
288 addCodegenInformation(genType, module, node);
289 genType.setSchemaPath(node.getPath());
290 if (node instanceof DataNodeContainer) {
291 context.addChildNodeType(node, genType);
292 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
293 processUsesAugments((DataNodeContainer) node, context, inGrouping);
298 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
299 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
300 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
301 if (genType != null) {
302 constructGetter(parent, genType, node);
303 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
304 actionsToGenType(context, genType, node, null, inGrouping);
308 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
309 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
310 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
311 if (genType != null) {
312 final ParameterizedType listType = listTypeFor(genType);
313 constructGetter(parent, listType, node);
314 constructNonnull(parent, listType, node);
316 final List<String> listKeys = listKeys(node);
317 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
318 if (genTOBuilder != null) {
319 final Type identifierMarker = identifier(genType);
320 final Type identifiableMarker = identifiable(genTOBuilder);
321 genTOBuilder.addImplementsType(identifierMarker);
322 genType.addImplementsType(identifiableMarker);
325 actionsToGenType(context, genType, node, genTOBuilder, inGrouping);
327 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
328 if (!schemaNode.isAugmenting()) {
329 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys, inGrouping);
334 if (genTOBuilder != null) {
335 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
336 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
337 genTOBuilder.setSUID(prop);
340 typeBuildersToGenTypes(context, genType, genTOBuilder);
344 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
345 final boolean inGrouping) {
346 for (final UsesNode usesNode : node.getUses()) {
347 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
348 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
349 processUsesAugments(augment, context, inGrouping);
355 * Converts all <b>augmentation</b> of the module to the list
356 * <code>Type</code> objects.
359 * module from which is obtained list of all augmentation objects
360 * to iterate over them
361 * @throws IllegalArgumentException
363 * <li>if the module is null</li>
364 * <li>if the name of module is null</li>
366 * @throws IllegalStateException
367 * if set of augmentations from module is null
369 private void allAugmentsToGenTypes(final ModuleContext context) {
370 final Module module = context.module();
371 checkArgument(module != null, "Module reference cannot be NULL.");
372 checkArgument(module.getName() != null, "Module name cannot be NULL.");
373 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
375 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
376 augmentationToGenTypes(context, augment);
381 * Returns list of <code>AugmentationSchema</code> objects. The objects are
382 * sorted according to the length of their target path from the shortest to
386 * module from which is obtained list of all augmentation objects
387 * @return list of sorted <code>AugmentationSchema</code> objects obtained
388 * from <code>module</code>
389 * @throws IllegalArgumentException
391 * @throws IllegalStateException
392 * if set of module augmentations is null
394 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
395 checkArgument(module != null, "Module reference cannot be NULL.");
396 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
398 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
399 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
400 sortedAugmentations.sort(AUGMENT_COMP);
402 return sortedAugmentations;
406 * Create GeneratedTypeBuilder object from module argument.
409 * Module object from which builder will be created
410 * @return <code>GeneratedTypeBuilder</code> which is internal
411 * representation of the module
412 * @throws IllegalArgumentException
415 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
416 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
417 final Module module = context.module();
418 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
419 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
421 addCodegenInformation(moduleDataTypeBuilder, module);
422 return moduleDataTypeBuilder;
425 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
426 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
427 for (final ActionDefinition action : parentSchema.getActions()) {
428 if (action.isAugmenting()) {
432 final GeneratedType input;
433 final GeneratedType output;
434 if (action.isAddedByUses()) {
435 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
436 input = context.getChildNode(orig.getInput().getPath()).build();
437 output = context.getChildNode(orig.getOutput().getPath()).build();
439 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
440 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
443 if (!(parentSchema instanceof GroupingDefinition)) {
444 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
445 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
446 // and do not capture an actual instantiation.
447 final QName qname = action.getQName();
448 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
449 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
450 BindingMapping.getClassName(qname)));
451 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
452 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
454 annotateDeprecatedIfNecessary(action, builder);
455 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
456 : action(parent, input, output));
458 addCodegenInformation(builder, context.module(), action);
459 context.addChildNodeType(action, builder);
464 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
465 for (UsesNode uses : parent.getUses()) {
466 final GroupingDefinition grp = findUsedGrouping(uses);
467 final Optional<ActionDefinition> found = grp.findAction(action.getQName());
468 if (found.isPresent()) {
469 final ActionDefinition result = found.get();
470 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
474 return Optional.empty();
477 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
478 final ContainerSchemaNode schema, final boolean inGrouping) {
479 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
480 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
481 return genType.build();
485 * Converts all <b>RPCs</b> input and output substatements of the module
486 * to the list of <code>Type</code> objects. In addition are to containers
487 * and lists which belong to input or output also part of returning list.
490 * module from which is obtained set of all rpc objects to
492 * @throws IllegalArgumentException
494 * <li>if the module is null</li>
495 * <li>if the name of module is null</li>
497 * @throws IllegalStateException
498 * if set of rpcs from module is null
500 private void rpcMethodsToGenType(final ModuleContext context) {
501 final Module module = context.module();
502 checkArgument(module.getName() != null, "Module name cannot be NULL.");
503 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
504 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
505 if (rpcDefinitions.isEmpty()) {
509 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
510 interfaceBuilder.addImplementsType(RPC_SERVICE);
512 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
514 for (final RpcDefinition rpc : rpcDefinitions) {
516 final String rpcName = BindingMapping.getClassName(rpc.getQName());
517 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
518 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
520 // Do not refer to annotation class, as it may not be available at runtime
521 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
522 addComment(method, rpc);
524 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
525 method.setReturnType(listenableFutureTypeFor(
526 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
530 context.addTopLevelNodeType(interfaceBuilder);
533 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
534 final ContainerSchemaNode schema, final Type type) {
535 processUsesAugments(schema, context, false);
536 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
537 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
539 addImplementedInterfaceFromUses(schema, outType);
540 outType.addImplementsType(type);
541 outType.addImplementsType(augmentable(outType));
542 defaultImplementedInterace(outType);
543 annotateDeprecatedIfNecessary(rpc, outType);
544 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
545 context.addChildNodeType(schema, outType);
546 return outType.build();
550 * Converts all <b>notifications</b> of the module to the list of
551 * <code>Type</code> objects. In addition are to this list added containers
552 * and lists which are part of this notification.
555 * module from which is obtained set of all notification objects
556 * to iterate over them
557 * @throws IllegalArgumentException
559 * <li>if the module equals null</li>
560 * <li>if the name of module equals null</li>
562 * @throws IllegalStateException
563 * if set of notifications from module is null
565 private void notificationsToGenType(final ModuleContext context) {
566 final Module module = context.module();
567 checkArgument(module.getName() != null, "Module name cannot be NULL.");
568 final Set<NotificationDefinition> notifications = module.getNotifications();
569 if (notifications.isEmpty()) {
573 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
574 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
576 for (final NotificationDefinition notification : notifications) {
577 if (notification != null) {
578 processUsesAugments(notification, context, false);
580 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
581 context.modulePackageName(), notification, DATA_OBJECT, context);
582 defaultImplementedInterace(notificationInterface);
583 annotateDeprecatedIfNecessary(notification, notificationInterface);
584 notificationInterface.addImplementsType(NOTIFICATION);
585 context.addChildNodeType(notification, notificationInterface);
587 // Notification object
588 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
589 notification.getChildNodes(), false);
591 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
592 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
593 .setReturnType(primitiveVoidType()), notification);
597 addCodegenInformation(listenerInterface, module, "notifications", notifications);
598 context.addTopLevelNodeType(listenerInterface);
602 * Converts all <b>identities</b> of the module to the list of
603 * <code>Type</code> objects.
606 * module from which is obtained set of all identity objects to
608 * @param schemaContext
609 * schema context only used as input parameter for method
610 * {@link BindingGeneratorImpl#identityToGenType}
613 private void allIdentitiesToGenTypes(final ModuleContext context) {
614 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
616 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
617 for (final IdentitySchemaNode identity : schemaIdentities) {
618 identityToGenType(context, identity);
624 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
625 * created transport object builder. If identity contains base identity then
626 * reference to base identity is added to superior identity as its extend.
627 * If identity doesn't contain base identity then only reference to abstract
628 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
629 * BaseIdentity} is added
633 * @param basePackageName
634 * string contains the module package name
636 * IdentitySchemaNode which contains data about identity
638 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
639 if (identity == null) {
643 JavaTypeName name = renames.get(identity);
645 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
646 BindingMapping.getClassName(identity.getQName()));
649 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
650 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
651 if (!baseIdentities.isEmpty()) {
652 for (IdentitySchemaNode baseIdentity : baseIdentities) {
653 JavaTypeName base = renames.get(baseIdentity);
655 final QName qname = baseIdentity.getQName();
656 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
657 BindingMapping.getClassName(qname));
660 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
661 newType.addImplementsType(gto);
664 newType.addImplementsType(BASE_IDENTITY);
667 final Module module = context.module();
668 addCodegenInformation(newType, module, identity);
669 newType.setModuleName(module.getName());
670 newType.setSchemaPath(identity.getPath());
672 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
673 identity.getQName().getLocalName());
675 context.addIdentityType(identity, newType);
678 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
679 final JavaTypeName yangModuleInfo, final String localName) {
680 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
681 new SimpleImmutableEntry<>(yangModuleInfo, localName));
685 * Converts all <b>groupings</b> of the module to the list of
686 * <code>Type</code> objects. Firstly are groupings sorted according mutual
687 * dependencies. At least dependent (independent) groupings are in the list
688 * saved at first positions. For every grouping the record is added to map
689 * {@link ModuleContext#groupings allGroupings}
694 * collection of groupings from which types will be generated
697 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
698 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
699 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
700 // node of grouping is resolved to the method.
701 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
702 narrowImplementedInterface(genType);
703 annotateDeprecatedIfNecessary(grouping, genType);
704 context.addGroupingType(grouping, genType);
705 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
706 groupingsToGenTypes(context, grouping.getGroupings());
707 processUsesAugments(grouping, context, true);
708 actionsToGenType(context, genType, grouping, null, true);
713 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
714 * <code>enumTypeDef</code> item is added to builder with its name and value.
716 * @param enumTypeDef EnumTypeDefinition contains enum data
717 * @param enumName string contains name which will be assigned to enumeration builder
718 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
719 * @param module Module in which type should be generated
720 * @return enumeration builder which contains data from <code>enumTypeDef</code>
722 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
723 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
724 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
725 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
726 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
727 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
728 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
735 * Generates type builder for <code>module</code>.
737 * @param module Module which is source of package name for generated type builder
738 * @param postfix string which is added to the module class name representation as suffix
739 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
740 * @throws IllegalArgumentException if <code>module</code> is null
742 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
743 final Module module = context.module();
744 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
745 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
746 JavaTypeName.create(context.modulePackageName(), moduleName));
748 moduleBuilder.setModuleName(moduleName);
749 addCodegenInformation(moduleBuilder, module);
750 return moduleBuilder;
754 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
755 * In addition there are also generated types for all containers, list and choices which are child of
756 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
758 * @param augmentPackageName string with the name of the package to which the augmentation belongs
759 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
760 * @param module current module
761 * @throws IllegalArgumentException
763 * <li>if <code>augmentPackageName</code> equals null</li>
764 * <li>if <code>augSchema</code> equals null</li>
766 * @throws IllegalStateException
767 * if augment target path is null
769 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
770 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
771 checkState(augSchema.getTargetPath() != null,
772 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
774 processUsesAugments(augSchema, context, false);
775 final SchemaPath targetPath = augSchema.getTargetPath();
776 SchemaNode targetSchemaNode = null;
778 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
779 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
780 if (targetSchemaNode instanceof DerivableSchemaNode) {
781 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
783 if (targetSchemaNode == null) {
784 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
785 + " in module " + context.module().getName());
788 if (targetSchemaNode == null) {
789 throw new IllegalArgumentException("augment target not found: " + targetPath);
792 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
793 if (targetTypeBuilder == null) {
794 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
796 if (targetTypeBuilder == null) {
797 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
800 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
801 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
802 addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
805 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
806 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
810 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
811 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
812 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
813 checkState(augSchema.getTargetPath() != null,
814 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
816 processUsesAugments(augSchema, context, inGrouping);
817 final SchemaPath targetPath = augSchema.getTargetPath();
818 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
819 if (targetSchemaNode == null) {
820 throw new IllegalArgumentException("augment target not found: " + targetPath);
823 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
824 if (targetTypeBuilder == null) {
825 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
827 if (targetTypeBuilder == null) {
828 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
831 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
832 if (usesNodeParent instanceof SchemaNode) {
833 addRawAugmentGenTypeDefinition(context,
834 packageNameForAugmentedGeneratedType(context.modulePackageName(),
835 ((SchemaNode) usesNodeParent).getPath()),
836 targetTypeBuilder.build(), augSchema, inGrouping);
838 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
841 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
842 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
846 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
847 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
849 if (targetGrouping instanceof GroupingDefinition) {
850 return (GroupingDefinition) targetGrouping;
853 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
857 * Convenient method to find node added by uses statement.
859 * @param targetPath node path
860 * @param parentUsesNode parent of uses node
861 * @return node from its original location in grouping
863 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
864 SchemaNode result = findUsedGrouping(parentUsesNode);
865 for (final QName node : targetPath.getPathFromRoot()) {
866 if (result instanceof DataNodeContainer) {
867 final QName resultNode = node.withModule(result.getQName().getModule());
868 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
869 } else if (result instanceof ChoiceSchemaNode) {
870 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
873 if (result == null) {
877 if (result instanceof DerivableSchemaNode) {
878 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
879 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
880 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
881 result = originalNode.get();
885 if (result instanceof DataSchemaNode) {
886 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
887 if (resultDataSchemaNode.isAddedByUses()) {
888 // The original node is required, but we have only the copy of
889 // the original node.
890 // Maybe this indicates a bug in Yang parser.
891 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
894 return resultDataSchemaNode;
897 throw new IllegalStateException(
898 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
903 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
904 * of augmented node with serial number as suffix.
906 * @param context current module
907 * @param augmentPackageName string with contains the package name to which the augment belongs
908 * @param basePackageName string with the package name to which the augmented node belongs
909 * @param targetTypeRef target type
910 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
911 * @return generated type builder for augment
913 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
914 final String augmentPackageName, final Type targetTypeRef,
915 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
916 Map<String, GeneratedTypeBuilder> augmentBuilders =
917 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
918 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
921 if (augIdentifier != null) {
922 augTypeName = BindingMapping.getClassName(augIdentifier);
924 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
927 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
928 JavaTypeName.create(augmentPackageName, augTypeName));
930 augTypeBuilder.addImplementsType(DATA_OBJECT);
931 defaultImplementedInterace(augTypeBuilder);
933 augTypeBuilder.addImplementsType(augmentationTypeFor(targetTypeRef));
934 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
935 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
937 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
938 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
939 augmentBuilders.put(augTypeName, augTypeBuilder);
941 if (!augSchema.getChildNodes().isEmpty()) {
942 context.addTypeToAugmentation(augTypeBuilder, augSchema);
945 context.addAugmentType(augTypeBuilder);
946 return augTypeBuilder;
949 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
950 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
951 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
955 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
956 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
957 final QName nodeType = unknownSchemaNode.getNodeType();
958 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
959 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
960 return unknownSchemaNode.getNodeParameter();
967 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
968 * consists from name of augmented node and serial number of its augmentation.
970 * @param builders map of builders which were created in the package to which the augmentation belongs
971 * @param genTypeName string with name of augmented node
972 * @return string with unique name for augmentation builder
974 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
976 if (builders != null) {
977 while (builders.containsKey(genTypeName + index)) {
981 return genTypeName + index;
985 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
986 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
987 * already part of them).
989 * @param module current module
990 * @param parent generated type builder which represents any node. The subnodes of this node are added
991 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
993 * @param childOf parent type
994 * @param schemaNodes set of data schema nodes which are the children of the node for which
995 * <code>typeBuilder</code> was created
996 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
997 * child nodes) could be added to it.
999 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1000 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
1001 if (schemaNodes != null && parent != null) {
1002 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1003 for (final DataSchemaNode schemaNode : schemaNodes) {
1004 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1005 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1013 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1016 * @param module current module
1017 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1018 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1019 * container, choice.
1020 * @param childOf parent type
1021 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1023 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1024 * The getter method could be added to it.
1026 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1027 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1028 final boolean inGrouping) {
1029 if (schemaNodes != null && typeBuilder != null) {
1030 final Type baseInterface = childOf(typeBuilder);
1031 for (final DataSchemaNode schemaNode : schemaNodes) {
1032 if (!schemaNode.isAugmenting()) {
1033 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1041 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1043 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1044 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1045 * @param childOf parent type
1046 * @param module current module
1048 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1049 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1050 if (node != null && typeBuilder != null) {
1051 if (node instanceof LeafSchemaNode) {
1052 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1053 } else if (node instanceof LeafListSchemaNode) {
1054 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1055 } else if (node instanceof ContainerSchemaNode) {
1056 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1057 } else if (node instanceof ListSchemaNode) {
1058 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1059 } else if (node instanceof ChoiceSchemaNode) {
1060 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1061 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1062 opaqueToGeneratedType(context, typeBuilder, node);
1064 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1065 typeBuilder.getFullyQualifiedName());
1071 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1072 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1073 * and names of all parents node.
1075 * @param context current module
1076 * @param basePackageName string with the module package name
1077 * @param parent parent type
1078 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1080 * @throws IllegalArgumentException
1082 * <li>if <code>basePackageName</code> is null</li>
1083 * <li>if <code>choiceNode</code> is null</li>
1086 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1087 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1088 if (!choiceNode.isAddedByUses()) {
1089 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1090 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1091 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1092 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1093 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1094 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1096 final GeneratedType choiceType = choiceTypeBuilder.build();
1097 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1099 constructGetter(parent, choiceType, choiceNode);
1103 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1104 final DataSchemaNode anyNode) {
1105 if (!anyNode.isAddedByUses()) {
1106 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(
1107 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1108 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1109 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1110 defaultImplementedInterace(anyxmlTypeBuilder);
1111 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1112 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1114 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1119 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1120 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1121 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1122 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1124 * @param context current module context
1125 * @param refChoiceType type which represents superior <i>case</i>
1126 * @param choiceNode choice case node which is mapped to generated type
1127 * @throws IllegalArgumentException
1129 * <li>if <code>refChoiceType</code> equals null</li>
1130 * <li>if <code>caseNodes</code> equals null</li>
1133 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1134 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1135 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1136 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1138 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1139 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1140 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1141 caseTypeBuilder.addImplementsType(refChoiceType);
1142 defaultImplementedInterace(caseTypeBuilder);
1143 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1144 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1145 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1146 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1147 if (caseChildNodes != null) {
1148 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1150 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1151 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1153 if (parent instanceof AugmentationSchemaNode) {
1154 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1155 final SchemaPath targetPath = augSchema.getTargetPath();
1156 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1157 if (targetSchemaNode instanceof DataSchemaNode
1158 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1159 if (targetSchemaNode instanceof DerivableSchemaNode) {
1160 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1163 if (targetSchemaNode == null) {
1164 throw new IllegalStateException(
1165 "Failed to find target node from grouping for augmentation " + augSchema
1166 + " in module " + context.module().getName());
1169 parent = targetSchemaNode;
1172 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1173 Type childOfType = findChildNodeByPath(parent.getPath());
1174 if (childOfType == null) {
1175 childOfType = findGroupingByPath(parent.getPath());
1177 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1179 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1184 processUsesAugments(caseNode, context, inGrouping);
1189 * Generates list of generated types for all the cases of a choice which are added to the choice through
1192 * @param module current module
1193 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1194 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1195 * of the augmenting choice will belong to pcg2.
1196 * @param targetType Type which represents target choice
1197 * @param targetNode node which represents target choice
1198 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1200 * @throws IllegalArgumentException
1202 * <li>if <code>basePackageName</code> is null</li>
1203 * <li>if <code>targetType</code> is null</li>
1204 * <li>if <code>augmentedNodes</code> is null</li>
1207 // FIXME: nullness rules need to untangled in this method
1208 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1209 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1210 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1211 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1212 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1213 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1215 for (final DataSchemaNode caseNode : augmentedNodes) {
1216 if (caseNode != null) {
1217 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1218 caseTypeBuilder.addImplementsType(targetType);
1219 defaultImplementedInterace(caseTypeBuilder);
1221 CaseSchemaNode node = null;
1222 final String caseLocalName = caseNode.getQName().getLocalName();
1223 if (caseNode instanceof CaseSchemaNode) {
1224 node = (CaseSchemaNode) caseNode;
1225 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1226 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1227 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1228 if (dataSchemaNode instanceof ChoiceSchemaNode
1229 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1230 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1235 node = findNamedCase(targetNode, caseLocalName);
1237 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1238 if (childNodes != null) {
1239 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1242 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1243 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1248 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1249 final SchemaPath nodePath = targetNode.getPath();
1250 final SchemaPath parentSp = nodePath.getParent();
1251 if (parentSp.getParent() == null) {
1252 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1255 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1256 GeneratedTypeBuilder childOfType = null;
1257 if (parent instanceof CaseSchemaNode) {
1258 childOfType = findCaseByPath(parent.getPath());
1259 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1260 childOfType = findChildNodeByPath(parent.getPath());
1261 } else if (parent instanceof GroupingDefinition) {
1262 childOfType = findGroupingByPath(parent.getPath());
1265 if (childOfType == null) {
1266 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1272 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1273 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1274 return cases.isEmpty() ? null : cases.get(0);
1277 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1278 // New parser with encapsulated type
1279 if (leaf.getPath().equals(type.getPath())) {
1283 // Embedded type definition with new parser. Also takes care of the old parser with bits
1284 if (leaf.getPath().equals(type.getPath().getParent())) {
1291 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1292 final List<PatternConstraint> patternConstraints) {
1293 if (!patternConstraints.isEmpty()) {
1294 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1295 .append(BindingMapping.getPropertyName(leafName));
1296 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1297 typeProvider.resolveRegExpressions(patternConstraints));
1302 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1304 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1305 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1306 * @param module Module in which type was defined
1307 * @return boolean value
1309 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1311 * <li>true - in other cases</li>
1314 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1315 final ModuleContext context, final boolean inGrouping) {
1316 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1320 final Module parentModule = findParentModule(schemaContext, leaf);
1321 Type returnType = null;
1323 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1324 if (isInnerType(leaf, typeDef)) {
1325 if (typeDef instanceof EnumTypeDefinition) {
1326 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1327 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1328 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1329 typeBuilder, context);
1330 if (enumBuilder != null) {
1331 returnType = enumBuilder.toInstance(typeBuilder);
1333 typeProvider.putReferencedType(leaf.getPath(), returnType);
1334 } else if (typeDef instanceof UnionTypeDefinition) {
1335 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1336 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1337 // Store the inner type within the union so that we can find the reference for it
1338 context.addInnerTypedefType(typeDef.getPath(), returnType);
1339 } else if (typeDef instanceof BitsTypeDefinition) {
1340 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1342 if (genTOBuilder != null) {
1343 returnType = genTOBuilder.build();
1346 // It is constrained version of already declared type (inner declared type exists,
1347 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1348 // In order to get proper class we need to look up closest derived type
1349 // and apply restrictions from leaf type
1350 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1351 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1352 restrictions, inGrouping);
1353 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1356 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1357 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1358 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1361 if (returnType == null) {
1365 if (typeDef instanceof EnumTypeDefinition) {
1366 typeProvider.putReferencedType(leaf.getPath(), returnType);
1369 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1370 processContextRefExtension(leaf, getter, parentModule);
1374 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1375 // Returns DerivedType in case of new parser.
1376 final TypeDefinition<?> baseType = typeDef.getBaseType();
1377 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1380 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1381 final Module module) {
1382 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1383 final QName nodeType = node.getNodeType();
1384 if ("context-reference".equals(nodeType.getLocalName())) {
1385 final String nodeParam = node.getNodeParameter();
1386 IdentitySchemaNode identity = null;
1387 String basePackageName = null;
1388 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1389 final Iterator<String> iterator = splittedElement.iterator();
1390 final int length = Iterables.size(splittedElement);
1392 identity = findIdentityByName(module.getIdentities(), iterator.next());
1393 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1394 } else if (length == 2) {
1395 final String prefix = iterator.next();
1396 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1397 if (dependentModule == null) {
1398 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1401 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1402 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1404 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1407 if (identity == null) {
1408 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1412 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1413 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1414 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1415 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1420 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1421 for (final IdentitySchemaNode id : identities) {
1422 if (id.getQName().getLocalName().equals(name)) {
1429 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1430 for (final ModuleImport imp : imports) {
1431 if (imp.getPrefix().equals(prefix)) {
1432 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1438 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1439 final boolean isReadOnly) {
1440 if (leaf != null && toBuilder != null) {
1442 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1443 if (typeDef instanceof UnionTypeDefinition) {
1444 // GeneratedType for this type definition should have be already created
1445 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1446 returnType = mc.getTypedefs().get(typeDef.getPath());
1447 if (returnType == null) {
1448 // This may still be an inner type, try to find it
1449 returnType = mc.getInnerType(typeDef.getPath());
1451 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1452 // Annonymous enumeration (already generated, since it is inherited via uses).
1453 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1454 QName qname = originalLeaf.getQName();
1455 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1457 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1459 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1465 * Converts <code>leaf</code> schema node to property of generated TO builder.
1467 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1468 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1469 * @param returnType property type
1470 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1471 * @return boolean value
1473 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1474 * name equals null or if leaf is added by <i>uses</i>.</li>
1475 * <li>true - other cases</li>
1478 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1479 final Type returnType, final boolean isReadOnly) {
1480 if (returnType == null) {
1483 final String leafName = leaf.getQName().getLocalName();
1484 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1485 propBuilder.setReadOnly(isReadOnly);
1486 propBuilder.setReturnType(returnType);
1487 addComment(propBuilder, leaf);
1489 toBuilder.addEqualsIdentity(propBuilder);
1490 toBuilder.addHashIdentity(propBuilder);
1491 toBuilder.addToStringProperty(propBuilder);
1496 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1498 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1499 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1500 * @param module module
1501 * @return boolean value
1503 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1504 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1505 * <li>false - other cases</li>
1508 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1509 final ModuleContext context, final boolean inGrouping) {
1510 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1514 final QName nodeName = node.getQName();
1516 final TypeDefinition<?> typeDef = node.getType();
1517 final Module parentModule = findParentModule(schemaContext, node);
1519 Type returnType = null;
1520 if (typeDef.getBaseType() == null) {
1521 if (typeDef instanceof EnumTypeDefinition) {
1522 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1523 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1524 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1525 typeBuilder, context);
1526 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1527 typeProvider.putReferencedType(node.getPath(), returnType);
1528 } else if (typeDef instanceof UnionTypeDefinition) {
1529 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1530 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1531 } else if (typeDef instanceof BitsTypeDefinition) {
1532 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1533 node, parentModule);
1534 returnType = genTOBuilder.build();
1536 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1537 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1538 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1541 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1542 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1543 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1546 constructGetter(typeBuilder, listTypeFor(returnType), node);
1550 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1551 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1552 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1553 returnTypeBuilder.setIsUnion(true);
1554 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1555 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1556 returnTypeBuilder.setModuleName(parentModule.getName());
1557 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1559 genTOBuilder.setTypedef(true);
1560 genTOBuilder.setIsUnion(true);
1561 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1563 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1567 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1568 final GeneratedTransferObject returnType, final Module parentModule) {
1569 // Append enclosing path hierarchy without dots
1570 final StringBuilder sb = new StringBuilder();
1571 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1572 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1573 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1574 unionBuilder.setIsUnionBuilder(true);
1576 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1577 method.setReturnType(returnType);
1578 method.addParameter(STRING, "defaultValue");
1579 method.setAccessModifier(AccessModifier.PUBLIC);
1580 method.setStatic(true);
1582 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1583 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1586 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1587 final SchemaNode schemaNode) {
1588 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1591 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1592 final SchemaNode schemaNode, final Type baseInterface) {
1593 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1594 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1598 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1599 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1600 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1601 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1602 * If <code>schemaNode</code> is instance of
1603 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1604 * which are specified in <i>uses</i>.
1606 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1607 * @param schemaNode schema node for which is created generated type builder
1608 * @param parent parent type (can be null)
1609 * @return generated type builder <code>schemaNode</code>
1611 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1612 final Type baseInterface, final ModuleContext context) {
1613 JavaTypeName name = renames.get(schemaNode);
1615 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1618 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1619 it.addImplementsType(baseInterface);
1620 if (!(schemaNode instanceof GroupingDefinition)) {
1621 it.addImplementsType(augmentable(it));
1623 if (schemaNode instanceof DataNodeContainer) {
1624 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1625 groupingsToGenTypes(context, containerSchema.getGroupings());
1626 addImplementedInterfaceFromUses(containerSchema, it);
1633 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1634 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1635 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1637 * @param packageName string with the package name to which returning generated type builder belongs
1638 * @param schemaNode schema node which provide data about the schema node name
1639 * @param prefix return type name prefix
1640 * @return generated type builder for <code>schemaNode</code>
1641 * @throws IllegalArgumentException
1643 * <li>if <code>schemaNode</code> is null</li>
1644 * <li>if <code>packageName</code> is null</li>
1645 * <li>if QName of schema node is null</li>
1646 * <li>if schemaNode name is null</li>
1649 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1650 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1651 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1652 final String schemaNodeName = schemaNode.getQName().getLocalName();
1653 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1655 // FIXME: Validation of name conflict
1656 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1657 final Module module = findParentModule(schemaContext, schemaNode);
1658 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1659 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1661 addCodegenInformation(newType, module, schemaNode);
1662 newType.setSchemaPath(schemaNode.getPath());
1663 newType.setModuleName(module.getName());
1665 final String packageName = identifier.packageName();
1666 final String simpleName = identifier.simpleName();
1667 if (!genTypeBuilders.containsKey(packageName)) {
1668 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1669 builders.put(simpleName, newType);
1670 genTypeBuilders.put(packageName, builders);
1672 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1673 if (!builders.containsKey(simpleName)) {
1674 builders.put(simpleName, newType);
1681 * Creates the name of the getter method name from <code>localName</code>.
1683 * @param localName string with the name of the getter method
1684 * @param returnType return type
1685 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1687 public static String getterMethodName(final String localName, final Type returnType) {
1688 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1692 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1693 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1694 * and <code>returnType</code> information are added to the builder.
1696 * @param interfaceBuilder generated type builder for which the getter method should be created
1697 * @param returnType type which represents the return type of the getter method
1698 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1699 * @param comment string with comment for the getter method
1700 * @param status status from yang file, for deprecated annotation
1701 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1703 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1704 final SchemaNode node) {
1705 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1706 getterMethodName(node.getQName().getLocalName(), returnType));
1707 getMethod.setReturnType(returnType);
1709 annotateDeprecatedIfNecessary(node, getMethod);
1710 addComment(getMethod, node);
1715 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1716 final ListSchemaNode node) {
1717 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1718 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1719 getMethod.setReturnType(returnType).setDefault(true);
1720 annotateDeprecatedIfNecessary(node, getMethod);
1724 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1727 * @param basePackageName string contains the module package name
1728 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1729 * or as a property to <code>genTOBuilder</code> if is part of the list key
1730 * @param typeBuilder generated type builder for the list schema node
1731 * @param genTOBuilder generated TO builder for the list keys
1732 * @param listKeys list of string which contains names of the list keys
1733 * @param module current module
1734 * @throws IllegalArgumentException
1736 * <li>if <code>schemaNode</code> equals null</li>
1737 * <li>if <code>typeBuilder</code> equals null</li>
1740 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1741 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1742 final List<String> listKeys, final boolean inGrouping) {
1743 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1744 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1746 if (schemaNode instanceof LeafSchemaNode) {
1747 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1748 final String leafName = leaf.getQName().getLocalName();
1749 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1750 if (listKeys.contains(leafName)) {
1752 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1754 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1757 } else if (!schemaNode.isAddedByUses()) {
1758 if (schemaNode instanceof LeafListSchemaNode) {
1759 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1760 } else if (schemaNode instanceof ContainerSchemaNode) {
1761 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1762 (ContainerSchemaNode) schemaNode, inGrouping);
1763 } else if (schemaNode instanceof ChoiceSchemaNode) {
1764 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1765 } else if (schemaNode instanceof ListSchemaNode) {
1766 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1771 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1772 final GeneratedTOBuilder genTOBuilder) {
1773 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1775 if (genTOBuilder != null) {
1776 final GeneratedTransferObject genTO = genTOBuilder.build();
1777 // Add Identifiable.getKey() for items
1778 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1779 .addAnnotation(OVERRIDE_ANNOTATION);
1780 context.addGeneratedTOBuilder(genTOBuilder);
1785 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1787 * @param list of string with names of the list keys
1788 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1789 * an empty list is returned.
1791 private static List<String> listKeys(final ListSchemaNode list) {
1792 final List<QName> keyDefinition = list.getKeyDefinition();
1793 switch (keyDefinition.size()) {
1795 return Collections.emptyList();
1797 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1799 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1800 for (final QName keyDef : keyDefinition) {
1801 listKeys.add(keyDef.getLocalName());
1808 * Generates for the <code>list</code> which contains any list keys special generated TO builder.
1810 * @param packageName string with package name to which the list belongs
1811 * @param list list schema node which is source of data about the list name
1812 * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
1813 * null or list of key definitions is null or empty.
1815 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1816 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1817 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1818 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1819 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1825 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1826 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1827 * enclosing transfer objects.
1829 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1830 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1831 * @param leaf string with name for generated TO builder
1832 * @param parentModule parent module
1833 * @return generated TO builder for <code>typeDef</code>
1835 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1836 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1837 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1838 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1840 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1841 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1842 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1843 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1844 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1846 for (GeneratedTOBuilder builder : types) {
1847 if (builder.isUnion()) {
1848 final GeneratedTransferObject type = builder.build();
1849 createUnionBuilder(builder, typeBuilder, type, parentModule);
1853 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1857 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1858 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1859 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1862 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1863 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1864 * @param leaf string with name for generated TO builder
1865 * @param parentModule parent module
1866 * @return generated TO builder for <code>typeDef</code>
1868 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1869 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1870 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1871 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1872 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1873 return genTOBuilder;
1877 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1878 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1879 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1880 * to <code>builder</code>
1882 * @param dataNodeContainer element which contains the list of used YANG groupings
1883 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1884 * @return generated type builder with all implemented types
1886 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1887 final GeneratedTypeBuilder builder) {
1888 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1889 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1890 if (genType == null) {
1891 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1892 + builder.getName());
1895 builder.addImplementsType(genType.build());
1900 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1901 for (final ModuleContext ctx : genCtx.values()) {
1902 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1903 if (result != null) {
1910 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1911 for (final ModuleContext ctx : genCtx.values()) {
1912 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1913 if (result != null) {
1920 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1921 for (final ModuleContext ctx : genCtx.values()) {
1922 final GeneratedTypeBuilder result = ctx.getCase(path);
1923 if (result != null) {
1930 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
1931 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
1932 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
1935 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
1936 switch (node.getStatus()) {
1938 // FIXME: we really want to use a pre-made annotation
1939 builder.addAnnotation(DEPRECATED_ANNOTATION);
1942 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
1948 throw new IllegalStateException("Unhandled status in " + node);
1952 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
1953 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
1956 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
1957 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
1961 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
1962 final Type classType) {
1963 final MethodSignatureBuilder ret = typeBuilder
1964 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
1965 .setAccessModifier(AccessModifier.PUBLIC)
1966 .setReturnType(classType(classType));
1967 ret.addAnnotation(OVERRIDE_ANNOTATION);