2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.mdsal.binding.generator.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
15 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.BASE_IDENTITY;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.QNAME;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentation;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
34 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.instanceNotification;
35 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
36 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListNotification;
37 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.opaqueObject;
38 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
39 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
40 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
41 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
42 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
43 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
44 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
45 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
46 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
47 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
48 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
50 import com.google.common.base.Splitter;
51 import com.google.common.collect.Iterables;
52 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
53 import java.util.AbstractMap.SimpleImmutableEntry;
54 import java.util.ArrayList;
55 import java.util.Collection;
56 import java.util.Collections;
57 import java.util.Comparator;
58 import java.util.HashMap;
59 import java.util.HashSet;
60 import java.util.Iterator;
61 import java.util.List;
63 import java.util.Optional;
65 import org.eclipse.jdt.annotation.Nullable;
66 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
67 import org.opendaylight.mdsal.binding.model.api.Constant;
68 import org.opendaylight.mdsal.binding.model.api.Enumeration;
69 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
70 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
71 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
72 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
73 import org.opendaylight.mdsal.binding.model.api.Restrictions;
74 import org.opendaylight.mdsal.binding.model.api.Type;
75 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
76 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
77 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
78 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
79 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
83 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
84 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
85 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
86 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
87 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
88 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
89 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
90 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
91 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
92 import org.opendaylight.yangtools.yang.common.QName;
93 import org.opendaylight.yangtools.yang.common.QNameModule;
94 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
95 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
96 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
103 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
106 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
107 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
108 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
112 import org.opendaylight.yangtools.yang.model.api.Module;
113 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
114 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
115 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
116 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
117 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
118 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
119 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
120 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
121 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
122 import org.opendaylight.yangtools.yang.model.api.UsesNode;
123 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
124 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
125 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
126 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
127 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
128 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
129 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
130 import org.slf4j.Logger;
131 import org.slf4j.LoggerFactory;
133 abstract class AbstractTypeGenerator {
134 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
135 private static final Splitter COLON_SPLITTER = Splitter.on(':');
136 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
137 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
138 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
141 * Comparator based on augment target path.
143 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
144 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
145 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
147 while (thisIt.hasNext()) {
148 if (!otherIt.hasNext()) {
152 final int comp = thisIt.next().compareTo(otherIt.next());
158 return otherIt.hasNext() ? -1 : 0;
162 * Constant with the concrete name of identifier.
164 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
167 * Constant with the concrete name of namespace.
169 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
171 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
174 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
175 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
176 * for schema node specified in key part.
178 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
181 * Provide methods for converting YANG types to JAVA types.
183 private final AbstractTypeProvider typeProvider;
186 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
188 private final SchemaContext schemaContext;
191 * Holds renamed elements.
193 private final Map<SchemaNode, JavaTypeName> renames;
195 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
196 final Map<SchemaNode, JavaTypeName> renames) {
197 this.schemaContext = requireNonNull(context);
198 this.typeProvider = requireNonNull(typeProvider);
199 this.renames = requireNonNull(renames);
201 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
202 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
203 for (final Module contextModule : contextModules) {
204 contexts.add(moduleToGenTypes(contextModule));
207 contexts.forEach(this::allAugmentsToGenTypes);
210 final Collection<ModuleContext> moduleContexts() {
211 return genCtx.values();
214 final ModuleContext moduleContext(final QNameModule module) {
215 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
218 final AbstractTypeProvider typeProvider() {
222 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
224 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
226 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
227 Set<? extends SchemaNode> nodes);
229 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
231 private ModuleContext moduleToGenTypes(final Module module) {
232 final ModuleContext context = new ModuleContext(module);
233 genCtx.put(module.getQNameModule(), context);
234 allTypeDefinitionsToGenTypes(context);
235 groupingsToGenTypes(context, module.getGroupings());
236 allIdentitiesToGenTypes(context);
238 if (!module.getChildNodes().isEmpty()) {
239 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
240 context.addModuleNode(moduleType);
241 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
244 // Resolve RPCs and notifications only after we have created instantiated tree
245 rpcMethodsToGenType(context);
246 notificationsToGenType(context);
251 * Converts all extended type definitions of module to the list of
252 * <code>Type</code> objects.
255 * module from which is obtained set of type definitions
256 * @throws IllegalArgumentException
258 * <li>if module is null</li>
259 * <li>if name of module is null</li>
261 * @throws IllegalStateException
262 * if set of type definitions from module is null
264 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
265 final Module module = context.module();
266 checkArgument(module.getName() != null, "Module name cannot be NULL.");
268 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
269 if (typedef != null) {
270 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
272 context.addTypedefType(typedef, type);
273 context.addTypeToSchema(type,typedef);
279 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
280 final DataSchemaNode node, final boolean inGrouping) {
281 if (node.isAugmenting() || node.isAddedByUses()) {
284 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
285 defaultImplementedInterace(genType);
286 annotateDeprecatedIfNecessary(node, genType);
288 final Module module = context.module();
289 genType.setModuleName(module.getName());
290 addCodegenInformation(genType, module, node);
291 genType.setSchemaPath(node.getPath());
292 if (node instanceof DataNodeContainer) {
293 context.addChildNodeType(node, genType);
294 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
295 processUsesAugments((DataNodeContainer) node, context, inGrouping);
300 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
301 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
302 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
303 if (genType != null) {
304 constructGetter(parent, genType, node);
305 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
306 actionsToGenType(context, genType, node, null, inGrouping);
307 notificationsToGenType(context, genType, node, null, inGrouping);
311 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
312 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
313 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
314 if (genType != null) {
315 final List<String> listKeys = listKeys(node);
316 final GeneratedTOBuilder keyTypeBuilder;
317 if (!listKeys.isEmpty()) {
318 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
319 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
320 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
321 .addImplementsType(identifier(genType));
322 genType.addImplementsType(identifiable(keyTypeBuilder));
324 keyTypeBuilder = null;
327 final ParameterizedType listType = listTypeFor(genType);
328 constructGetter(parent, listType, node);
329 constructNonnull(parent, listType, node);
331 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
332 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
334 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
335 if (!schemaNode.isAugmenting()) {
336 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
341 if (keyTypeBuilder != null) {
342 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
343 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
344 keyTypeBuilder.setSUID(prop);
347 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
351 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
352 final boolean inGrouping) {
353 for (final UsesNode usesNode : node.getUses()) {
354 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
355 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
356 processUsesAugments(augment, context, inGrouping);
362 * Converts all <b>augmentation</b> of the module to the list
363 * <code>Type</code> objects.
366 * module from which is obtained list of all augmentation objects
367 * to iterate over them
368 * @throws IllegalArgumentException
370 * <li>if the module is null</li>
371 * <li>if the name of module is null</li>
373 * @throws IllegalStateException
374 * if set of augmentations from module is null
376 private void allAugmentsToGenTypes(final ModuleContext context) {
377 final Module module = context.module();
378 checkArgument(module != null, "Module reference cannot be NULL.");
379 checkArgument(module.getName() != null, "Module name cannot be NULL.");
380 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
382 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
383 augmentationToGenTypes(context, augment);
388 * Returns list of <code>AugmentationSchema</code> objects. The objects are
389 * sorted according to the length of their target path from the shortest to
393 * module from which is obtained list of all augmentation objects
394 * @return list of sorted <code>AugmentationSchema</code> objects obtained
395 * from <code>module</code>
396 * @throws IllegalArgumentException
398 * @throws IllegalStateException
399 * if set of module augmentations is null
401 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
402 checkArgument(module != null, "Module reference cannot be NULL.");
403 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
405 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
406 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
407 sortedAugmentations.sort(AUGMENT_COMP);
409 return sortedAugmentations;
413 * Create GeneratedTypeBuilder object from module argument.
416 * Module object from which builder will be created
417 * @return <code>GeneratedTypeBuilder</code> which is internal
418 * representation of the module
419 * @throws IllegalArgumentException
422 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
423 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
424 final Module module = context.module();
425 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
426 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
427 // if we have more than 2 top level uses statements we need to define getImplementedInterface() on the
428 // top level DataRoot object
429 if (module.getUses().size() > 1) {
430 narrowImplementedInterface(moduleDataTypeBuilder);
433 addCodegenInformation(moduleDataTypeBuilder, module);
434 return moduleDataTypeBuilder;
437 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
438 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
439 for (final ActionDefinition action : parentSchema.getActions()) {
440 if (action.isAugmenting()) {
444 final GeneratedType input;
445 final GeneratedType output;
446 if (action.isAddedByUses()) {
447 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
448 // Original definition may live in a different module, make sure we account for that
449 final ModuleContext origContext = moduleContext(
450 orig.getPath().getPathFromRoot().iterator().next().getModule());
451 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
452 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
454 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
455 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
458 if (!(parentSchema instanceof GroupingDefinition)) {
459 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
460 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
461 // and do not capture an actual instantiation.
462 final QName qname = action.getQName();
463 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
464 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
465 BindingMapping.getClassName(qname)));
466 qnameConstant(builder, context.moduleInfoType(), qname.getLocalName());
468 annotateDeprecatedIfNecessary(action, builder);
469 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
470 : action(parent, input, output));
472 addCodegenInformation(builder, context.module(), action);
473 context.addChildNodeType(action, builder);
478 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
479 final QName qname = action.getQName();
480 for (UsesNode uses : parent.getUses()) {
481 final GroupingDefinition grp = findUsedGrouping(uses);
482 // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
484 final Optional<ActionDefinition> found = grp.findAction(qname.withModule(grp.getQName().getModule()));
485 if (found.isPresent()) {
486 final ActionDefinition result = found.get();
487 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
491 return Optional.empty();
494 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
495 final ContainerSchemaNode schema, final boolean inGrouping) {
496 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
497 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
498 return genType.build();
502 * Converts all <b>RPCs</b> input and output substatements of the module
503 * to the list of <code>Type</code> objects. In addition are to containers
504 * and lists which belong to input or output also part of returning list.
507 * module from which is obtained set of all rpc objects to
509 * @throws IllegalArgumentException
511 * <li>if the module is null</li>
512 * <li>if the name of module is null</li>
514 * @throws IllegalStateException
515 * if set of rpcs from module is null
517 private void rpcMethodsToGenType(final ModuleContext context) {
518 final Module module = context.module();
519 checkArgument(module.getName() != null, "Module name cannot be NULL.");
520 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
521 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
522 if (rpcDefinitions.isEmpty()) {
526 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
527 interfaceBuilder.addImplementsType(RPC_SERVICE);
529 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
531 for (final RpcDefinition rpc : rpcDefinitions) {
533 final String rpcName = BindingMapping.getClassName(rpc.getQName());
534 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
535 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
537 // Do not refer to annotation class, as it may not be available at runtime
538 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
539 addComment(method, rpc);
541 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
542 method.setReturnType(listenableFutureTypeFor(
543 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
547 context.addTopLevelNodeType(interfaceBuilder);
550 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
551 final ContainerSchemaNode schema, final Type type) {
552 processUsesAugments(schema, context, false);
553 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(context,
554 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
556 addImplementedInterfaceFromUses(schema, outType);
557 outType.addImplementsType(type);
558 outType.addImplementsType(augmentable(outType));
559 defaultImplementedInterace(outType);
560 annotateDeprecatedIfNecessary(rpc, outType);
561 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
562 context.addChildNodeType(schema, outType);
563 return outType.build();
567 * Converts all <b>notifications</b> of the module to the list of
568 * <code>Type</code> objects. In addition are to this list added containers
569 * and lists which are part of this notification.
572 * module from which is obtained set of all notification objects
573 * to iterate over them
574 * @throws IllegalArgumentException
576 * <li>if the module equals null</li>
577 * <li>if the name of module equals null</li>
579 * @throws IllegalStateException
580 * if set of notifications from module is null
582 private void notificationsToGenType(final ModuleContext context) {
583 final Module module = context.module();
584 checkArgument(module.getName() != null, "Module name cannot be NULL.");
585 final Set<NotificationDefinition> notifications = module.getNotifications();
586 if (notifications.isEmpty()) {
590 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
591 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
593 for (final NotificationDefinition notification : notifications) {
594 if (notification != null) {
595 processUsesAugments(notification, context, false);
597 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
598 context.modulePackageName(), notification, DATA_OBJECT, context);
599 defaultImplementedInterace(notificationInterface);
600 annotateDeprecatedIfNecessary(notification, notificationInterface);
601 notificationInterface.addImplementsType(NOTIFICATION);
602 context.addChildNodeType(notification, notificationInterface);
604 // Notification object
605 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
606 notification.getChildNodes(), false);
608 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
609 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
610 .setReturnType(primitiveVoidType()), notification);
614 addCodegenInformation(listenerInterface, module, "notifications", notifications);
615 context.addTopLevelNodeType(listenerInterface);
618 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
619 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
620 final boolean inGrouping) {
621 final Set<NotificationDefinition> notifications = parentSchema.getNotifications();
622 if (notifications.isEmpty()) {
626 for (NotificationDefinition notif : notifications) {
627 if (notif.isAugmenting()) {
630 if (parentSchema instanceof GroupingDefinition) {
631 // Notifications cannot be really established, as they lack instantiation context, which would be
632 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
636 processUsesAugments(notif, context, false);
638 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
639 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
640 defaultImplementedInterace(notifInterface);
641 annotateDeprecatedIfNecessary(notif, notifInterface);
643 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
644 : instanceNotification(notifInterface, parent));
645 context.addChildNodeType(notif, notifInterface);
647 // Notification object
648 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
653 * Converts all <b>identities</b> of the module to the list of
654 * <code>Type</code> objects.
657 * module from which is obtained set of all identity objects to
659 * @param schemaContext
660 * schema context only used as input parameter for method
661 * {@link BindingGeneratorImpl#identityToGenType}
664 private void allIdentitiesToGenTypes(final ModuleContext context) {
665 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
667 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
668 for (final IdentitySchemaNode identity : schemaIdentities) {
669 identityToGenType(context, identity);
675 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
676 * created transport object builder. If identity contains base identity then
677 * reference to base identity is added to superior identity as its extend.
678 * If identity doesn't contain base identity then only reference to abstract
679 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
680 * BaseIdentity} is added
684 * @param basePackageName
685 * string contains the module package name
687 * IdentitySchemaNode which contains data about identity
689 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
690 if (identity == null) {
694 JavaTypeName name = renames.get(identity);
696 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
697 BindingMapping.getClassName(identity.getQName()));
700 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
701 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
702 if (!baseIdentities.isEmpty()) {
703 for (IdentitySchemaNode baseIdentity : baseIdentities) {
704 JavaTypeName base = renames.get(baseIdentity);
706 final QName qname = baseIdentity.getQName();
707 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
708 BindingMapping.getClassName(qname));
711 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
712 newType.addImplementsType(gto);
715 newType.addImplementsType(BASE_IDENTITY);
718 final Module module = context.module();
719 addCodegenInformation(newType, module, identity);
720 newType.setModuleName(module.getName());
721 newType.setSchemaPath(identity.getPath());
723 qnameConstant(newType, context.moduleInfoType(), identity.getQName().getLocalName());
725 context.addIdentityType(identity, newType);
728 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
729 final JavaTypeName yangModuleInfo, final String localName) {
730 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
731 new SimpleImmutableEntry<>(yangModuleInfo, localName));
735 * Converts all <b>groupings</b> of the module to the list of
736 * <code>Type</code> objects. Firstly are groupings sorted according mutual
737 * dependencies. At least dependent (independent) groupings are in the list
738 * saved at first positions. For every grouping the record is added to map
739 * {@link ModuleContext#groupings allGroupings}
744 * collection of groupings from which types will be generated
747 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
748 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
749 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
750 // node of grouping is resolved to the method.
751 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
752 narrowImplementedInterface(genType);
753 annotateDeprecatedIfNecessary(grouping, genType);
754 context.addGroupingType(grouping, genType);
755 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
756 groupingsToGenTypes(context, grouping.getGroupings());
757 processUsesAugments(grouping, context, true);
758 actionsToGenType(context, genType, grouping, null, true);
759 notificationsToGenType(context, genType, grouping, null, true);
764 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
765 * <code>enumTypeDef</code> item is added to builder with its name and value.
767 * @param enumTypeDef EnumTypeDefinition contains enum data
768 * @param enumName string contains name which will be assigned to enumeration builder
769 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
770 * @param module Module in which type should be generated
771 * @return enumeration builder which contains data from <code>enumTypeDef</code>
773 private Enumeration resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
774 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
775 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
776 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
777 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
778 final Enumeration ret = enumBuilder.toInstance(typeBuilder);
779 context.addTypeToSchema(ret, enumTypeDef);
780 context.addInnerTypedefType(enumTypeDef.getPath(), ret);
785 * Generates type builder for <code>module</code>.
787 * @param module Module which is source of package name for generated type builder
788 * @param postfix string which is added to the module class name representation as suffix
789 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
790 * @throws IllegalArgumentException if <code>module</code> is null
792 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
793 final Module module = context.module();
794 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
795 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
796 JavaTypeName.create(context.modulePackageName(), moduleName));
798 moduleBuilder.setModuleName(moduleName);
799 addCodegenInformation(moduleBuilder, module);
800 return moduleBuilder;
804 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
805 * In addition there are also generated types for all containers, list and choices which are child of
806 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
808 * @param augmentPackageName string with the name of the package to which the augmentation belongs
809 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
810 * @param module current module
811 * @throws IllegalArgumentException
813 * <li>if <code>augmentPackageName</code> equals null</li>
814 * <li>if <code>augSchema</code> equals null</li>
816 * @throws IllegalStateException
817 * if augment target path is null
819 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
820 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
821 checkState(augSchema.getTargetPath() != null,
822 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
824 processUsesAugments(augSchema, context, false);
825 final SchemaPath targetPath = augSchema.getTargetPath();
826 SchemaNode targetSchemaNode = null;
828 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
829 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
830 if (targetSchemaNode instanceof DerivableSchemaNode) {
831 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
833 if (targetSchemaNode == null) {
834 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
835 + " in module " + context.module().getName());
838 if (targetSchemaNode == null) {
839 throw new IllegalArgumentException("augment target not found: " + targetPath);
842 if (targetSchemaNode instanceof ChoiceSchemaNode) {
843 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
844 checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
845 generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
846 augSchema.getChildNodes(), null, false);
850 final JavaTypeName targetName;
851 if (targetSchemaNode instanceof CaseSchemaNode) {
852 final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
853 checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
854 targetName = builder.getIdentifier();
856 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
857 if (builder == null) {
858 targetName = findAliasByPath(targetSchemaNode.getPath());
859 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
861 targetName = builder.getIdentifier();
865 addRawAugmentGenTypeDefinition(context, new ReferencedTypeImpl(targetName), augSchema, false);
868 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
869 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
870 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
871 checkState(augSchema.getTargetPath() != null,
872 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
874 processUsesAugments(augSchema, context, inGrouping);
875 final SchemaPath targetPath = augSchema.getTargetPath();
876 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
877 if (targetSchemaNode == null) {
878 throw new IllegalArgumentException("augment target not found: " + targetPath);
881 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
882 if (targetTypeBuilder == null) {
883 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
885 if (targetTypeBuilder == null) {
886 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
889 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
890 if (usesNodeParent instanceof SchemaNode) {
891 addRawAugmentGenTypeDefinition(context,
892 packageNameForAugmentedGeneratedType(context.modulePackageName(),
893 ((SchemaNode) usesNodeParent).getPath()),
894 targetTypeBuilder.build(), augSchema, inGrouping);
896 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
899 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
900 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
904 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
905 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
907 if (targetGrouping instanceof GroupingDefinition) {
908 return (GroupingDefinition) targetGrouping;
911 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
915 * Convenient method to find node added by uses statement.
917 * @param targetPath node path
918 * @param parentUsesNode parent of uses node
919 * @return node from its original location in grouping
921 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
922 SchemaNode result = findUsedGrouping(parentUsesNode);
923 for (final QName node : targetPath.getPathFromRoot()) {
924 // FIXME: this dispatch is rather ugly, we probably want to refactor it a bit
925 if (result instanceof DataNodeContainer) {
926 final QName resultNode = node.withModule(result.getQName().getModule());
928 SchemaNode found = ((DataNodeContainer) result).getDataChildByName(resultNode);
930 if (result instanceof ActionNodeContainer) {
931 found = ((ActionNodeContainer) result).findAction(resultNode).orElse(null);
933 if (found == null && result instanceof NotificationNodeContainer) {
934 found = ((NotificationNodeContainer) result).findNotification(resultNode).orElse(null);
938 } else if (result instanceof ChoiceSchemaNode) {
939 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
940 } else if (result instanceof ActionDefinition) {
941 final ActionDefinition action = (ActionDefinition) result;
942 final QName resultNode = node.withModule(result.getQName().getModule());
944 final ContainerSchemaNode input = action.getInput();
945 final ContainerSchemaNode output = action.getOutput();
946 if (resultNode.equals(input.getQName())) {
948 } else if (resultNode.equals(output.getQName())) {
953 } else if (result != null) {
954 throw new IllegalStateException("Cannot handle " + result);
957 if (result == null) {
961 if (result instanceof DerivableSchemaNode) {
962 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
963 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
964 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
965 result = originalNode.get();
969 if (result instanceof DataSchemaNode) {
970 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
971 if (resultDataSchemaNode.isAddedByUses()) {
972 // The original node is required, but we have only the copy of
973 // the original node.
974 // Maybe this indicates a bug in Yang parser.
975 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
978 return resultDataSchemaNode;
981 throw new IllegalStateException(
982 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
987 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
988 * of augmented node with serial number as suffix.
990 * @param context current module
991 * @param augmentPackageName string with contains the package name to which the augment belongs
992 * @param basePackageName string with the package name to which the augmented node belongs
993 * @param targetTypeRef target type
994 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
995 * @return generated type builder for augment
997 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
998 final String augmentPackageName, final Type targetTypeRef,
999 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1000 Map<String, GeneratedTypeBuilder> augmentBuilders =
1001 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
1002 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
1005 if (augIdentifier != null) {
1006 augTypeName = BindingMapping.getClassName(augIdentifier);
1008 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1011 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
1012 JavaTypeName.create(augmentPackageName, augTypeName));
1014 augTypeBuilder.addImplementsType(DATA_OBJECT);
1015 defaultImplementedInterace(augTypeBuilder);
1017 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
1018 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
1019 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1021 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
1022 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1023 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1025 augmentBuilders.put(augTypeName, augTypeBuilder);
1027 if (!augSchema.getChildNodes().isEmpty()) {
1028 context.addTypeToAugmentation(augTypeBuilder, augSchema);
1031 context.addAugmentType(augTypeBuilder);
1032 return augTypeBuilder;
1035 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1036 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1037 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1041 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1042 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1043 final QName nodeType = unknownSchemaNode.getNodeType();
1044 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1045 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1046 return unknownSchemaNode.getNodeParameter();
1053 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1054 * consists from name of augmented node and serial number of its augmentation.
1056 * @param builders map of builders which were created in the package to which the augmentation belongs
1057 * @param genTypeName string with name of augmented node
1058 * @return string with unique name for augmentation builder
1060 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1062 if (builders != null) {
1063 while (builders.containsKey(genTypeName + index)) {
1067 return genTypeName + index;
1071 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1072 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1073 * already part of them).
1075 * @param module current module
1076 * @param parent generated type builder which represents any node. The subnodes of this node are added
1077 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1078 * container, choice.
1079 * @param childOf parent type
1080 * @param schemaNodes set of data schema nodes which are the children of the node for which
1081 * <code>typeBuilder</code> was created
1082 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1083 * child nodes) could be added to it.
1085 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1086 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
1087 if (schemaNodes != null && parent != null) {
1088 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1089 for (final DataSchemaNode schemaNode : schemaNodes) {
1090 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1091 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1099 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1102 * @param module current module
1103 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1104 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1105 * container, choice.
1106 * @param childOf parent type
1107 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1109 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1110 * The getter method could be added to it.
1112 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1113 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1114 final boolean inGrouping) {
1115 if (schemaNodes != null && typeBuilder != null) {
1116 final Type baseInterface = childOf(typeBuilder);
1117 for (final DataSchemaNode schemaNode : schemaNodes) {
1118 if (!schemaNode.isAugmenting()) {
1119 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1127 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1129 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1130 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1131 * @param childOf parent type
1132 * @param module current module
1134 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1135 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1136 if (node != null && typeBuilder != null) {
1137 if (node instanceof LeafSchemaNode) {
1138 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1139 } else if (node instanceof LeafListSchemaNode) {
1140 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1141 } else if (node instanceof ContainerSchemaNode) {
1142 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1143 } else if (node instanceof ListSchemaNode) {
1144 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1145 } else if (node instanceof ChoiceSchemaNode) {
1146 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1147 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1148 opaqueToGeneratedType(context, typeBuilder, node);
1150 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1151 typeBuilder.getFullyQualifiedName());
1157 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1158 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1159 * and names of all parents node.
1161 * @param context current module
1162 * @param basePackageName string with the module package name
1163 * @param parent parent type
1164 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1166 * @throws IllegalArgumentException
1168 * <li>if <code>basePackageName</code> is null</li>
1169 * <li>if <code>choiceNode</code> is null</li>
1172 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1173 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1174 if (!choiceNode.isAddedByUses()) {
1175 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(context,
1176 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1177 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1178 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1179 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1180 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1182 final GeneratedType choiceType = choiceTypeBuilder.build();
1183 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1185 constructGetter(parent, choiceType, choiceNode);
1189 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1190 final DataSchemaNode anyNode) {
1191 if (!anyNode.isAddedByUses()) {
1192 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(context,
1193 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1194 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1195 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1196 defaultImplementedInterace(anyxmlTypeBuilder);
1197 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1198 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1200 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1205 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1206 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1207 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1208 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1210 * @param context current module context
1211 * @param refChoiceType type which represents superior <i>case</i>
1212 * @param choiceNode choice case node which is mapped to generated type
1213 * @throws IllegalArgumentException
1215 * <li>if <code>refChoiceType</code> equals null</li>
1216 * <li>if <code>caseNodes</code> equals null</li>
1219 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1220 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1221 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1222 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1224 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1225 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1226 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1227 caseTypeBuilder.addImplementsType(refChoiceType);
1228 defaultImplementedInterace(caseTypeBuilder);
1229 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1230 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1231 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1232 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1233 if (caseChildNodes != null) {
1234 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1236 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1237 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1239 if (parent instanceof AugmentationSchemaNode) {
1240 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1241 final SchemaPath targetPath = augSchema.getTargetPath();
1242 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1243 if (targetSchemaNode instanceof DataSchemaNode
1244 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1245 if (targetSchemaNode instanceof DerivableSchemaNode) {
1246 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1249 if (targetSchemaNode == null) {
1250 throw new IllegalStateException(
1251 "Failed to find target node from grouping for augmentation " + augSchema
1252 + " in module " + context.module().getName());
1255 parent = targetSchemaNode;
1258 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1259 Type childOfType = findChildNodeByPath(parent.getPath());
1260 if (childOfType == null) {
1261 childOfType = findGroupingByPath(parent.getPath());
1263 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1265 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1270 processUsesAugments(caseNode, context, inGrouping);
1275 * Generates list of generated types for all the cases of a choice which are added to the choice through
1278 * @param module current module
1279 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1280 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1281 * of the augmenting choice will belong to pcg2.
1282 * @param targetType Type which represents target choice
1283 * @param targetNode node which represents target choice
1284 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1286 * @throws IllegalArgumentException
1288 * <li>if <code>basePackageName</code> is null</li>
1289 * <li>if <code>targetType</code> is null</li>
1290 * <li>if <code>augmentedNodes</code> is null</li>
1293 // FIXME: nullness rules need to untangled in this method
1294 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1295 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1296 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1297 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1298 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1299 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1301 for (final DataSchemaNode caseNode : augmentedNodes) {
1302 if (caseNode != null) {
1303 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1304 caseTypeBuilder.addImplementsType(targetType);
1305 defaultImplementedInterace(caseTypeBuilder);
1307 CaseSchemaNode node = null;
1308 final String caseLocalName = caseNode.getQName().getLocalName();
1309 if (caseNode instanceof CaseSchemaNode) {
1310 node = (CaseSchemaNode) caseNode;
1311 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1312 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1313 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1314 if (dataSchemaNode instanceof ChoiceSchemaNode
1315 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1316 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1321 node = findNamedCase(targetNode, caseLocalName);
1323 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1324 if (childNodes != null) {
1325 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1328 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1329 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1334 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1335 final SchemaPath nodePath = targetNode.getPath();
1336 final SchemaPath parentSp = nodePath.getParent();
1337 if (parentSp.getParent() == null) {
1338 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1341 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1342 GeneratedTypeBuilder childOfType = null;
1343 if (parent instanceof CaseSchemaNode) {
1344 childOfType = findCaseByPath(parent.getPath());
1345 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1346 childOfType = findChildNodeByPath(parent.getPath());
1347 } else if (parent instanceof GroupingDefinition) {
1348 childOfType = findGroupingByPath(parent.getPath());
1351 if (childOfType == null) {
1352 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1358 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1359 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1360 return cases.isEmpty() ? null : cases.get(0);
1363 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1364 // New parser with encapsulated type
1365 if (leaf.getPath().equals(type.getPath())) {
1369 // Embedded type definition with new parser. Also takes care of the old parser with bits
1370 if (leaf.getPath().equals(type.getPath().getParent())) {
1377 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1378 final List<PatternConstraint> patternConstraints) {
1379 if (!patternConstraints.isEmpty()) {
1380 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1381 .append(BindingMapping.getPropertyName(leafName));
1382 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1383 typeProvider.resolveRegExpressions(patternConstraints));
1388 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1390 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1391 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1392 * @param module Module in which type was defined
1393 * @return boolean value
1395 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1397 * <li>true - in other cases</li>
1400 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1401 final ModuleContext context, final boolean inGrouping) {
1402 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1406 final Module parentModule = findParentModule(schemaContext, leaf);
1407 Type returnType = null;
1409 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1410 if (isInnerType(leaf, typeDef)) {
1411 if (typeDef instanceof EnumTypeDefinition) {
1412 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1413 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(), typeBuilder, context);
1414 typeProvider.putReferencedType(leaf.getPath(), returnType);
1415 } else if (typeDef instanceof UnionTypeDefinition) {
1416 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1417 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1418 // Store the inner type within the union so that we can find the reference for it
1419 context.addInnerTypedefType(typeDef.getPath(), returnType);
1420 } else if (typeDef instanceof BitsTypeDefinition) {
1421 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1423 if (genTOBuilder != null) {
1424 returnType = genTOBuilder.build();
1427 // It is constrained version of already declared type (inner declared type exists,
1428 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1429 // In order to get proper class we need to look up closest derived type
1430 // and apply restrictions from leaf type
1431 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1432 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1433 restrictions, inGrouping);
1434 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1437 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1438 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1439 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1442 if (returnType == null) {
1446 if (typeDef instanceof EnumTypeDefinition) {
1447 typeProvider.putReferencedType(leaf.getPath(), returnType);
1450 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1451 processContextRefExtension(leaf, getter, parentModule);
1455 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1456 // Returns DerivedType in case of new parser.
1457 final TypeDefinition<?> baseType = typeDef.getBaseType();
1458 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1461 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1462 final Module module) {
1463 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1464 final QName nodeType = node.getNodeType();
1465 if ("context-reference".equals(nodeType.getLocalName())) {
1466 final String nodeParam = node.getNodeParameter();
1467 IdentitySchemaNode identity = null;
1468 String basePackageName = null;
1469 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1470 final Iterator<String> iterator = splittedElement.iterator();
1471 final int length = Iterables.size(splittedElement);
1473 identity = findIdentityByName(module.getIdentities(), iterator.next());
1474 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1475 } else if (length == 2) {
1476 final String prefix = iterator.next();
1477 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1478 if (dependentModule == null) {
1479 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1482 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1483 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1485 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1488 if (identity == null) {
1489 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1493 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1494 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1495 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1496 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1501 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1502 for (final IdentitySchemaNode id : identities) {
1503 if (id.getQName().getLocalName().equals(name)) {
1510 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1511 for (final ModuleImport imp : imports) {
1512 if (imp.getPrefix().equals(prefix)) {
1513 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1519 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1520 final boolean isReadOnly) {
1521 if (leaf != null && toBuilder != null) {
1523 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1524 if (typeDef instanceof UnionTypeDefinition) {
1525 // GeneratedType for this type definition should have be already created
1526 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1527 returnType = mc.getTypedefs().get(typeDef.getPath());
1528 if (returnType == null) {
1529 // This may still be an inner type, try to find it
1530 returnType = mc.getInnerType(typeDef.getPath());
1532 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1533 // Annonymous enumeration (already generated, since it is inherited via uses).
1534 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1535 QName qname = originalLeaf.getQName();
1536 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1538 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1540 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1546 * Converts <code>leaf</code> schema node to property of generated TO builder.
1548 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1549 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1550 * @param returnType property type
1551 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1552 * @return boolean value
1554 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1555 * name equals null or if leaf is added by <i>uses</i>.</li>
1556 * <li>true - other cases</li>
1559 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1560 final Type returnType, final boolean isReadOnly) {
1561 if (returnType == null) {
1564 final String leafName = leaf.getQName().getLocalName();
1565 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1566 propBuilder.setReadOnly(isReadOnly);
1567 propBuilder.setReturnType(returnType);
1568 addComment(propBuilder, leaf);
1570 toBuilder.addEqualsIdentity(propBuilder);
1571 toBuilder.addHashIdentity(propBuilder);
1572 toBuilder.addToStringProperty(propBuilder);
1577 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1579 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1580 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1581 * @param module module
1582 * @return boolean value
1584 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1585 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1586 * <li>false - other cases</li>
1589 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1590 final ModuleContext context, final boolean inGrouping) {
1591 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1595 final QName nodeName = node.getQName();
1597 final TypeDefinition<?> typeDef = node.getType();
1598 final Module parentModule = findParentModule(schemaContext, node);
1600 Type returnType = null;
1601 if (typeDef.getBaseType() == null) {
1602 if (typeDef instanceof EnumTypeDefinition) {
1603 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1604 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName, typeBuilder, context);
1605 typeProvider.putReferencedType(node.getPath(), returnType);
1606 } else if (typeDef instanceof UnionTypeDefinition) {
1607 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1608 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1609 } else if (typeDef instanceof BitsTypeDefinition) {
1610 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1611 node, parentModule);
1612 returnType = genTOBuilder.build();
1614 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1615 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1616 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1619 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1620 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1621 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1624 constructGetter(typeBuilder, listTypeFor(returnType), node);
1628 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1629 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1630 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1631 returnTypeBuilder.setIsUnion(true);
1632 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1633 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1634 returnTypeBuilder.setModuleName(parentModule.getName());
1635 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1637 genTOBuilder.setTypedef(true);
1638 genTOBuilder.setIsUnion(true);
1639 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1641 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1645 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1646 final GeneratedTransferObject returnType, final Module parentModule) {
1647 // Append enclosing path hierarchy without dots
1648 final StringBuilder sb = new StringBuilder();
1649 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1650 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1651 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1652 unionBuilder.setIsUnionBuilder(true);
1654 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1655 method.setReturnType(returnType);
1656 method.addParameter(STRING, "defaultValue");
1657 method.setAccessModifier(AccessModifier.PUBLIC);
1658 method.setStatic(true);
1660 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1661 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1664 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1665 final SchemaNode schemaNode) {
1666 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1669 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1670 final SchemaNode schemaNode, final Type baseInterface) {
1671 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1672 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1676 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1677 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1678 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1679 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1680 * If <code>schemaNode</code> is instance of
1681 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1682 * which are specified in <i>uses</i>.
1684 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1685 * @param schemaNode schema node for which is created generated type builder
1686 * @param parent parent type (can be null)
1687 * @return generated type builder <code>schemaNode</code>
1689 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1690 final Type baseInterface, final ModuleContext context) {
1691 JavaTypeName name = renames.get(schemaNode);
1693 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1696 final GeneratedTypeBuilder it = addRawInterfaceDefinition(context, name, schemaNode);
1697 it.addImplementsType(baseInterface);
1698 if (!(schemaNode instanceof GroupingDefinition)) {
1699 it.addImplementsType(augmentable(it));
1701 if (schemaNode instanceof DataNodeContainer) {
1702 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1703 groupingsToGenTypes(context, containerSchema.getGroupings());
1704 addImplementedInterfaceFromUses(containerSchema, it);
1711 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1712 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1713 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1715 * @param packageName string with the package name to which returning generated type builder belongs
1716 * @param schemaNode schema node which provide data about the schema node name
1717 * @param prefix return type name prefix
1718 * @return generated type builder for <code>schemaNode</code>
1719 * @throws IllegalArgumentException
1721 * <li>if <code>schemaNode</code> is null</li>
1722 * <li>if <code>packageName</code> is null</li>
1723 * <li>if QName of schema node is null</li>
1724 * <li>if schemaNode name is null</li>
1727 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final JavaTypeName identifier,
1728 final SchemaNode schemaNode) {
1729 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1730 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1731 final String schemaNodeName = schemaNode.getQName().getLocalName();
1732 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1734 // FIXME: Validation of name conflict
1735 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1736 qnameConstant(newType, context.moduleInfoType(), schemaNode.getQName().getLocalName());
1738 final Module module = context.module();
1739 addCodegenInformation(newType, module, schemaNode);
1740 newType.setSchemaPath(schemaNode.getPath());
1741 newType.setModuleName(module.getName());
1743 final String packageName = identifier.packageName();
1744 final String simpleName = identifier.simpleName();
1745 if (!genTypeBuilders.containsKey(packageName)) {
1746 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1747 builders.put(simpleName, newType);
1748 genTypeBuilders.put(packageName, builders);
1750 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1751 if (!builders.containsKey(simpleName)) {
1752 builders.put(simpleName, newType);
1759 * Creates the name of the getter method name from <code>localName</code>.
1761 * @param localName string with the name of the getter method
1762 * @param returnType return type
1763 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1765 public static String getterMethodName(final String localName, final Type returnType) {
1766 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1770 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1771 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1772 * and <code>returnType</code> information are added to the builder.
1774 * @param interfaceBuilder generated type builder for which the getter method should be created
1775 * @param returnType type which represents the return type of the getter method
1776 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1777 * @param comment string with comment for the getter method
1778 * @param status status from yang file, for deprecated annotation
1779 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1781 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1782 final SchemaNode node) {
1783 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1784 getterMethodName(node.getQName().getLocalName(), returnType));
1785 getMethod.setReturnType(returnType);
1787 annotateDeprecatedIfNecessary(node, getMethod);
1788 addComment(getMethod, node);
1793 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1794 final ListSchemaNode node) {
1795 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1796 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1797 getMethod.setReturnType(returnType).setDefault(true);
1798 annotateDeprecatedIfNecessary(node, getMethod);
1802 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1805 * @param basePackageName string contains the module package name
1806 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1807 * or as a property to <code>genTOBuilder</code> if is part of the list key
1808 * @param typeBuilder generated type builder for the list schema node
1809 * @param genTOBuilder generated TO builder for the list keys
1810 * @param listKeys list of string which contains names of the list keys
1811 * @param module current module
1812 * @throws IllegalArgumentException
1814 * <li>if <code>schemaNode</code> equals null</li>
1815 * <li>if <code>typeBuilder</code> equals null</li>
1818 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1819 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1820 final List<String> listKeys, final boolean inGrouping) {
1821 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1822 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1824 if (schemaNode instanceof LeafSchemaNode) {
1825 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1826 final String leafName = leaf.getQName().getLocalName();
1827 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1828 if (listKeys.contains(leafName)) {
1830 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1832 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1835 } else if (!schemaNode.isAddedByUses()) {
1836 if (schemaNode instanceof LeafListSchemaNode) {
1837 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1838 } else if (schemaNode instanceof ContainerSchemaNode) {
1839 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1840 (ContainerSchemaNode) schemaNode, inGrouping);
1841 } else if (schemaNode instanceof ChoiceSchemaNode) {
1842 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1843 } else if (schemaNode instanceof ListSchemaNode) {
1844 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1845 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1846 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1851 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1852 final GeneratedTOBuilder genTOBuilder) {
1853 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1855 if (genTOBuilder != null) {
1856 final GeneratedTransferObject genTO = genTOBuilder.build();
1857 // Add Identifiable.getKey() for items
1858 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1859 .addAnnotation(OVERRIDE_ANNOTATION);
1860 context.addGeneratedTOBuilder(genTOBuilder);
1865 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1867 * @param list of string with names of the list keys
1868 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1869 * an empty list is returned.
1871 private static List<String> listKeys(final ListSchemaNode list) {
1872 final List<QName> keyDefinition = list.getKeyDefinition();
1873 switch (keyDefinition.size()) {
1875 return Collections.emptyList();
1877 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1879 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1880 for (final QName keyDef : keyDefinition) {
1881 listKeys.add(keyDef.getLocalName());
1888 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1889 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1890 * enclosing transfer objects.
1892 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1893 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1894 * @param leaf string with name for generated TO builder
1895 * @param parentModule parent module
1896 * @return generated TO builder for <code>typeDef</code>
1898 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1899 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1900 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1901 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1903 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1904 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1905 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1906 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1907 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1909 for (GeneratedTOBuilder builder : types) {
1910 if (builder.isUnion()) {
1911 final GeneratedTransferObject type = builder.build();
1912 createUnionBuilder(builder, typeBuilder, type, parentModule);
1916 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1920 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1921 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1922 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1925 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1926 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1927 * @param leaf string with name for generated TO builder
1928 * @param parentModule parent module
1929 * @return generated TO builder for <code>typeDef</code>
1931 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1932 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1933 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1934 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1935 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1936 return genTOBuilder;
1940 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1941 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1942 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1943 * to <code>builder</code>
1945 * @param dataNodeContainer element which contains the list of used YANG groupings
1946 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1947 * @return generated type builder with all implemented types
1949 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1950 final GeneratedTypeBuilder builder) {
1951 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1952 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1953 if (genType == null) {
1954 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + " is not resolved for "
1955 + builder.getFullyQualifiedName());
1958 builder.addImplementsType(genType.build());
1963 private JavaTypeName findAliasByPath(final SchemaPath path) {
1964 for (final ModuleContext ctx : genCtx.values()) {
1965 final JavaTypeName result = ctx.getAlias(path);
1966 if (result != null) {
1973 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1974 for (final ModuleContext ctx : genCtx.values()) {
1975 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1976 if (result != null) {
1983 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1984 for (final ModuleContext ctx : genCtx.values()) {
1985 final GeneratedTypeBuilder result = ctx.getGrouping(path);
1986 if (result != null) {
1993 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1994 for (final ModuleContext ctx : genCtx.values()) {
1995 final GeneratedTypeBuilder result = ctx.getCase(path);
1996 if (result != null) {
2003 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
2004 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
2005 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
2008 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
2009 switch (node.getStatus()) {
2011 // FIXME: we really want to use a pre-made annotation
2012 builder.addAnnotation(DEPRECATED_ANNOTATION);
2015 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
2021 throw new IllegalStateException("Unhandled status in " + node);
2025 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2026 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2029 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2030 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
2034 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2035 final Type classType) {
2036 final MethodSignatureBuilder ret = typeBuilder
2037 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2038 .setAccessModifier(AccessModifier.PUBLIC)
2039 .setReturnType(classType(classType));
2040 ret.addAnnotation(OVERRIDE_ANNOTATION);