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.Comparator;
55 import java.util.HashMap;
56 import java.util.HashSet;
57 import java.util.Iterator;
58 import java.util.List;
60 import java.util.Optional;
62 import org.eclipse.jdt.annotation.Nullable;
63 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
64 import org.opendaylight.mdsal.binding.model.api.Constant;
65 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
66 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
67 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
68 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
69 import org.opendaylight.mdsal.binding.model.api.Restrictions;
70 import org.opendaylight.mdsal.binding.model.api.Type;
71 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
72 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
73 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
74 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
75 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
76 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
80 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
81 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
82 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
83 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
84 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
85 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
86 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
87 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
88 import org.opendaylight.yangtools.yang.common.QName;
89 import org.opendaylight.yangtools.yang.common.QNameModule;
90 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
91 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
92 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
99 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
102 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
103 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.Module;
108 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
109 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
110 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
111 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
112 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
113 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
114 import org.opendaylight.yangtools.yang.model.api.Status;
115 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
116 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
117 import org.opendaylight.yangtools.yang.model.api.UsesNode;
118 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
119 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
120 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
121 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
122 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
123 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
124 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
125 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
126 import org.slf4j.Logger;
127 import org.slf4j.LoggerFactory;
129 abstract class AbstractTypeGenerator {
130 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
131 private static final Splitter COLON_SPLITTER = Splitter.on(':');
132 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
133 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
134 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
137 * Comparator based on augment target path.
139 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
140 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
141 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
143 while (thisIt.hasNext()) {
144 if (!otherIt.hasNext()) {
148 final int comp = thisIt.next().compareTo(otherIt.next());
154 return otherIt.hasNext() ? -1 : 0;
158 * Constant with the concrete name of identifier.
160 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
163 * Constant with the concrete name of namespace.
165 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
167 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
170 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
171 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
172 * for schema node specified in key part.
174 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
177 * Provide methods for converting YANG types to JAVA types.
179 private final AbstractTypeProvider typeProvider;
182 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
184 private final SchemaContext schemaContext;
187 * Holds renamed elements.
189 private final Map<SchemaNode, JavaTypeName> renames;
191 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
192 final Map<SchemaNode, JavaTypeName> renames) {
193 this.schemaContext = requireNonNull(context);
194 this.typeProvider = requireNonNull(typeProvider);
195 this.renames = requireNonNull(renames);
197 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
198 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
199 for (final Module contextModule : contextModules) {
200 contexts.add(moduleToGenTypes(contextModule));
203 contexts.forEach(this::allAugmentsToGenTypes);
206 final Collection<ModuleContext> moduleContexts() {
207 return genCtx.values();
210 final ModuleContext moduleContext(final QNameModule module) {
211 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
214 final AbstractTypeProvider typeProvider() {
218 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
220 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
222 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
223 Set<? extends SchemaNode> nodes);
225 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
227 private ModuleContext moduleToGenTypes(final Module module) {
228 final ModuleContext context = new ModuleContext(module);
229 genCtx.put(module.getQNameModule(), context);
230 allTypeDefinitionsToGenTypes(context);
231 groupingsToGenTypes(context, module.getGroupings());
232 rpcMethodsToGenType(context);
233 allIdentitiesToGenTypes(context);
234 notificationsToGenType(context);
236 if (!module.getChildNodes().isEmpty()) {
237 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
238 context.addModuleNode(moduleType);
239 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
245 * Converts all extended type definitions of module to the list of
246 * <code>Type</code> objects.
249 * module from which is obtained set of type definitions
250 * @throws IllegalArgumentException
252 * <li>if module is null</li>
253 * <li>if name of module is null</li>
255 * @throws IllegalStateException
256 * if set of type definitions from module is null
258 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
259 final Module module = context.module();
260 checkArgument(module.getName() != null, "Module name cannot be NULL.");
261 final DataNodeIterator it = new DataNodeIterator(module);
262 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
263 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
265 for (final TypeDefinition<?> typedef : typeDefinitions) {
266 if (typedef != null) {
267 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
269 context.addTypedefType(typedef, type);
270 context.addTypeToSchema(type,typedef);
276 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
277 final DataSchemaNode node, final boolean inGrouping) {
278 if (node.isAugmenting() || node.isAddedByUses()) {
281 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
282 defaultImplementedInterace(genType);
283 annotateDeprecatedIfNecessary(node.getStatus(), genType);
285 final Module module = context.module();
286 genType.setModuleName(module.getName());
287 addCodegenInformation(genType, module, node);
288 genType.setSchemaPath(node.getPath());
289 if (node instanceof DataNodeContainer) {
290 context.addChildNodeType(node, genType);
291 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
292 processUsesAugments((DataNodeContainer) node, context, inGrouping);
297 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
298 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
299 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
300 if (genType != null) {
301 constructGetter(parent, genType, node);
302 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
303 actionsToGenType(context, genType, node, null, inGrouping);
307 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
308 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
309 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
310 if (genType != null) {
311 final ParameterizedType listType = listTypeFor(genType);
312 constructGetter(parent, listType, node);
313 constructNonnull(parent, listType, node);
315 final List<String> listKeys = listKeys(node);
316 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
317 if (genTOBuilder != null) {
318 final Type identifierMarker = identifier(genType);
319 final Type identifiableMarker = identifiable(genTOBuilder);
320 genTOBuilder.addImplementsType(identifierMarker);
321 genType.addImplementsType(identifiableMarker);
324 actionsToGenType(context, genType, node, genTOBuilder, inGrouping);
326 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
327 if (!schemaNode.isAugmenting()) {
328 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys, inGrouping);
333 if (genTOBuilder != null) {
334 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
335 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
336 genTOBuilder.setSUID(prop);
339 typeBuildersToGenTypes(context, genType, genTOBuilder);
343 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
344 final boolean inGrouping) {
345 for (final UsesNode usesNode : node.getUses()) {
346 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
347 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
348 processUsesAugments(augment, context, inGrouping);
354 * Converts all <b>augmentation</b> of the module to the list
355 * <code>Type</code> objects.
358 * module from which is obtained list of all augmentation objects
359 * to iterate over them
360 * @throws IllegalArgumentException
362 * <li>if the module is null</li>
363 * <li>if the name of module is null</li>
365 * @throws IllegalStateException
366 * if set of augmentations from module is null
368 private void allAugmentsToGenTypes(final ModuleContext context) {
369 final Module module = context.module();
370 checkArgument(module != null, "Module reference cannot be NULL.");
371 checkArgument(module.getName() != null, "Module name cannot be NULL.");
372 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
374 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
375 augmentationToGenTypes(context, augment);
380 * Returns list of <code>AugmentationSchema</code> objects. The objects are
381 * sorted according to the length of their target path from the shortest to
385 * module from which is obtained list of all augmentation objects
386 * @return list of sorted <code>AugmentationSchema</code> objects obtained
387 * from <code>module</code>
388 * @throws IllegalArgumentException
390 * @throws IllegalStateException
391 * if set of module augmentations is null
393 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
394 checkArgument(module != null, "Module reference cannot be NULL.");
395 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
397 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
398 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
399 sortedAugmentations.sort(AUGMENT_COMP);
401 return sortedAugmentations;
405 * Create GeneratedTypeBuilder object from module argument.
408 * Module object from which builder will be created
409 * @return <code>GeneratedTypeBuilder</code> which is internal
410 * representation of the module
411 * @throws IllegalArgumentException
414 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
415 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
416 final Module module = context.module();
417 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
418 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
420 addCodegenInformation(moduleDataTypeBuilder, module);
421 return moduleDataTypeBuilder;
424 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
425 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
426 for (final ActionDefinition action : parentSchema.getActions()) {
427 if (action.isAugmenting()) {
431 final GeneratedType input;
432 final GeneratedType output;
433 if (action.isAddedByUses()) {
434 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
435 input = context.getChildNode(orig.getInput().getPath()).build();
436 output = context.getChildNode(orig.getOutput().getPath()).build();
438 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
439 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
442 if (!(parentSchema instanceof GroupingDefinition)) {
443 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
444 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
445 // and do not capture an actual instantiation.
446 final QName qname = action.getQName();
447 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
448 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
449 BindingMapping.getClassName(qname)));
450 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
451 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
453 annotateDeprecatedIfNecessary(action.getStatus(), builder);
454 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
455 : action(parent, input, output));
457 addCodegenInformation(builder, context.module(), action);
458 context.addChildNodeType(action, builder);
463 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
464 for (UsesNode uses : parent.getUses()) {
465 final GroupingDefinition grp = findUsedGrouping(uses);
466 final Optional<ActionDefinition> found = grp.findAction(action.getQName());
467 if (found.isPresent()) {
468 final ActionDefinition result = found.get();
469 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
473 return Optional.empty();
476 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
477 final ContainerSchemaNode schema, final boolean inGrouping) {
478 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
479 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
480 return genType.build();
484 * Converts all <b>RPCs</b> input and output substatements of the module
485 * to the list of <code>Type</code> objects. In addition are to containers
486 * and lists which belong to input or output also part of returning list.
489 * module from which is obtained set of all rpc objects to
491 * @throws IllegalArgumentException
493 * <li>if the module is null</li>
494 * <li>if the name of module is null</li>
496 * @throws IllegalStateException
497 * if set of rpcs from module is null
499 private void rpcMethodsToGenType(final ModuleContext context) {
500 final Module module = context.module();
501 checkArgument(module.getName() != null, "Module name cannot be NULL.");
502 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
503 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
504 if (rpcDefinitions.isEmpty()) {
508 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
509 interfaceBuilder.addImplementsType(RPC_SERVICE);
511 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
513 for (final RpcDefinition rpc : rpcDefinitions) {
515 final String rpcName = BindingMapping.getClassName(rpc.getQName());
516 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
517 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
519 // Do not refer to annotation class, as it may not be available at runtime
520 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
521 addComment(method, rpc);
523 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
524 method.setReturnType(listenableFutureTypeFor(
525 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
529 context.addTopLevelNodeType(interfaceBuilder);
532 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
533 final ContainerSchemaNode schema, final Type type) {
534 processUsesAugments(schema, context, false);
535 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
536 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
538 addImplementedInterfaceFromUses(schema, outType);
539 outType.addImplementsType(type);
540 outType.addImplementsType(augmentable(outType));
541 defaultImplementedInterace(outType);
542 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
543 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
544 context.addChildNodeType(schema, outType);
545 return outType.build();
549 * Converts all <b>notifications</b> of the module to the list of
550 * <code>Type</code> objects. In addition are to this list added containers
551 * and lists which are part of this notification.
554 * module from which is obtained set of all notification objects
555 * to iterate over them
556 * @throws IllegalArgumentException
558 * <li>if the module equals null</li>
559 * <li>if the name of module equals null</li>
561 * @throws IllegalStateException
562 * if set of notifications from module is null
564 private void notificationsToGenType(final ModuleContext context) {
565 final Module module = context.module();
566 checkArgument(module.getName() != null, "Module name cannot be NULL.");
567 final Set<NotificationDefinition> notifications = module.getNotifications();
568 if (notifications.isEmpty()) {
572 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
573 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
575 for (final NotificationDefinition notification : notifications) {
576 if (notification != null) {
577 processUsesAugments(notification, context, false);
579 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
580 context.modulePackageName(), notification, DATA_OBJECT, context);
581 defaultImplementedInterace(notificationInterface);
582 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
583 notificationInterface.addImplementsType(NOTIFICATION);
584 context.addChildNodeType(notification, notificationInterface);
586 // Notification object
587 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
588 notification.getChildNodes(), false);
590 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
591 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
592 .setReturnType(primitiveVoidType()), notification);
596 addCodegenInformation(listenerInterface, module, "notifications", notifications);
597 context.addTopLevelNodeType(listenerInterface);
601 * Converts all <b>identities</b> of the module to the list of
602 * <code>Type</code> objects.
605 * module from which is obtained set of all identity objects to
607 * @param schemaContext
608 * schema context only used as input parameter for method
609 * {@link BindingGeneratorImpl#identityToGenType}
612 private void allIdentitiesToGenTypes(final ModuleContext context) {
613 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
615 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
616 for (final IdentitySchemaNode identity : schemaIdentities) {
617 identityToGenType(context, identity);
623 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
624 * created transport object builder. If identity contains base identity then
625 * reference to base identity is added to superior identity as its extend.
626 * If identity doesn't contain base identity then only reference to abstract
627 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
628 * BaseIdentity} is added
632 * @param basePackageName
633 * string contains the module package name
635 * IdentitySchemaNode which contains data about identity
637 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
638 if (identity == null) {
642 JavaTypeName name = renames.get(identity);
644 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
645 BindingMapping.getClassName(identity.getQName()));
648 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
649 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
650 if (!baseIdentities.isEmpty()) {
651 for (IdentitySchemaNode baseIdentity : baseIdentities) {
652 JavaTypeName base = renames.get(baseIdentity);
654 final QName qname = baseIdentity.getQName();
655 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
656 BindingMapping.getClassName(qname));
659 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
660 newType.addImplementsType(gto);
663 newType.addImplementsType(BASE_IDENTITY);
666 final Module module = context.module();
667 addCodegenInformation(newType, module, identity);
668 newType.setModuleName(module.getName());
669 newType.setSchemaPath(identity.getPath());
671 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
672 identity.getQName().getLocalName());
674 context.addIdentityType(identity, newType);
677 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
678 final JavaTypeName yangModuleInfo, final String localName) {
679 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
680 new SimpleImmutableEntry<>(yangModuleInfo, localName));
684 * Converts all <b>groupings</b> of the module to the list of
685 * <code>Type</code> objects. Firstly are groupings sorted according mutual
686 * dependencies. At least dependent (independent) groupings are in the list
687 * saved at first positions. For every grouping the record is added to map
688 * {@link ModuleContext#groupings allGroupings}
693 * collection of groupings from which types will be generated
696 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
697 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
698 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
699 // node of grouping is resolved to the method.
700 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
701 narrowImplementedInterface(genType);
702 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
703 context.addGroupingType(grouping, genType);
704 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
705 groupingsToGenTypes(context, grouping.getGroupings());
706 processUsesAugments(grouping, context, true);
707 actionsToGenType(context, genType, grouping, null, true);
712 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
713 * <code>enumTypeDef</code> item is added to builder with its name and value.
715 * @param enumTypeDef EnumTypeDefinition contains enum data
716 * @param enumName string contains name which will be assigned to enumeration builder
717 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
718 * @param module Module in which type should be generated
719 * @return enumeration builder which contains data from <code>enumTypeDef</code>
721 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
722 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
723 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
724 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
725 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
726 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
727 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
734 * Generates type builder for <code>module</code>.
736 * @param module Module which is source of package name for generated type builder
737 * @param postfix string which is added to the module class name representation as suffix
738 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
739 * @throws IllegalArgumentException if <code>module</code> is null
741 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
742 final Module module = context.module();
743 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
744 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
745 JavaTypeName.create(context.modulePackageName(), moduleName));
747 moduleBuilder.setModuleName(moduleName);
748 addCodegenInformation(moduleBuilder, module);
749 return moduleBuilder;
753 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
754 * In addition there are also generated types for all containers, list and choices which are child of
755 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
757 * @param augmentPackageName string with the name of the package to which the augmentation belongs
758 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
759 * @param module current module
760 * @throws IllegalArgumentException
762 * <li>if <code>augmentPackageName</code> equals null</li>
763 * <li>if <code>augSchema</code> equals null</li>
765 * @throws IllegalStateException
766 * if augment target path is null
768 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
769 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
770 checkState(augSchema.getTargetPath() != null,
771 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
773 processUsesAugments(augSchema, context, false);
774 final SchemaPath targetPath = augSchema.getTargetPath();
775 SchemaNode targetSchemaNode = null;
777 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
778 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
779 if (targetSchemaNode instanceof DerivableSchemaNode) {
780 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
782 if (targetSchemaNode == null) {
783 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
784 + " in module " + context.module().getName());
787 if (targetSchemaNode == null) {
788 throw new IllegalArgumentException("augment target not found: " + targetPath);
791 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
792 if (targetTypeBuilder == null) {
793 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
795 if (targetTypeBuilder == null) {
796 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
799 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
800 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
801 addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
804 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
805 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
809 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
810 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
811 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
812 checkState(augSchema.getTargetPath() != null,
813 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
815 processUsesAugments(augSchema, context, inGrouping);
816 final SchemaPath targetPath = augSchema.getTargetPath();
817 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
818 if (targetSchemaNode == null) {
819 throw new IllegalArgumentException("augment target not found: " + targetPath);
822 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
823 if (targetTypeBuilder == null) {
824 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
826 if (targetTypeBuilder == null) {
827 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
830 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
831 if (usesNodeParent instanceof SchemaNode) {
832 addRawAugmentGenTypeDefinition(context,
833 packageNameForAugmentedGeneratedType(context.modulePackageName(),
834 ((SchemaNode) usesNodeParent).getPath()),
835 targetTypeBuilder.build(), augSchema, inGrouping);
837 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
840 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
841 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
845 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
846 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
848 if (targetGrouping instanceof GroupingDefinition) {
849 return (GroupingDefinition) targetGrouping;
852 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
856 * Convenient method to find node added by uses statement.
858 * @param targetPath node path
859 * @param parentUsesNode parent of uses node
860 * @return node from its original location in grouping
862 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
863 SchemaNode result = findUsedGrouping(parentUsesNode);
864 for (final QName node : targetPath.getPathFromRoot()) {
865 if (result instanceof DataNodeContainer) {
866 final QName resultNode = node.withModule(result.getQName().getModule());
867 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
868 } else if (result instanceof ChoiceSchemaNode) {
869 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
872 if (result == null) {
876 if (result instanceof DerivableSchemaNode) {
877 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
878 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
879 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
880 result = originalNode.get();
884 if (result instanceof DataSchemaNode) {
885 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
886 if (resultDataSchemaNode.isAddedByUses()) {
887 // The original node is required, but we have only the copy of
888 // the original node.
889 // Maybe this indicates a bug in Yang parser.
890 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
893 return resultDataSchemaNode;
896 throw new IllegalStateException(
897 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
902 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
903 * of augmented node with serial number as suffix.
905 * @param context current module
906 * @param augmentPackageName string with contains the package name to which the augment belongs
907 * @param basePackageName string with the package name to which the augmented node belongs
908 * @param targetTypeRef target type
909 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
910 * @return generated type builder for augment
912 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
913 final String augmentPackageName, final Type targetTypeRef,
914 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
915 Map<String, GeneratedTypeBuilder> augmentBuilders =
916 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
917 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
920 if (augIdentifier != null) {
921 augTypeName = BindingMapping.getClassName(augIdentifier);
923 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
926 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
927 JavaTypeName.create(augmentPackageName, augTypeName));
929 augTypeBuilder.addImplementsType(DATA_OBJECT);
930 defaultImplementedInterace(augTypeBuilder);
932 augTypeBuilder.addImplementsType(augmentationTypeFor(targetTypeRef));
933 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
934 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
936 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
937 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
938 augmentBuilders.put(augTypeName, augTypeBuilder);
940 if (!augSchema.getChildNodes().isEmpty()) {
941 context.addTypeToAugmentation(augTypeBuilder, augSchema);
944 context.addAugmentType(augTypeBuilder);
945 return augTypeBuilder;
948 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
949 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
950 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
954 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
955 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
956 final QName nodeType = unknownSchemaNode.getNodeType();
957 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
958 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
959 return unknownSchemaNode.getNodeParameter();
966 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
967 * consists from name of augmented node and serial number of its augmentation.
969 * @param builders map of builders which were created in the package to which the augmentation belongs
970 * @param genTypeName string with name of augmented node
971 * @return string with unique name for augmentation builder
973 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
975 if (builders != null) {
976 while (builders.containsKey(genTypeName + index)) {
980 return genTypeName + index;
984 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
985 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
986 * already part of them).
988 * @param module current module
989 * @param parent generated type builder which represents any node. The subnodes of this node are added
990 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
992 * @param childOf parent type
993 * @param schemaNodes set of data schema nodes which are the children of the node for which
994 * <code>typeBuilder</code> was created
995 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
996 * child nodes) could be added to it.
998 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
999 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
1000 if (schemaNodes != null && parent != null) {
1001 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1002 for (final DataSchemaNode schemaNode : schemaNodes) {
1003 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1004 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1012 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1015 * @param module current module
1016 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1017 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1018 * container, choice.
1019 * @param childOf parent type
1020 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1022 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1023 * The getter method could be added to it.
1025 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1026 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1027 final boolean inGrouping) {
1028 if (schemaNodes != null && typeBuilder != null) {
1029 final Type baseInterface = childOf(typeBuilder);
1030 for (final DataSchemaNode schemaNode : schemaNodes) {
1031 if (!schemaNode.isAugmenting()) {
1032 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1040 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1042 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1043 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1044 * @param childOf parent type
1045 * @param module current module
1047 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1048 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1049 if (node != null && typeBuilder != null) {
1050 if (node instanceof LeafSchemaNode) {
1051 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1052 } else if (node instanceof LeafListSchemaNode) {
1053 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1054 } else if (node instanceof ContainerSchemaNode) {
1055 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1056 } else if (node instanceof ListSchemaNode) {
1057 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1058 } else if (node instanceof ChoiceSchemaNode) {
1059 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1060 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1061 opaqueToGeneratedType(context, typeBuilder, node);
1063 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1064 typeBuilder.getFullyQualifiedName());
1070 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1071 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1072 * and names of all parents node.
1074 * @param context current module
1075 * @param basePackageName string with the module package name
1076 * @param parent parent type
1077 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1079 * @throws IllegalArgumentException
1081 * <li>if <code>basePackageName</code> is null</li>
1082 * <li>if <code>choiceNode</code> is null</li>
1085 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1086 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1087 if (!choiceNode.isAddedByUses()) {
1088 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1089 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1090 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1091 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1092 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1093 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1095 final GeneratedType choiceType = choiceTypeBuilder.build();
1096 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1098 constructGetter(parent, choiceType, choiceNode);
1102 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1103 final DataSchemaNode anyNode) {
1104 if (!anyNode.isAddedByUses()) {
1105 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(
1106 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1107 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1108 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1109 defaultImplementedInterace(anyxmlTypeBuilder);
1110 annotateDeprecatedIfNecessary(anyNode.getStatus(), anyxmlTypeBuilder);
1111 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1113 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1118 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1119 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1120 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1121 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1123 * @param context current module context
1124 * @param refChoiceType type which represents superior <i>case</i>
1125 * @param choiceNode choice case node which is mapped to generated type
1126 * @throws IllegalArgumentException
1128 * <li>if <code>refChoiceType</code> equals null</li>
1129 * <li>if <code>caseNodes</code> equals null</li>
1132 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1133 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1134 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1135 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1137 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1138 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1139 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1140 caseTypeBuilder.addImplementsType(refChoiceType);
1141 defaultImplementedInterace(caseTypeBuilder);
1142 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1143 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1144 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1145 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1146 if (caseChildNodes != null) {
1147 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1149 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1150 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1152 if (parent instanceof AugmentationSchemaNode) {
1153 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1154 final SchemaPath targetPath = augSchema.getTargetPath();
1155 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1156 if (targetSchemaNode instanceof DataSchemaNode
1157 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1158 if (targetSchemaNode instanceof DerivableSchemaNode) {
1159 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1162 if (targetSchemaNode == null) {
1163 throw new IllegalStateException(
1164 "Failed to find target node from grouping for augmentation " + augSchema
1165 + " in module " + context.module().getName());
1168 parent = targetSchemaNode;
1171 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1172 Type childOfType = findChildNodeByPath(parent.getPath());
1173 if (childOfType == null) {
1174 childOfType = findGroupingByPath(parent.getPath());
1176 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1178 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1183 processUsesAugments(caseNode, context, inGrouping);
1188 * Generates list of generated types for all the cases of a choice which are added to the choice through
1191 * @param module current module
1192 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1193 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1194 * of the augmenting choice will belong to pcg2.
1195 * @param targetType Type which represents target choice
1196 * @param targetNode node which represents target choice
1197 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1199 * @throws IllegalArgumentException
1201 * <li>if <code>basePackageName</code> is null</li>
1202 * <li>if <code>targetType</code> is null</li>
1203 * <li>if <code>augmentedNodes</code> is null</li>
1206 // FIXME: nullness rules need to untangled in this method
1207 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1208 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1209 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1210 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1211 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1212 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1214 for (final DataSchemaNode caseNode : augmentedNodes) {
1215 if (caseNode != null) {
1216 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1217 caseTypeBuilder.addImplementsType(targetType);
1218 defaultImplementedInterace(caseTypeBuilder);
1220 CaseSchemaNode node = null;
1221 final String caseLocalName = caseNode.getQName().getLocalName();
1222 if (caseNode instanceof CaseSchemaNode) {
1223 node = (CaseSchemaNode) caseNode;
1224 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1225 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1226 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1227 if (dataSchemaNode instanceof ChoiceSchemaNode
1228 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1229 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1234 node = findNamedCase(targetNode, caseLocalName);
1236 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1237 if (childNodes != null) {
1238 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1241 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1242 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1247 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1248 final SchemaPath nodePath = targetNode.getPath();
1249 final SchemaPath parentSp = nodePath.getParent();
1250 if (parentSp.getParent() == null) {
1251 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1254 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1255 GeneratedTypeBuilder childOfType = null;
1256 if (parent instanceof CaseSchemaNode) {
1257 childOfType = findCaseByPath(parent.getPath());
1258 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1259 childOfType = findChildNodeByPath(parent.getPath());
1260 } else if (parent instanceof GroupingDefinition) {
1261 childOfType = findGroupingByPath(parent.getPath());
1264 if (childOfType == null) {
1265 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1271 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1272 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1273 return cases.isEmpty() ? null : cases.get(0);
1276 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1277 // New parser with encapsulated type
1278 if (leaf.getPath().equals(type.getPath())) {
1282 // Embedded type definition with new parser. Also takes care of the old parser with bits
1283 if (leaf.getPath().equals(type.getPath().getParent())) {
1290 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1291 final List<PatternConstraint> patternConstraints) {
1292 if (!patternConstraints.isEmpty()) {
1293 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1294 .append(BindingMapping.getPropertyName(leafName));
1295 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1296 typeProvider.resolveRegExpressions(patternConstraints));
1301 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1303 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1304 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1305 * @param module Module in which type was defined
1306 * @return boolean value
1308 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1310 * <li>true - in other cases</li>
1313 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1314 final ModuleContext context, final boolean inGrouping) {
1315 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1319 final Module parentModule = findParentModule(schemaContext, leaf);
1320 Type returnType = null;
1322 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1323 if (isInnerType(leaf, typeDef)) {
1324 if (typeDef instanceof EnumTypeDefinition) {
1325 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1326 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1327 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1328 typeBuilder, context);
1329 if (enumBuilder != null) {
1330 returnType = enumBuilder.toInstance(typeBuilder);
1332 typeProvider.putReferencedType(leaf.getPath(), returnType);
1333 } else if (typeDef instanceof UnionTypeDefinition) {
1334 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1335 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1336 // Store the inner type within the union so that we can find the reference for it
1337 context.addInnerTypedefType(typeDef.getPath(), returnType);
1338 } else if (typeDef instanceof BitsTypeDefinition) {
1339 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1341 if (genTOBuilder != null) {
1342 returnType = genTOBuilder.build();
1345 // It is constrained version of already declared type (inner declared type exists,
1346 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1347 // In order to get proper class we need to look up closest derived type
1348 // and apply restrictions from leaf type
1349 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1350 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1351 restrictions, inGrouping);
1352 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1355 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1356 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1357 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1360 if (returnType == null) {
1364 if (typeDef instanceof EnumTypeDefinition) {
1365 typeProvider.putReferencedType(leaf.getPath(), returnType);
1368 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1369 processContextRefExtension(leaf, getter, parentModule);
1373 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1374 // Returns DerivedType in case of new parser.
1375 final TypeDefinition<?> baseType = typeDef.getBaseType();
1376 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1379 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1380 final Module module) {
1381 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1382 final QName nodeType = node.getNodeType();
1383 if ("context-reference".equals(nodeType.getLocalName())) {
1384 final String nodeParam = node.getNodeParameter();
1385 IdentitySchemaNode identity = null;
1386 String basePackageName = null;
1387 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1388 final Iterator<String> iterator = splittedElement.iterator();
1389 final int length = Iterables.size(splittedElement);
1391 identity = findIdentityByName(module.getIdentities(), iterator.next());
1392 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1393 } else if (length == 2) {
1394 final String prefix = iterator.next();
1395 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1396 if (dependentModule == null) {
1397 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1400 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1401 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1403 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1406 if (identity == null) {
1407 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1411 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1412 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1413 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1414 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1419 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1420 for (final IdentitySchemaNode id : identities) {
1421 if (id.getQName().getLocalName().equals(name)) {
1428 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1429 for (final ModuleImport imp : imports) {
1430 if (imp.getPrefix().equals(prefix)) {
1431 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1437 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1438 final boolean isReadOnly) {
1439 if (leaf != null && toBuilder != null) {
1441 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1442 if (typeDef instanceof UnionTypeDefinition) {
1443 // GeneratedType for this type definition should have be already created
1444 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1445 returnType = mc.getTypedefs().get(typeDef.getPath());
1446 if (returnType == null) {
1447 // This may still be an inner type, try to find it
1448 returnType = mc.getInnerType(typeDef.getPath());
1450 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1451 // Annonymous enumeration (already generated, since it is inherited via uses).
1452 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1453 QName qname = originalLeaf.getQName();
1454 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1456 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1458 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1464 * Converts <code>leaf</code> schema node to property of generated TO builder.
1466 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1467 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1468 * @param returnType property type
1469 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1470 * @return boolean value
1472 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1473 * name equals null or if leaf is added by <i>uses</i>.</li>
1474 * <li>true - other cases</li>
1477 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1478 final Type returnType, final boolean isReadOnly) {
1479 if (returnType == null) {
1482 final String leafName = leaf.getQName().getLocalName();
1483 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1484 propBuilder.setReadOnly(isReadOnly);
1485 propBuilder.setReturnType(returnType);
1486 addComment(propBuilder, leaf);
1488 toBuilder.addEqualsIdentity(propBuilder);
1489 toBuilder.addHashIdentity(propBuilder);
1490 toBuilder.addToStringProperty(propBuilder);
1495 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1497 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1498 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1499 * @param module module
1500 * @return boolean value
1502 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1503 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1504 * <li>false - other cases</li>
1507 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1508 final ModuleContext context, final boolean inGrouping) {
1509 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1513 final QName nodeName = node.getQName();
1515 final TypeDefinition<?> typeDef = node.getType();
1516 final Module parentModule = findParentModule(schemaContext, node);
1518 Type returnType = null;
1519 if (typeDef.getBaseType() == null) {
1520 if (typeDef instanceof EnumTypeDefinition) {
1521 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1522 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1523 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1524 typeBuilder, context);
1525 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1526 typeProvider.putReferencedType(node.getPath(), returnType);
1527 } else if (typeDef instanceof UnionTypeDefinition) {
1528 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1529 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1530 } else if (typeDef instanceof BitsTypeDefinition) {
1531 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1532 node, parentModule);
1533 returnType = genTOBuilder.build();
1535 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1536 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1537 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1540 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1541 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1542 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1545 constructGetter(typeBuilder, listTypeFor(returnType), node);
1549 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1550 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1551 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1552 returnTypeBuilder.setIsUnion(true);
1553 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1554 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1555 returnTypeBuilder.setModuleName(parentModule.getName());
1556 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1558 genTOBuilder.setTypedef(true);
1559 genTOBuilder.setIsUnion(true);
1560 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1562 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1566 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1567 final GeneratedTransferObject returnType, final Module parentModule) {
1568 // Append enclosing path hierarchy without dots
1569 final StringBuilder sb = new StringBuilder();
1570 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1571 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1572 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1573 unionBuilder.setIsUnionBuilder(true);
1575 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1576 method.setReturnType(returnType);
1577 method.addParameter(STRING, "defaultValue");
1578 method.setAccessModifier(AccessModifier.PUBLIC);
1579 method.setStatic(true);
1581 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1582 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1585 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1586 final SchemaNode schemaNode) {
1587 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1590 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1591 final SchemaNode schemaNode, final Type baseInterface) {
1592 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1593 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1597 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1598 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1599 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1600 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1601 * If <code>schemaNode</code> is instance of
1602 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1603 * which are specified in <i>uses</i>.
1605 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1606 * @param schemaNode schema node for which is created generated type builder
1607 * @param parent parent type (can be null)
1608 * @return generated type builder <code>schemaNode</code>
1610 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1611 final Type baseInterface, final ModuleContext context) {
1612 JavaTypeName name = renames.get(schemaNode);
1614 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1617 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1618 it.addImplementsType(baseInterface);
1619 if (!(schemaNode instanceof GroupingDefinition)) {
1620 it.addImplementsType(augmentable(it));
1622 if (schemaNode instanceof DataNodeContainer) {
1623 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1624 groupingsToGenTypes(context, containerSchema.getGroupings());
1625 addImplementedInterfaceFromUses(containerSchema, it);
1632 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1633 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1634 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1636 * @param packageName string with the package name to which returning generated type builder belongs
1637 * @param schemaNode schema node which provide data about the schema node name
1638 * @param prefix return type name prefix
1639 * @return generated type builder for <code>schemaNode</code>
1640 * @throws IllegalArgumentException
1642 * <li>if <code>schemaNode</code> is null</li>
1643 * <li>if <code>packageName</code> is null</li>
1644 * <li>if QName of schema node is null</li>
1645 * <li>if schemaNode name is null</li>
1648 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1649 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1650 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1651 final String schemaNodeName = schemaNode.getQName().getLocalName();
1652 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1654 // FIXME: Validation of name conflict
1655 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1656 final Module module = findParentModule(schemaContext, schemaNode);
1657 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1658 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1660 addCodegenInformation(newType, module, schemaNode);
1661 newType.setSchemaPath(schemaNode.getPath());
1662 newType.setModuleName(module.getName());
1664 final String packageName = identifier.packageName();
1665 final String simpleName = identifier.simpleName();
1666 if (!genTypeBuilders.containsKey(packageName)) {
1667 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1668 builders.put(simpleName, newType);
1669 genTypeBuilders.put(packageName, builders);
1671 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1672 if (!builders.containsKey(simpleName)) {
1673 builders.put(simpleName, newType);
1680 * Creates the name of the getter method name from <code>localName</code>.
1682 * @param localName string with the name of the getter method
1683 * @param returnType return type
1684 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1686 public static String getterMethodName(final String localName, final Type returnType) {
1687 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1691 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1692 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1693 * and <code>returnType</code> information are added to the builder.
1695 * @param interfaceBuilder generated type builder for which the getter method should be created
1696 * @param returnType type which represents the return type of the getter method
1697 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1698 * @param comment string with comment for the getter method
1699 * @param status status from yang file, for deprecated annotation
1700 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1702 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1703 final SchemaNode node) {
1704 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1705 getterMethodName(node.getQName().getLocalName(), returnType));
1706 getMethod.setReturnType(returnType);
1708 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1709 addComment(getMethod, node);
1714 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1715 final ListSchemaNode node) {
1716 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1717 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1718 getMethod.setReturnType(returnType).setDefault(true);
1719 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1723 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1726 * @param basePackageName string contains the module package name
1727 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1728 * or as a property to <code>genTOBuilder</code> if is part of the list key
1729 * @param typeBuilder generated type builder for the list schema node
1730 * @param genTOBuilder generated TO builder for the list keys
1731 * @param listKeys list of string which contains names of the list keys
1732 * @param module current module
1733 * @throws IllegalArgumentException
1735 * <li>if <code>schemaNode</code> equals null</li>
1736 * <li>if <code>typeBuilder</code> equals null</li>
1739 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1740 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1741 final List<String> listKeys, final boolean inGrouping) {
1742 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1743 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1745 if (schemaNode instanceof LeafSchemaNode) {
1746 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1747 final String leafName = leaf.getQName().getLocalName();
1748 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1749 if (listKeys.contains(leafName)) {
1751 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1753 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1756 } else if (!schemaNode.isAddedByUses()) {
1757 if (schemaNode instanceof LeafListSchemaNode) {
1758 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1759 } else if (schemaNode instanceof ContainerSchemaNode) {
1760 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1761 (ContainerSchemaNode) schemaNode, inGrouping);
1762 } else if (schemaNode instanceof ChoiceSchemaNode) {
1763 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1764 } else if (schemaNode instanceof ListSchemaNode) {
1765 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1770 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1771 final GeneratedTOBuilder genTOBuilder) {
1772 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1774 if (genTOBuilder != null) {
1775 final GeneratedTransferObject genTO = genTOBuilder.build();
1776 // Add Identifiable.getKey() for items
1777 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1778 .addAnnotation(OVERRIDE_ANNOTATION);
1779 context.addGeneratedTOBuilder(genTOBuilder);
1784 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1786 * @param list of string with names of the list keys
1787 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1788 * an empty list is returned.
1790 private static List<String> listKeys(final ListSchemaNode list) {
1791 final List<String> listKeys = new ArrayList<>();
1793 final List<QName> keyDefinition = list.getKeyDefinition();
1794 if (keyDefinition != null) {
1795 for (final QName keyDef : keyDefinition) {
1796 listKeys.add(keyDef.getLocalName());
1803 * Generates for the <code>list</code> which contains any list keys special generated TO builder.
1805 * @param packageName string with package name to which the list belongs
1806 * @param list list schema node which is source of data about the list name
1807 * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
1808 * null or list of key definitions is null or empty.
1810 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1811 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1812 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1813 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1814 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1820 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1821 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1822 * enclosing transfer objects.
1824 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1825 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1826 * @param leaf string with name for generated TO builder
1827 * @param parentModule parent module
1828 * @return generated TO builder for <code>typeDef</code>
1830 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1831 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1832 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1833 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1835 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1836 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1837 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1838 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1839 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1841 for (GeneratedTOBuilder builder : types) {
1842 if (builder.isUnion()) {
1843 final GeneratedTransferObject type = builder.build();
1844 createUnionBuilder(builder, typeBuilder, type, parentModule);
1848 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1852 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1853 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1854 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1857 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1858 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1859 * @param leaf string with name for generated TO builder
1860 * @param parentModule parent module
1861 * @return generated TO builder for <code>typeDef</code>
1863 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1864 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1865 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1866 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1867 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1868 return genTOBuilder;
1872 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1873 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1874 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1875 * to <code>builder</code>
1877 * @param dataNodeContainer element which contains the list of used YANG groupings
1878 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1879 * @return generated type builder with all implemented types
1881 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1882 final GeneratedTypeBuilder builder) {
1883 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1884 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1885 if (genType == null) {
1886 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1887 + builder.getName());
1890 builder.addImplementsType(genType.build());
1895 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1896 for (final ModuleContext ctx : genCtx.values()) {
1897 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1898 if (result != null) {
1905 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1906 for (final ModuleContext ctx : genCtx.values()) {
1907 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1908 if (result != null) {
1915 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1916 for (final ModuleContext ctx : genCtx.values()) {
1917 final GeneratedTypeBuilder result = ctx.getCase(path);
1918 if (result != null) {
1925 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
1926 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
1927 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
1930 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1931 if (status == Status.DEPRECATED) {
1932 builder.addAnnotation(DEPRECATED_ANNOTATION);
1936 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
1937 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
1940 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
1941 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
1945 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
1946 final Type classType) {
1947 final MethodSignatureBuilder ret = typeBuilder
1948 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
1949 .setAccessModifier(AccessModifier.PUBLIC)
1950 .setReturnType(classType(classType));
1951 ret.addAnnotation(OVERRIDE_ANNOTATION);