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.AnyXmlSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
98 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
101 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
102 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.Module;
107 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
108 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
109 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
110 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
111 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
112 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
113 import org.opendaylight.yangtools.yang.model.api.Status;
114 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
115 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
116 import org.opendaylight.yangtools.yang.model.api.UsesNode;
117 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
118 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
119 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
120 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
121 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
122 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
123 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
124 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
125 import org.slf4j.Logger;
126 import org.slf4j.LoggerFactory;
128 abstract class AbstractTypeGenerator {
129 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
130 private static final Splitter COLON_SPLITTER = Splitter.on(':');
131 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
132 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
133 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
136 * Comparator based on augment target path.
138 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
139 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
140 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
142 while (thisIt.hasNext()) {
143 if (!otherIt.hasNext()) {
147 final int comp = thisIt.next().compareTo(otherIt.next());
153 return otherIt.hasNext() ? -1 : 0;
157 * Constant with the concrete name of identifier.
159 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
162 * Constant with the concrete name of namespace.
164 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
166 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
169 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
170 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
171 * for schema node specified in key part.
173 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
176 * Provide methods for converting YANG types to JAVA types.
178 private final AbstractTypeProvider typeProvider;
181 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
183 private final SchemaContext schemaContext;
186 * Holds renamed elements.
188 private final Map<SchemaNode, JavaTypeName> renames;
190 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
191 final Map<SchemaNode, JavaTypeName> renames) {
192 this.schemaContext = requireNonNull(context);
193 this.typeProvider = requireNonNull(typeProvider);
194 this.renames = requireNonNull(renames);
196 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
197 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
198 for (final Module contextModule : contextModules) {
199 contexts.add(moduleToGenTypes(contextModule));
202 contexts.forEach(this::allAugmentsToGenTypes);
205 final Collection<ModuleContext> moduleContexts() {
206 return genCtx.values();
209 final ModuleContext moduleContext(final QNameModule module) {
210 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
213 final AbstractTypeProvider typeProvider() {
217 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
219 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
221 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
222 Set<? extends SchemaNode> nodes);
224 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
226 private ModuleContext moduleToGenTypes(final Module module) {
227 final ModuleContext context = new ModuleContext(module);
228 genCtx.put(module.getQNameModule(), context);
229 allTypeDefinitionsToGenTypes(context);
230 groupingsToGenTypes(context, module.getGroupings());
231 rpcMethodsToGenType(context);
232 allIdentitiesToGenTypes(context);
233 notificationsToGenType(context);
235 if (!module.getChildNodes().isEmpty()) {
236 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
237 context.addModuleNode(moduleType);
238 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
244 * Converts all extended type definitions of module to the list of
245 * <code>Type</code> objects.
248 * module from which is obtained set of type definitions
249 * @throws IllegalArgumentException
251 * <li>if module is null</li>
252 * <li>if name of module is null</li>
254 * @throws IllegalStateException
255 * if set of type definitions from module is null
257 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
258 final Module module = context.module();
259 checkArgument(module.getName() != null, "Module name cannot be NULL.");
260 final DataNodeIterator it = new DataNodeIterator(module);
261 final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
262 checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
264 for (final TypeDefinition<?> typedef : typeDefinitions) {
265 if (typedef != null) {
266 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
268 context.addTypedefType(typedef, type);
269 context.addTypeToSchema(type,typedef);
275 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
276 final DataSchemaNode node, final boolean inGrouping) {
277 if (node.isAugmenting() || node.isAddedByUses()) {
280 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
281 defaultImplementedInterace(genType);
282 annotateDeprecatedIfNecessary(node.getStatus(), genType);
284 final Module module = context.module();
285 genType.setModuleName(module.getName());
286 addCodegenInformation(genType, module, node);
287 genType.setSchemaPath(node.getPath());
288 if (node instanceof DataNodeContainer) {
289 context.addChildNodeType(node, genType);
290 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
291 processUsesAugments((DataNodeContainer) node, context, inGrouping);
296 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
297 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
298 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
299 if (genType != null) {
300 constructGetter(parent, genType, node);
301 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
302 actionsToGenType(context, genType, node, null, inGrouping);
306 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
307 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
308 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
309 if (genType != null) {
310 final ParameterizedType listType = listTypeFor(genType);
311 constructGetter(parent, listType, node);
312 constructNonnull(parent, listType, node);
314 final List<String> listKeys = listKeys(node);
315 final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
316 if (genTOBuilder != null) {
317 final Type identifierMarker = identifier(genType);
318 final Type identifiableMarker = identifiable(genTOBuilder);
319 genTOBuilder.addImplementsType(identifierMarker);
320 genType.addImplementsType(identifiableMarker);
323 actionsToGenType(context, genType, node, genTOBuilder, inGrouping);
325 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
326 if (!schemaNode.isAugmenting()) {
327 addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys, inGrouping);
332 if (genTOBuilder != null) {
333 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
334 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
335 genTOBuilder.setSUID(prop);
338 typeBuildersToGenTypes(context, genType, genTOBuilder);
342 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
343 final boolean inGrouping) {
344 for (final UsesNode usesNode : node.getUses()) {
345 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
346 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
347 processUsesAugments(augment, context, inGrouping);
353 * Converts all <b>augmentation</b> of the module to the list
354 * <code>Type</code> objects.
357 * module from which is obtained list of all augmentation objects
358 * to iterate over them
359 * @throws IllegalArgumentException
361 * <li>if the module is null</li>
362 * <li>if the name of module is null</li>
364 * @throws IllegalStateException
365 * if set of augmentations from module is null
367 private void allAugmentsToGenTypes(final ModuleContext context) {
368 final Module module = context.module();
369 checkArgument(module != null, "Module reference cannot be NULL.");
370 checkArgument(module.getName() != null, "Module name cannot be NULL.");
371 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
373 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
374 augmentationToGenTypes(context, augment);
379 * Returns list of <code>AugmentationSchema</code> objects. The objects are
380 * sorted according to the length of their target path from the shortest to
384 * module from which is obtained list of all augmentation objects
385 * @return list of sorted <code>AugmentationSchema</code> objects obtained
386 * from <code>module</code>
387 * @throws IllegalArgumentException
389 * @throws IllegalStateException
390 * if set of module augmentations is null
392 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
393 checkArgument(module != null, "Module reference cannot be NULL.");
394 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
396 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
397 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
398 sortedAugmentations.sort(AUGMENT_COMP);
400 return sortedAugmentations;
404 * Create GeneratedTypeBuilder object from module argument.
407 * Module object from which builder will be created
408 * @return <code>GeneratedTypeBuilder</code> which is internal
409 * representation of the module
410 * @throws IllegalArgumentException
413 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
414 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
415 final Module module = context.module();
416 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
417 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
419 addCodegenInformation(moduleDataTypeBuilder, module);
420 return moduleDataTypeBuilder;
423 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
424 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
425 for (final ActionDefinition action : parentSchema.getActions()) {
426 final GeneratedType input;
427 final GeneratedType output;
428 if (action.isAddedByUses()) {
429 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
430 input = context.getChildNode(orig.getInput().getPath()).build();
431 output = context.getChildNode(orig.getOutput().getPath()).build();
433 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
434 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
437 if (!(parentSchema instanceof GroupingDefinition)) {
438 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
439 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
440 // and do not capture an actual instantiation.
441 final QName qname = action.getQName();
442 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
443 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
444 BindingMapping.getClassName(qname)));
445 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
446 BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
448 annotateDeprecatedIfNecessary(action.getStatus(), builder);
449 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
450 : action(parent, input, output));
452 addCodegenInformation(builder, context.module(), action);
453 context.addChildNodeType(action, builder);
458 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
459 for (UsesNode uses : parent.getUses()) {
460 final GroupingDefinition grp = findUsedGrouping(uses);
461 final Optional<ActionDefinition> found = grp.getActions().stream()
462 .filter(act -> action.getQName().equals(act.getQName())).findFirst();
463 if (found.isPresent()) {
464 final ActionDefinition result = found.get();
465 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
469 return Optional.empty();
472 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
473 final ContainerSchemaNode schema, final boolean inGrouping) {
474 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
475 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
476 return genType.build();
480 * Converts all <b>RPCs</b> input and output substatements of the module
481 * to the list of <code>Type</code> objects. In addition are to containers
482 * and lists which belong to input or output also part of returning list.
485 * module from which is obtained set of all rpc objects to
487 * @throws IllegalArgumentException
489 * <li>if the module is null</li>
490 * <li>if the name of module is null</li>
492 * @throws IllegalStateException
493 * if set of rpcs from module is null
495 private void rpcMethodsToGenType(final ModuleContext context) {
496 final Module module = context.module();
497 checkArgument(module.getName() != null, "Module name cannot be NULL.");
498 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
499 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
500 if (rpcDefinitions.isEmpty()) {
504 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
505 interfaceBuilder.addImplementsType(RPC_SERVICE);
507 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
509 for (final RpcDefinition rpc : rpcDefinitions) {
511 final String rpcName = BindingMapping.getClassName(rpc.getQName());
512 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
513 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
515 // Do not refer to annotation class, as it may not be available at runtime
516 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
517 addComment(method, rpc);
519 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
520 method.setReturnType(listenableFutureTypeFor(
521 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
525 context.addTopLevelNodeType(interfaceBuilder);
528 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
529 final ContainerSchemaNode schema, final Type type) {
530 processUsesAugments(schema, context, false);
531 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
532 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
534 addImplementedInterfaceFromUses(schema, outType);
535 outType.addImplementsType(type);
536 outType.addImplementsType(augmentable(outType));
537 defaultImplementedInterace(outType);
538 annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
539 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
540 context.addChildNodeType(schema, outType);
541 return outType.build();
545 * Converts all <b>notifications</b> of the module to the list of
546 * <code>Type</code> objects. In addition are to this list added containers
547 * and lists which are part of this notification.
550 * module from which is obtained set of all notification objects
551 * to iterate over them
552 * @throws IllegalArgumentException
554 * <li>if the module equals null</li>
555 * <li>if the name of module equals null</li>
557 * @throws IllegalStateException
558 * if set of notifications from module is null
560 private void notificationsToGenType(final ModuleContext context) {
561 final Module module = context.module();
562 checkArgument(module.getName() != null, "Module name cannot be NULL.");
563 final Set<NotificationDefinition> notifications = module.getNotifications();
564 if (notifications.isEmpty()) {
568 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
569 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
571 for (final NotificationDefinition notification : notifications) {
572 if (notification != null) {
573 processUsesAugments(notification, context, false);
575 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
576 context.modulePackageName(), notification, DATA_OBJECT, context);
577 defaultImplementedInterace(notificationInterface);
578 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
579 notificationInterface.addImplementsType(NOTIFICATION);
580 context.addChildNodeType(notification, notificationInterface);
582 // Notification object
583 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
584 notification.getChildNodes(), false);
586 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
587 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
588 .setReturnType(primitiveVoidType()), notification);
592 addCodegenInformation(listenerInterface, module, "notifications", notifications);
593 context.addTopLevelNodeType(listenerInterface);
597 * Converts all <b>identities</b> of the module to the list of
598 * <code>Type</code> objects.
601 * module from which is obtained set of all identity objects to
603 * @param schemaContext
604 * schema context only used as input parameter for method
605 * {@link BindingGeneratorImpl#identityToGenType}
608 private void allIdentitiesToGenTypes(final ModuleContext context) {
609 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
611 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
612 for (final IdentitySchemaNode identity : schemaIdentities) {
613 identityToGenType(context, identity);
619 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
620 * created transport object builder. If identity contains base identity then
621 * reference to base identity is added to superior identity as its extend.
622 * If identity doesn't contain base identity then only reference to abstract
623 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
624 * BaseIdentity} is added
628 * @param basePackageName
629 * string contains the module package name
631 * IdentitySchemaNode which contains data about identity
633 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
634 if (identity == null) {
638 JavaTypeName name = renames.get(identity);
640 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
641 BindingMapping.getClassName(identity.getQName()));
644 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
645 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
646 if (!baseIdentities.isEmpty()) {
647 for (IdentitySchemaNode baseIdentity : baseIdentities) {
648 JavaTypeName base = renames.get(baseIdentity);
650 final QName qname = baseIdentity.getQName();
651 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
652 BindingMapping.getClassName(qname));
655 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
656 newType.addImplementsType(gto);
659 newType.addImplementsType(BASE_IDENTITY);
662 final Module module = context.module();
663 addCodegenInformation(newType, module, identity);
664 newType.setModuleName(module.getName());
665 newType.setSchemaPath(identity.getPath());
667 qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
668 identity.getQName().getLocalName());
670 context.addIdentityType(identity, newType);
673 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
674 final JavaTypeName yangModuleInfo, final String localName) {
675 return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
676 new SimpleImmutableEntry<>(yangModuleInfo, localName));
680 * Converts all <b>groupings</b> of the module to the list of
681 * <code>Type</code> objects. Firstly are groupings sorted according mutual
682 * dependencies. At least dependent (independent) groupings are in the list
683 * saved at first positions. For every grouping the record is added to map
684 * {@link ModuleContext#groupings allGroupings}
689 * collection of groupings from which types will be generated
692 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
693 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
694 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
695 // node of grouping is resolved to the method.
696 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
697 narrowImplementedInterface(genType);
698 annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
699 context.addGroupingType(grouping, genType);
700 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
701 groupingsToGenTypes(context, grouping.getGroupings());
702 processUsesAugments(grouping, context, true);
703 actionsToGenType(context, genType, grouping, null, true);
708 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
709 * <code>enumTypeDef</code> item is added to builder with its name and value.
711 * @param enumTypeDef EnumTypeDefinition contains enum data
712 * @param enumName string contains name which will be assigned to enumeration builder
713 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
714 * @param module Module in which type should be generated
715 * @return enumeration builder which contains data from <code>enumTypeDef</code>
717 private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
718 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
719 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
720 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
721 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
722 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
723 context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
730 * Generates type builder for <code>module</code>.
732 * @param module Module which is source of package name for generated type builder
733 * @param postfix string which is added to the module class name representation as suffix
734 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
735 * @throws IllegalArgumentException if <code>module</code> is null
737 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
738 final Module module = context.module();
739 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
740 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
741 JavaTypeName.create(context.modulePackageName(), moduleName));
743 moduleBuilder.setModuleName(moduleName);
744 addCodegenInformation(moduleBuilder, module);
745 return moduleBuilder;
749 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
750 * In addition there are also generated types for all containers, list and choices which are child of
751 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
753 * @param augmentPackageName string with the name of the package to which the augmentation belongs
754 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
755 * @param module current module
756 * @throws IllegalArgumentException
758 * <li>if <code>augmentPackageName</code> equals null</li>
759 * <li>if <code>augSchema</code> equals null</li>
761 * @throws IllegalStateException
762 * if augment target path is null
764 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
765 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
766 checkState(augSchema.getTargetPath() != null,
767 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
769 processUsesAugments(augSchema, context, false);
770 final SchemaPath targetPath = augSchema.getTargetPath();
771 SchemaNode targetSchemaNode = null;
773 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
774 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
775 if (targetSchemaNode instanceof DerivableSchemaNode) {
776 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
778 if (targetSchemaNode == null) {
779 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
780 + " in module " + context.module().getName());
783 if (targetSchemaNode == null) {
784 throw new IllegalArgumentException("augment target not found: " + targetPath);
787 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
788 if (targetTypeBuilder == null) {
789 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
791 if (targetTypeBuilder == null) {
792 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
795 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
796 final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
797 addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
800 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
801 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
805 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
806 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
807 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
808 checkState(augSchema.getTargetPath() != null,
809 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
811 processUsesAugments(augSchema, context, inGrouping);
812 final SchemaPath targetPath = augSchema.getTargetPath();
813 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
814 if (targetSchemaNode == null) {
815 throw new IllegalArgumentException("augment target not found: " + targetPath);
818 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
819 if (targetTypeBuilder == null) {
820 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
822 if (targetTypeBuilder == null) {
823 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
826 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
827 if (usesNodeParent instanceof SchemaNode) {
828 addRawAugmentGenTypeDefinition(context,
829 packageNameForAugmentedGeneratedType(context.modulePackageName(),
830 ((SchemaNode) usesNodeParent).getPath()),
831 targetTypeBuilder.build(), augSchema, inGrouping);
833 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
836 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
837 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
841 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
842 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
844 if (targetGrouping instanceof GroupingDefinition) {
845 return (GroupingDefinition) targetGrouping;
848 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
852 * Convenient method to find node added by uses statement.
854 * @param targetPath node path
855 * @param parentUsesNode parent of uses node
856 * @return node from its original location in grouping
858 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
859 SchemaNode result = findUsedGrouping(parentUsesNode);
860 for (final QName node : targetPath.getPathFromRoot()) {
861 if (result instanceof DataNodeContainer) {
862 final QName resultNode = node.withModule(result.getQName().getModule());
863 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
864 } else if (result instanceof ChoiceSchemaNode) {
865 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
868 if (result == null) {
872 if (result instanceof DerivableSchemaNode) {
873 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
874 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
875 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
876 result = originalNode.get();
880 if (result instanceof DataSchemaNode) {
881 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
882 if (resultDataSchemaNode.isAddedByUses()) {
883 // The original node is required, but we have only the copy of
884 // the original node.
885 // Maybe this indicates a bug in Yang parser.
886 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
889 return resultDataSchemaNode;
892 throw new IllegalStateException(
893 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
898 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
899 * of augmented node with serial number as suffix.
901 * @param context current module
902 * @param augmentPackageName string with contains the package name to which the augment belongs
903 * @param basePackageName string with the package name to which the augmented node belongs
904 * @param targetTypeRef target type
905 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
906 * @return generated type builder for augment
908 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
909 final String augmentPackageName, final Type targetTypeRef,
910 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
911 Map<String, GeneratedTypeBuilder> augmentBuilders =
912 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
913 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
916 if (augIdentifier != null) {
917 augTypeName = BindingMapping.getClassName(augIdentifier);
919 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
922 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
923 JavaTypeName.create(augmentPackageName, augTypeName));
925 augTypeBuilder.addImplementsType(DATA_OBJECT);
926 defaultImplementedInterace(augTypeBuilder);
928 augTypeBuilder.addImplementsType(augmentationTypeFor(targetTypeRef));
929 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
930 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
932 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
933 augmentBuilders.put(augTypeName, augTypeBuilder);
935 if (!augSchema.getChildNodes().isEmpty()) {
936 context.addTypeToAugmentation(augTypeBuilder, augSchema);
939 context.addAugmentType(augTypeBuilder);
940 return augTypeBuilder;
943 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
944 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
945 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
949 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
950 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
951 final QName nodeType = unknownSchemaNode.getNodeType();
952 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
953 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
954 return unknownSchemaNode.getNodeParameter();
961 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
962 * consists from name of augmented node and serial number of its augmentation.
964 * @param builders map of builders which were created in the package to which the augmentation belongs
965 * @param genTypeName string with name of augmented node
966 * @return string with unique name for augmentation builder
968 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
970 if (builders != null) {
971 while (builders.containsKey(genTypeName + index)) {
975 return genTypeName + index;
979 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
980 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
981 * already part of them).
983 * @param module current module
984 * @param parent generated type builder which represents any node. The subnodes of this node are added
985 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
987 * @param childOf parent type
988 * @param schemaNodes set of data schema nodes which are the children of the node for which
989 * <code>typeBuilder</code> was created
990 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
991 * child nodes) could be added to it.
993 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
994 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
995 if (schemaNodes != null && parent != null) {
996 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
997 for (final DataSchemaNode schemaNode : schemaNodes) {
998 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
999 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1007 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1010 * @param module current module
1011 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1012 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1013 * container, choice.
1014 * @param childOf parent type
1015 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1017 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1018 * The getter method could be added to it.
1020 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1021 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1022 final boolean inGrouping) {
1023 if (schemaNodes != null && typeBuilder != null) {
1024 final Type baseInterface = childOf(typeBuilder);
1025 for (final DataSchemaNode schemaNode : schemaNodes) {
1026 if (!schemaNode.isAugmenting()) {
1027 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1035 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1037 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1038 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1039 * @param childOf parent type
1040 * @param module current module
1042 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1043 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1044 if (node != null && typeBuilder != null) {
1045 if (node instanceof LeafSchemaNode) {
1046 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1047 } else if (node instanceof LeafListSchemaNode) {
1048 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1049 } else if (node instanceof ContainerSchemaNode) {
1050 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1051 } else if (node instanceof ListSchemaNode) {
1052 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1053 } else if (node instanceof ChoiceSchemaNode) {
1054 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1055 } else if (node instanceof AnyXmlSchemaNode) {
1056 // FIXME: MDSAL-438: also cover AnyDataSchemaNode
1057 opaqueToGeneratedType(context, typeBuilder, (AnyXmlSchemaNode) node);
1059 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1060 typeBuilder.getFullyQualifiedName());
1066 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1067 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1068 * and names of all parents node.
1070 * @param context current module
1071 * @param basePackageName string with the module package name
1072 * @param parent parent type
1073 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1075 * @throws IllegalArgumentException
1077 * <li>if <code>basePackageName</code> is null</li>
1078 * <li>if <code>choiceNode</code> is null</li>
1081 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1082 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1083 if (!choiceNode.isAddedByUses()) {
1084 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1085 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1086 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1087 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1088 annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1089 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1091 final GeneratedType choiceType = choiceTypeBuilder.build();
1092 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1094 constructGetter(parent, choiceType, choiceNode);
1098 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1099 final AnyXmlSchemaNode anyxmlNode) {
1100 if (!anyxmlNode.isAddedByUses()) {
1101 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(
1102 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyxmlNode.getPath()),
1103 BindingMapping.getClassName(anyxmlNode.getQName())), anyxmlNode);
1104 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1105 defaultImplementedInterace(anyxmlTypeBuilder);
1106 annotateDeprecatedIfNecessary(anyxmlNode.getStatus(), anyxmlTypeBuilder);
1107 context.addChildNodeType(anyxmlNode, anyxmlTypeBuilder);
1109 constructGetter(parent, anyxmlTypeBuilder.build(), anyxmlNode);
1114 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1115 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1116 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1117 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1119 * @param context current module context
1120 * @param refChoiceType type which represents superior <i>case</i>
1121 * @param choiceNode choice case node which is mapped to generated type
1122 * @throws IllegalArgumentException
1124 * <li>if <code>refChoiceType</code> equals null</li>
1125 * <li>if <code>caseNodes</code> equals null</li>
1128 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1129 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1130 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1131 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1133 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1134 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1135 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1136 caseTypeBuilder.addImplementsType(refChoiceType);
1137 defaultImplementedInterace(caseTypeBuilder);
1138 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1139 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1140 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1141 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1142 if (caseChildNodes != null) {
1143 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1145 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1146 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1148 if (parent instanceof AugmentationSchemaNode) {
1149 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1150 final SchemaPath targetPath = augSchema.getTargetPath();
1151 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1152 if (targetSchemaNode instanceof DataSchemaNode
1153 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1154 if (targetSchemaNode instanceof DerivableSchemaNode) {
1155 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1158 if (targetSchemaNode == null) {
1159 throw new IllegalStateException(
1160 "Failed to find target node from grouping for augmentation " + augSchema
1161 + " in module " + context.module().getName());
1164 parent = targetSchemaNode;
1167 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1168 Type childOfType = findChildNodeByPath(parent.getPath());
1169 if (childOfType == null) {
1170 childOfType = findGroupingByPath(parent.getPath());
1172 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1174 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1179 processUsesAugments(caseNode, context, inGrouping);
1184 * Generates list of generated types for all the cases of a choice which are added to the choice through
1187 * @param module current module
1188 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1189 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1190 * of the augmenting choice will belong to pcg2.
1191 * @param targetType Type which represents target choice
1192 * @param targetNode node which represents target choice
1193 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1195 * @throws IllegalArgumentException
1197 * <li>if <code>basePackageName</code> is null</li>
1198 * <li>if <code>targetType</code> is null</li>
1199 * <li>if <code>augmentedNodes</code> is null</li>
1202 // FIXME: nullness rules need to untangled in this method
1203 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1204 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1205 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1206 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1207 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1208 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1210 for (final DataSchemaNode caseNode : augmentedNodes) {
1211 if (caseNode != null) {
1212 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1213 caseTypeBuilder.addImplementsType(targetType);
1214 defaultImplementedInterace(caseTypeBuilder);
1216 CaseSchemaNode node = null;
1217 final String caseLocalName = caseNode.getQName().getLocalName();
1218 if (caseNode instanceof CaseSchemaNode) {
1219 node = (CaseSchemaNode) caseNode;
1220 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1221 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1222 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1223 if (dataSchemaNode instanceof ChoiceSchemaNode
1224 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1225 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1230 node = findNamedCase(targetNode, caseLocalName);
1232 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1233 if (childNodes != null) {
1234 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1237 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1238 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1243 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1244 final SchemaPath nodePath = targetNode.getPath();
1245 final SchemaPath parentSp = nodePath.getParent();
1246 if (parentSp.getParent() == null) {
1247 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1250 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1251 GeneratedTypeBuilder childOfType = null;
1252 if (parent instanceof CaseSchemaNode) {
1253 childOfType = findCaseByPath(parent.getPath());
1254 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1255 childOfType = findChildNodeByPath(parent.getPath());
1256 } else if (parent instanceof GroupingDefinition) {
1257 childOfType = findGroupingByPath(parent.getPath());
1260 if (childOfType == null) {
1261 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1267 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1268 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1269 return cases.isEmpty() ? null : cases.get(0);
1272 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1273 // New parser with encapsulated type
1274 if (leaf.getPath().equals(type.getPath())) {
1278 // Embedded type definition with new parser. Also takes care of the old parser with bits
1279 if (leaf.getPath().equals(type.getPath().getParent())) {
1286 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1287 final List<PatternConstraint> patternConstraints) {
1288 if (!patternConstraints.isEmpty()) {
1289 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1290 .append(BindingMapping.getPropertyName(leafName));
1291 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1292 typeProvider.resolveRegExpressions(patternConstraints));
1297 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1299 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1300 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1301 * @param module Module in which type was defined
1302 * @return boolean value
1304 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1306 * <li>true - in other cases</li>
1309 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1310 final ModuleContext context, final boolean inGrouping) {
1311 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1315 final Module parentModule = findParentModule(schemaContext, leaf);
1316 Type returnType = null;
1318 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1319 if (isInnerType(leaf, typeDef)) {
1320 if (typeDef instanceof EnumTypeDefinition) {
1321 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, inGrouping);
1322 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1323 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1324 typeBuilder, context);
1325 if (enumBuilder != null) {
1326 returnType = enumBuilder.toInstance(typeBuilder);
1328 typeProvider.putReferencedType(leaf.getPath(), returnType);
1329 } else if (typeDef instanceof UnionTypeDefinition) {
1330 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1331 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1332 // Store the inner type within the union so that we can find the reference for it
1333 context.addInnerTypedefType(typeDef.getPath(), returnType);
1334 } else if (typeDef instanceof BitsTypeDefinition) {
1335 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1337 if (genTOBuilder != null) {
1338 returnType = genTOBuilder.build();
1341 // It is constrained version of already declared type (inner declared type exists,
1342 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1343 // In order to get proper class we need to look up closest derived type
1344 // and apply restrictions from leaf type
1345 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1346 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1347 restrictions, inGrouping);
1348 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1351 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1352 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1353 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1356 if (returnType == null) {
1360 if (typeDef instanceof EnumTypeDefinition) {
1361 typeProvider.putReferencedType(leaf.getPath(), returnType);
1364 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1365 processContextRefExtension(leaf, getter, parentModule);
1369 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1370 // Returns DerivedType in case of new parser.
1371 final TypeDefinition<?> baseType = typeDef.getBaseType();
1372 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1375 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1376 final Module module) {
1377 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1378 final QName nodeType = node.getNodeType();
1379 if ("context-reference".equals(nodeType.getLocalName())) {
1380 final String nodeParam = node.getNodeParameter();
1381 IdentitySchemaNode identity = null;
1382 String basePackageName = null;
1383 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1384 final Iterator<String> iterator = splittedElement.iterator();
1385 final int length = Iterables.size(splittedElement);
1387 identity = findIdentityByName(module.getIdentities(), iterator.next());
1388 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1389 } else if (length == 2) {
1390 final String prefix = iterator.next();
1391 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1392 if (dependentModule == null) {
1393 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1396 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1397 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1399 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1402 if (identity == null) {
1403 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1407 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1408 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1409 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1410 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1415 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1416 for (final IdentitySchemaNode id : identities) {
1417 if (id.getQName().getLocalName().equals(name)) {
1424 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1425 for (final ModuleImport imp : imports) {
1426 if (imp.getPrefix().equals(prefix)) {
1427 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1433 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1434 final boolean isReadOnly) {
1435 if (leaf != null && toBuilder != null) {
1437 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1438 if (typeDef instanceof UnionTypeDefinition) {
1439 // GeneratedType for this type definition should have be already created
1440 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1441 returnType = mc.getTypedefs().get(typeDef.getPath());
1442 if (returnType == null) {
1443 // This may still be an inner type, try to find it
1444 returnType = mc.getInnerType(typeDef.getPath());
1446 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1447 // Annonymous enumeration (already generated, since it is inherited via uses).
1448 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1449 QName qname = originalLeaf.getQName();
1450 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1452 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1454 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1460 * Converts <code>leaf</code> schema node to property of generated TO builder.
1462 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1463 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1464 * @param returnType property type
1465 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1466 * @return boolean value
1468 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1469 * name equals null or if leaf is added by <i>uses</i>.</li>
1470 * <li>true - other cases</li>
1473 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1474 final Type returnType, final boolean isReadOnly) {
1475 if (returnType == null) {
1478 final String leafName = leaf.getQName().getLocalName();
1479 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1480 propBuilder.setReadOnly(isReadOnly);
1481 propBuilder.setReturnType(returnType);
1482 addComment(propBuilder, leaf);
1484 toBuilder.addEqualsIdentity(propBuilder);
1485 toBuilder.addHashIdentity(propBuilder);
1486 toBuilder.addToStringProperty(propBuilder);
1491 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1493 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1494 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1495 * @param module module
1496 * @return boolean value
1498 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1499 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1500 * <li>false - other cases</li>
1503 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1504 final ModuleContext context, final boolean inGrouping) {
1505 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1509 final QName nodeName = node.getQName();
1511 final TypeDefinition<?> typeDef = node.getType();
1512 final Module parentModule = findParentModule(schemaContext, node);
1514 Type returnType = null;
1515 if (typeDef.getBaseType() == null) {
1516 if (typeDef instanceof EnumTypeDefinition) {
1517 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, inGrouping);
1518 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1519 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1520 typeBuilder, context);
1521 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1522 typeProvider.putReferencedType(node.getPath(), returnType);
1523 } else if (typeDef instanceof UnionTypeDefinition) {
1524 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1525 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1526 } else if (typeDef instanceof BitsTypeDefinition) {
1527 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1528 node, parentModule);
1529 returnType = genTOBuilder.build();
1531 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1532 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1533 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1536 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1537 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1538 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1541 constructGetter(typeBuilder, listTypeFor(returnType), node);
1545 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1546 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1547 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1548 returnTypeBuilder.setIsUnion(true);
1549 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1550 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1551 returnTypeBuilder.setModuleName(parentModule.getName());
1552 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1554 genTOBuilder.setTypedef(true);
1555 genTOBuilder.setIsUnion(true);
1556 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1558 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1562 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1563 final GeneratedTransferObject returnType, final Module parentModule) {
1564 // Append enclosing path hierarchy without dots
1565 final StringBuilder sb = new StringBuilder();
1566 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1567 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1568 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1569 unionBuilder.setIsUnionBuilder(true);
1571 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1572 method.setReturnType(returnType);
1573 method.addParameter(STRING, "defaultValue");
1574 method.setAccessModifier(AccessModifier.PUBLIC);
1575 method.setStatic(true);
1577 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1578 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1581 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1582 final SchemaNode schemaNode) {
1583 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1586 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1587 final SchemaNode schemaNode, final Type baseInterface) {
1588 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1589 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1593 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1594 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1595 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1596 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1597 * If <code>schemaNode</code> is instance of
1598 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1599 * which are specified in <i>uses</i>.
1601 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1602 * @param schemaNode schema node for which is created generated type builder
1603 * @param parent parent type (can be null)
1604 * @return generated type builder <code>schemaNode</code>
1606 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1607 final Type baseInterface, final ModuleContext context) {
1608 JavaTypeName name = renames.get(schemaNode);
1610 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1613 final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1614 it.addImplementsType(baseInterface);
1615 if (!(schemaNode instanceof GroupingDefinition)) {
1616 it.addImplementsType(augmentable(it));
1618 if (schemaNode instanceof DataNodeContainer) {
1619 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1620 groupingsToGenTypes(context, containerSchema.getGroupings());
1621 addImplementedInterfaceFromUses(containerSchema, it);
1628 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1629 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1630 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1632 * @param packageName string with the package name to which returning generated type builder belongs
1633 * @param schemaNode schema node which provide data about the schema node name
1634 * @param prefix return type name prefix
1635 * @return generated type builder for <code>schemaNode</code>
1636 * @throws IllegalArgumentException
1638 * <li>if <code>schemaNode</code> is null</li>
1639 * <li>if <code>packageName</code> is null</li>
1640 * <li>if QName of schema node is null</li>
1641 * <li>if schemaNode name is null</li>
1644 private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1645 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1646 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1647 final String schemaNodeName = schemaNode.getQName().getLocalName();
1648 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1650 // FIXME: Validation of name conflict
1651 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1652 final Module module = findParentModule(schemaContext, schemaNode);
1653 qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1654 BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1656 addCodegenInformation(newType, module, schemaNode);
1657 newType.setSchemaPath(schemaNode.getPath());
1658 newType.setModuleName(module.getName());
1660 final String packageName = identifier.packageName();
1661 final String simpleName = identifier.simpleName();
1662 if (!genTypeBuilders.containsKey(packageName)) {
1663 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1664 builders.put(simpleName, newType);
1665 genTypeBuilders.put(packageName, builders);
1667 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1668 if (!builders.containsKey(simpleName)) {
1669 builders.put(simpleName, newType);
1676 * Creates the name of the getter method name from <code>localName</code>.
1678 * @param localName string with the name of the getter method
1679 * @param returnType return type
1680 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1682 public static String getterMethodName(final String localName, final Type returnType) {
1683 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1687 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1688 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1689 * and <code>returnType</code> information are added to the builder.
1691 * @param interfaceBuilder generated type builder for which the getter method should be created
1692 * @param returnType type which represents the return type of the getter method
1693 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1694 * @param comment string with comment for the getter method
1695 * @param status status from yang file, for deprecated annotation
1696 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1698 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1699 final SchemaNode node) {
1700 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1701 getterMethodName(node.getQName().getLocalName(), returnType));
1702 getMethod.setReturnType(returnType);
1704 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1705 addComment(getMethod, node);
1710 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1711 final ListSchemaNode node) {
1712 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1713 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1714 getMethod.setReturnType(returnType).setDefault(true);
1715 annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1719 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1722 * @param basePackageName string contains the module package name
1723 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1724 * or as a property to <code>genTOBuilder</code> if is part of the list key
1725 * @param typeBuilder generated type builder for the list schema node
1726 * @param genTOBuilder generated TO builder for the list keys
1727 * @param listKeys list of string which contains names of the list keys
1728 * @param module current module
1729 * @throws IllegalArgumentException
1731 * <li>if <code>schemaNode</code> equals null</li>
1732 * <li>if <code>typeBuilder</code> equals null</li>
1735 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1736 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1737 final List<String> listKeys, final boolean inGrouping) {
1738 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1739 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1741 if (schemaNode instanceof LeafSchemaNode) {
1742 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1743 final String leafName = leaf.getQName().getLocalName();
1744 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1745 if (listKeys.contains(leafName)) {
1747 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1749 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1752 } else if (!schemaNode.isAddedByUses()) {
1753 if (schemaNode instanceof LeafListSchemaNode) {
1754 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1755 } else if (schemaNode instanceof ContainerSchemaNode) {
1756 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1757 (ContainerSchemaNode) schemaNode, inGrouping);
1758 } else if (schemaNode instanceof ChoiceSchemaNode) {
1759 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1760 } else if (schemaNode instanceof ListSchemaNode) {
1761 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1766 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1767 final GeneratedTOBuilder genTOBuilder) {
1768 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1770 if (genTOBuilder != null) {
1771 final GeneratedTransferObject genTO = genTOBuilder.build();
1772 // Add Identifiable.getKey() for items
1773 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1774 .addAnnotation(OVERRIDE_ANNOTATION);
1775 context.addGeneratedTOBuilder(genTOBuilder);
1780 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1782 * @param list of string with names of the list keys
1783 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1784 * an empty list is returned.
1786 private static List<String> listKeys(final ListSchemaNode list) {
1787 final List<String> listKeys = new ArrayList<>();
1789 final List<QName> keyDefinition = list.getKeyDefinition();
1790 if (keyDefinition != null) {
1791 for (final QName keyDef : keyDefinition) {
1792 listKeys.add(keyDef.getLocalName());
1799 * Generates for the <code>list</code> which contains any list keys special generated TO builder.
1801 * @param packageName string with package name to which the list belongs
1802 * @param list list schema node which is source of data about the list name
1803 * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
1804 * null or list of key definitions is null or empty.
1806 private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1807 if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1808 return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1809 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1810 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1816 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1817 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1818 * enclosing transfer objects.
1820 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1821 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1822 * @param leaf string with name for generated TO builder
1823 * @param parentModule parent module
1824 * @return generated TO builder for <code>typeDef</code>
1826 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1827 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1828 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1829 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1832 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1833 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1834 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1835 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1836 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1838 for (GeneratedTOBuilder builder : types) {
1839 if (builder.isUnion()) {
1840 final GeneratedTransferObject type = builder.build();
1841 createUnionBuilder(builder, typeBuilder, type, parentModule);
1845 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1849 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1850 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1851 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1854 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1855 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1856 * @param leaf string with name for generated TO builder
1857 * @param parentModule parent module
1858 * @return generated TO builder for <code>typeDef</code>
1860 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1861 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1862 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1863 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1864 typeDef, parentModule.getName());
1865 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1866 return genTOBuilder;
1871 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1872 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1873 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1874 * to <code>builder</code>
1876 * @param dataNodeContainer element which contains the list of used YANG groupings
1877 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1878 * @return generated type builder with all implemented types
1880 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1881 final GeneratedTypeBuilder builder) {
1882 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1883 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1884 if (genType == null) {
1885 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1886 + builder.getName());
1889 builder.addImplementsType(genType);
1894 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1895 for (final ModuleContext ctx : genCtx.values()) {
1896 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1897 if (result != null) {
1904 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1905 for (final ModuleContext ctx : genCtx.values()) {
1906 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1907 if (result != null) {
1914 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1915 for (final ModuleContext ctx : genCtx.values()) {
1916 final GeneratedTypeBuilder result = ctx.getCase(path);
1917 if (result != null) {
1924 private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1925 if (status == Status.DEPRECATED) {
1926 builder.addAnnotation(DEPRECATED_ANNOTATION);
1930 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
1931 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
1934 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
1935 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
1939 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
1940 final Type classType) {
1941 final MethodSignatureBuilder ret = typeBuilder
1942 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
1943 .setAccessModifier(AccessModifier.PUBLIC)
1944 .setReturnType(classType(classType));
1945 ret.addAnnotation(OVERRIDE_ANNOTATION);