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.TypedDataSchemaNode;
122 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
123 import org.opendaylight.yangtools.yang.model.api.UsesNode;
124 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
125 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
126 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
127 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
128 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
129 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
130 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
131 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
132 import org.slf4j.Logger;
133 import org.slf4j.LoggerFactory;
135 abstract class AbstractTypeGenerator {
136 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
137 private static final Splitter COLON_SPLITTER = Splitter.on(':');
138 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
139 private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
140 private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
143 * Comparator based on augment target path.
145 private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
146 final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
147 final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
149 while (thisIt.hasNext()) {
150 if (!otherIt.hasNext()) {
154 final int comp = thisIt.next().compareTo(otherIt.next());
160 return otherIt.hasNext() ? -1 : 0;
164 * Constant with the concrete name of identifier.
166 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
169 * Constant with the concrete name of namespace.
171 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
173 private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
176 * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
177 * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
178 * for schema node specified in key part.
180 private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
183 * Provide methods for converting YANG types to JAVA types.
185 private final AbstractTypeProvider typeProvider;
188 * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
190 private final SchemaContext schemaContext;
193 * Holds renamed elements.
195 private final Map<SchemaNode, JavaTypeName> renames;
197 AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider,
198 final Map<SchemaNode, JavaTypeName> renames) {
199 this.schemaContext = requireNonNull(context);
200 this.typeProvider = requireNonNull(typeProvider);
201 this.renames = requireNonNull(renames);
203 final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
204 final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
205 for (final Module contextModule : contextModules) {
206 contexts.add(moduleToGenTypes(contextModule));
209 contexts.forEach(this::allAugmentsToGenTypes);
212 final Collection<ModuleContext> moduleContexts() {
213 return genCtx.values();
216 final ModuleContext moduleContext(final QNameModule module) {
217 return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
220 final AbstractTypeProvider typeProvider() {
224 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
226 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
228 abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
229 Set<? extends SchemaNode> nodes);
231 abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
233 private ModuleContext moduleToGenTypes(final Module module) {
234 final ModuleContext context = new ModuleContext(module);
235 genCtx.put(module.getQNameModule(), context);
236 allTypeDefinitionsToGenTypes(context);
237 groupingsToGenTypes(context, module.getGroupings());
238 allIdentitiesToGenTypes(context);
240 if (!module.getChildNodes().isEmpty()) {
241 final GeneratedTypeBuilder moduleType = moduleToDataType(context);
242 context.addModuleNode(moduleType);
243 resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
246 // Resolve RPCs and notifications only after we have created instantiated tree
247 rpcMethodsToGenType(context);
248 notificationsToGenType(context);
253 * Converts all extended type definitions of module to the list of
254 * <code>Type</code> objects.
257 * module from which is obtained set of type definitions
258 * @throws IllegalArgumentException
260 * <li>if module is null</li>
261 * <li>if name of module is null</li>
263 * @throws IllegalStateException
264 * if set of type definitions from module is null
266 private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
267 final Module module = context.module();
268 checkArgument(module.getName() != null, "Module name cannot be NULL.");
270 for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
271 if (typedef != null) {
272 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef, typedef);
274 context.addTypedefType(typedef, type);
275 context.addTypeToSchema(type,typedef);
281 private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
282 final DataSchemaNode node, final boolean inGrouping) {
283 if (node.isAugmenting() || node.isAddedByUses()) {
286 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
287 defaultImplementedInterace(genType);
288 annotateDeprecatedIfNecessary(node, genType);
290 final Module module = context.module();
291 genType.setModuleName(module.getName());
292 addCodegenInformation(genType, module, node);
293 genType.setSchemaPath(node.getPath());
294 if (node instanceof DataNodeContainer) {
295 context.addChildNodeType(node, genType);
296 groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
297 processUsesAugments((DataNodeContainer) node, context, inGrouping);
302 private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
303 final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
304 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
305 if (genType != null) {
306 constructGetter(parent, genType, node);
307 resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
308 actionsToGenType(context, genType, node, null, inGrouping);
309 notificationsToGenType(context, genType, node, null, inGrouping);
313 private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
314 final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
315 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
316 if (genType != null) {
317 final List<String> listKeys = listKeys(node);
318 final GeneratedTOBuilder keyTypeBuilder;
319 if (!listKeys.isEmpty()) {
320 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
321 packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
322 BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
323 .addImplementsType(identifier(genType));
324 genType.addImplementsType(identifiable(keyTypeBuilder));
326 keyTypeBuilder = null;
329 final ParameterizedType listType = listTypeFor(genType);
330 constructGetter(parent, listType, node);
331 constructNonnull(parent, listType, node);
333 actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
334 notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
336 for (final DataSchemaNode schemaNode : node.getChildNodes()) {
337 if (!schemaNode.isAugmenting()) {
338 addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
343 if (keyTypeBuilder != null) {
344 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
345 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
346 keyTypeBuilder.setSUID(prop);
349 typeBuildersToGenTypes(context, genType, keyTypeBuilder);
353 private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
354 final boolean inGrouping) {
355 for (final UsesNode usesNode : node.getUses()) {
356 for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
357 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
358 processUsesAugments(augment, context, inGrouping);
364 * Converts all <b>augmentation</b> of the module to the list
365 * <code>Type</code> objects.
368 * module from which is obtained list of all augmentation objects
369 * to iterate over them
370 * @throws IllegalArgumentException
372 * <li>if the module is null</li>
373 * <li>if the name of module is null</li>
375 * @throws IllegalStateException
376 * if set of augmentations from module is null
378 private void allAugmentsToGenTypes(final ModuleContext context) {
379 final Module module = context.module();
380 checkArgument(module != null, "Module reference cannot be NULL.");
381 checkArgument(module.getName() != null, "Module name cannot be NULL.");
382 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
384 for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
385 augmentationToGenTypes(context, augment);
390 * Returns list of <code>AugmentationSchema</code> objects. The objects are
391 * sorted according to the length of their target path from the shortest to
395 * module from which is obtained list of all augmentation objects
396 * @return list of sorted <code>AugmentationSchema</code> objects obtained
397 * from <code>module</code>
398 * @throws IllegalArgumentException
400 * @throws IllegalStateException
401 * if set of module augmentations is null
403 private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
404 checkArgument(module != null, "Module reference cannot be NULL.");
405 checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
407 final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
408 final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
409 sortedAugmentations.sort(AUGMENT_COMP);
411 return sortedAugmentations;
415 * Create GeneratedTypeBuilder object from module argument.
418 * Module object from which builder will be created
419 * @return <code>GeneratedTypeBuilder</code> which is internal
420 * representation of the module
421 * @throws IllegalArgumentException
424 private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
425 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
426 final Module module = context.module();
427 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
428 moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
429 // if we have more than 2 top level uses statements we need to define getImplementedInterface() on the
430 // top level DataRoot object
431 if (module.getUses().size() > 1) {
432 narrowImplementedInterface(moduleDataTypeBuilder);
435 addCodegenInformation(moduleDataTypeBuilder, module);
436 return moduleDataTypeBuilder;
439 private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
440 final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
441 for (final ActionDefinition action : parentSchema.getActions()) {
442 if (action.isAugmenting()) {
446 final GeneratedType input;
447 final GeneratedType output;
448 if (action.isAddedByUses()) {
449 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
450 // Original definition may live in a different module, make sure we account for that
451 final ModuleContext origContext = moduleContext(
452 orig.getPath().getPathFromRoot().iterator().next().getModule());
453 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
454 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
456 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
457 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
460 if (!(parentSchema instanceof GroupingDefinition)) {
461 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
462 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
463 // and do not capture an actual instantiation.
464 final QName qname = action.getQName();
465 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
466 packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
467 BindingMapping.getClassName(qname)));
468 qnameConstant(builder, context.moduleInfoType(), qname.getLocalName());
470 annotateDeprecatedIfNecessary(action, builder);
471 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
472 : action(parent, input, output));
474 addCodegenInformation(builder, context.module(), action);
475 context.addChildNodeType(action, builder);
480 private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
481 final QName qname = action.getQName();
482 for (UsesNode uses : parent.getUses()) {
483 final GroupingDefinition grp = findUsedGrouping(uses);
484 // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
486 final Optional<ActionDefinition> found = grp.findAction(qname.withModule(grp.getQName().getModule()));
487 if (found.isPresent()) {
488 final ActionDefinition result = found.get();
489 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
493 return Optional.empty();
496 private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
497 final ContainerSchemaNode schema, final boolean inGrouping) {
498 final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
499 resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
500 return genType.build();
504 * Converts all <b>RPCs</b> input and output substatements of the module
505 * to the list of <code>Type</code> objects. In addition are to containers
506 * and lists which belong to input or output also part of returning list.
509 * module from which is obtained set of all rpc objects to
511 * @throws IllegalArgumentException
513 * <li>if the module is null</li>
514 * <li>if the name of module is null</li>
516 * @throws IllegalStateException
517 * if set of rpcs from module is null
519 private void rpcMethodsToGenType(final ModuleContext context) {
520 final Module module = context.module();
521 checkArgument(module.getName() != null, "Module name cannot be NULL.");
522 final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
523 checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
524 if (rpcDefinitions.isEmpty()) {
528 final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
529 interfaceBuilder.addImplementsType(RPC_SERVICE);
531 addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
533 for (final RpcDefinition rpc : rpcDefinitions) {
535 final String rpcName = BindingMapping.getClassName(rpc.getQName());
536 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
537 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
539 // Do not refer to annotation class, as it may not be available at runtime
540 method.addAnnotation("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
541 addComment(method, rpc);
543 createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
544 method.setReturnType(listenableFutureTypeFor(
545 rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
549 context.addTopLevelNodeType(interfaceBuilder);
552 private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
553 final ContainerSchemaNode schema, final Type type) {
554 processUsesAugments(schema, context, false);
555 final GeneratedTypeBuilder outType = addRawInterfaceDefinition(context,
556 JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
558 addImplementedInterfaceFromUses(schema, outType);
559 outType.addImplementsType(type);
560 outType.addImplementsType(augmentable(outType));
561 defaultImplementedInterace(outType);
562 annotateDeprecatedIfNecessary(rpc, outType);
563 resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
564 context.addChildNodeType(schema, outType);
565 return outType.build();
569 * Converts all <b>notifications</b> of the module to the list of
570 * <code>Type</code> objects. In addition are to this list added containers
571 * and lists which are part of this notification.
574 * module from which is obtained set of all notification objects
575 * to iterate over them
576 * @throws IllegalArgumentException
578 * <li>if the module equals null</li>
579 * <li>if the name of module equals null</li>
581 * @throws IllegalStateException
582 * if set of notifications from module is null
584 private void notificationsToGenType(final ModuleContext context) {
585 final Module module = context.module();
586 checkArgument(module.getName() != null, "Module name cannot be NULL.");
587 final Set<NotificationDefinition> notifications = module.getNotifications();
588 if (notifications.isEmpty()) {
592 final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
593 listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
595 for (final NotificationDefinition notification : notifications) {
596 if (notification != null) {
597 processUsesAugments(notification, context, false);
599 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
600 context.modulePackageName(), notification, DATA_OBJECT, context);
601 defaultImplementedInterace(notificationInterface);
602 annotateDeprecatedIfNecessary(notification, notificationInterface);
603 notificationInterface.addImplementsType(NOTIFICATION);
604 context.addChildNodeType(notification, notificationInterface);
606 // Notification object
607 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
608 notification.getChildNodes(), false);
610 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
611 .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
612 .setReturnType(primitiveVoidType()), notification);
616 addCodegenInformation(listenerInterface, module, "notifications", notifications);
617 context.addTopLevelNodeType(listenerInterface);
620 private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
621 final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
622 final boolean inGrouping) {
623 final Set<NotificationDefinition> notifications = parentSchema.getNotifications();
624 if (notifications.isEmpty()) {
628 for (NotificationDefinition notif : notifications) {
629 if (notif.isAugmenting()) {
632 if (parentSchema instanceof GroupingDefinition) {
633 // Notifications cannot be really established, as they lack instantiation context, which would be
634 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
638 processUsesAugments(notif, context, false);
640 final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
641 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
642 defaultImplementedInterace(notifInterface);
643 annotateDeprecatedIfNecessary(notif, notifInterface);
645 notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
646 : instanceNotification(notifInterface, parent));
647 context.addChildNodeType(notif, notifInterface);
649 // Notification object
650 resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
655 * Converts all <b>identities</b> of the module to the list of
656 * <code>Type</code> objects.
659 * module from which is obtained set of all identity objects to
661 * @param schemaContext
662 * schema context only used as input parameter for method
663 * {@link BindingGeneratorImpl#identityToGenType}
666 private void allIdentitiesToGenTypes(final ModuleContext context) {
667 final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
669 if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
670 for (final IdentitySchemaNode identity : schemaIdentities) {
671 identityToGenType(context, identity);
677 * Converts the <b>identity</b> object to GeneratedType. Firstly it is
678 * created transport object builder. If identity contains base identity then
679 * reference to base identity is added to superior identity as its extend.
680 * If identity doesn't contain base identity then only reference to abstract
681 * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
682 * BaseIdentity} is added
686 * @param basePackageName
687 * string contains the module package name
689 * IdentitySchemaNode which contains data about identity
691 private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
692 if (identity == null) {
696 JavaTypeName name = renames.get(identity);
698 name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
699 BindingMapping.getClassName(identity.getQName()));
702 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
703 final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
704 if (!baseIdentities.isEmpty()) {
705 for (IdentitySchemaNode baseIdentity : baseIdentities) {
706 JavaTypeName base = renames.get(baseIdentity);
708 final QName qname = baseIdentity.getQName();
709 base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
710 BindingMapping.getClassName(qname));
713 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
714 newType.addImplementsType(gto);
717 newType.addImplementsType(BASE_IDENTITY);
720 final Module module = context.module();
721 addCodegenInformation(newType, module, identity);
722 newType.setModuleName(module.getName());
723 newType.setSchemaPath(identity.getPath());
725 qnameConstant(newType, context.moduleInfoType(), identity.getQName().getLocalName());
727 context.addIdentityType(identity, newType);
730 private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
731 final JavaTypeName yangModuleInfo, final String localName) {
732 return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
733 new SimpleImmutableEntry<>(yangModuleInfo, localName));
737 * Converts all <b>groupings</b> of the module to the list of
738 * <code>Type</code> objects. Firstly are groupings sorted according mutual
739 * dependencies. At least dependent (independent) groupings are in the list
740 * saved at first positions. For every grouping the record is added to map
741 * {@link ModuleContext#groupings allGroupings}
746 * collection of groupings from which types will be generated
749 private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
750 for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
751 // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
752 // node of grouping is resolved to the method.
753 final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
754 narrowImplementedInterface(genType);
755 annotateDeprecatedIfNecessary(grouping, genType);
756 context.addGroupingType(grouping, genType);
757 resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
758 groupingsToGenTypes(context, grouping.getGroupings());
759 processUsesAugments(grouping, context, true);
760 actionsToGenType(context, genType, grouping, null, true);
761 notificationsToGenType(context, genType, grouping, null, true);
766 * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
767 * <code>enumTypeDef</code> item is added to builder with its name and value.
769 * @param enumTypeDef EnumTypeDefinition contains enum data
770 * @param enumName string contains name which will be assigned to enumeration builder
771 * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
772 * @param module Module in which type should be generated
773 * @return enumeration builder which contains data from <code>enumTypeDef</code>
775 private Enumeration resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
776 final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
777 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
778 typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
779 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
780 final Enumeration ret = enumBuilder.toInstance(typeBuilder);
781 context.addTypeToSchema(ret, enumTypeDef);
782 context.addInnerTypedefType(enumTypeDef.getPath(), ret);
787 * Generates type builder for <code>module</code>.
789 * @param module Module which is source of package name for generated type builder
790 * @param postfix string which is added to the module class name representation as suffix
791 * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
792 * @throws IllegalArgumentException if <code>module</code> is null
794 private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
795 final Module module = context.module();
796 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
797 final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
798 JavaTypeName.create(context.modulePackageName(), moduleName));
800 moduleBuilder.setModuleName(moduleName);
801 addCodegenInformation(moduleBuilder, module);
802 return moduleBuilder;
806 * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
807 * In addition there are also generated types for all containers, list and choices which are child of
808 * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
810 * @param augmentPackageName string with the name of the package to which the augmentation belongs
811 * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
812 * @param module current module
813 * @throws IllegalArgumentException
815 * <li>if <code>augmentPackageName</code> equals null</li>
816 * <li>if <code>augSchema</code> equals null</li>
818 * @throws IllegalStateException
819 * if augment target path is null
821 private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
822 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
823 checkState(augSchema.getTargetPath() != null,
824 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
826 processUsesAugments(augSchema, context, false);
827 final SchemaPath targetPath = augSchema.getTargetPath();
828 SchemaNode targetSchemaNode = null;
830 targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
831 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
832 if (targetSchemaNode instanceof DerivableSchemaNode) {
833 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
835 if (targetSchemaNode == null) {
836 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
837 + " in module " + context.module().getName());
840 if (targetSchemaNode == null) {
841 throw new IllegalArgumentException("augment target not found: " + targetPath);
844 if (targetSchemaNode instanceof ChoiceSchemaNode) {
845 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
846 checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
847 generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
848 augSchema.getChildNodes(), null, false);
852 final JavaTypeName targetName;
853 if (targetSchemaNode instanceof CaseSchemaNode) {
854 final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
855 checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
856 targetName = builder.getIdentifier();
858 final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
859 if (builder == null) {
860 targetName = findAliasByPath(targetSchemaNode.getPath());
861 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
863 targetName = builder.getIdentifier();
867 addRawAugmentGenTypeDefinition(context, new ReferencedTypeImpl(targetName), augSchema, false);
870 private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
871 final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
872 checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
873 checkState(augSchema.getTargetPath() != null,
874 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
876 processUsesAugments(augSchema, context, inGrouping);
877 final SchemaPath targetPath = augSchema.getTargetPath();
878 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
879 if (targetSchemaNode == null) {
880 throw new IllegalArgumentException("augment target not found: " + targetPath);
883 GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
884 if (targetTypeBuilder == null) {
885 targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
887 if (targetTypeBuilder == null) {
888 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
891 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
892 if (usesNodeParent instanceof SchemaNode) {
893 addRawAugmentGenTypeDefinition(context,
894 packageNameForAugmentedGeneratedType(context.modulePackageName(),
895 ((SchemaNode) usesNodeParent).getPath()),
896 targetTypeBuilder.build(), augSchema, inGrouping);
898 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
901 generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
902 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
906 private GroupingDefinition findUsedGrouping(final UsesNode uses) {
907 final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, uses.getGroupingPath()
909 if (targetGrouping instanceof GroupingDefinition) {
910 return (GroupingDefinition) targetGrouping;
913 throw new IllegalArgumentException("Failed to resolve used grouping for " + uses);
917 * Convenient method to find node added by uses statement.
919 * @param targetPath node path
920 * @param parentUsesNode parent of uses node
921 * @return node from its original location in grouping
923 private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
924 SchemaNode result = findUsedGrouping(parentUsesNode);
925 for (final QName node : targetPath.getPathFromRoot()) {
926 // FIXME: this dispatch is rather ugly, we probably want to refactor it a bit
927 if (result instanceof DataNodeContainer) {
928 final QName resultNode = node.withModule(result.getQName().getModule());
930 SchemaNode found = ((DataNodeContainer) result).getDataChildByName(resultNode);
932 if (result instanceof ActionNodeContainer) {
933 found = ((ActionNodeContainer) result).findAction(resultNode).orElse(null);
935 if (found == null && result instanceof NotificationNodeContainer) {
936 found = ((NotificationNodeContainer) result).findNotification(resultNode).orElse(null);
940 } else if (result instanceof ChoiceSchemaNode) {
941 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
942 } else if (result instanceof ActionDefinition) {
943 final ActionDefinition action = (ActionDefinition) result;
944 final QName resultNode = node.withModule(result.getQName().getModule());
946 final ContainerSchemaNode input = action.getInput();
947 final ContainerSchemaNode output = action.getOutput();
948 if (resultNode.equals(input.getQName())) {
950 } else if (resultNode.equals(output.getQName())) {
955 } else if (result != null) {
956 throw new IllegalStateException("Cannot handle " + result);
959 if (result == null) {
963 if (result instanceof DerivableSchemaNode) {
964 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
965 Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
966 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
967 result = originalNode.get();
971 if (result instanceof DataSchemaNode) {
972 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
973 if (resultDataSchemaNode.isAddedByUses()) {
974 // The original node is required, but we have only the copy of
975 // the original node.
976 // Maybe this indicates a bug in Yang parser.
977 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
980 return resultDataSchemaNode;
983 throw new IllegalStateException(
984 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
989 * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
990 * of augmented node with serial number as suffix.
992 * @param context current module
993 * @param augmentPackageName string with contains the package name to which the augment belongs
994 * @param basePackageName string with the package name to which the augmented node belongs
995 * @param targetTypeRef target type
996 * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
997 * @return generated type builder for augment
999 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
1000 final String augmentPackageName, final Type targetTypeRef,
1001 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1002 Map<String, GeneratedTypeBuilder> augmentBuilders =
1003 genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
1004 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
1007 if (augIdentifier != null) {
1008 augTypeName = BindingMapping.getClassName(augIdentifier);
1010 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1013 final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
1014 JavaTypeName.create(augmentPackageName, augTypeName));
1016 augTypeBuilder.addImplementsType(DATA_OBJECT);
1017 defaultImplementedInterace(augTypeBuilder);
1019 augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
1020 annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
1021 addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1023 augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
1024 actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1025 notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1027 augmentBuilders.put(augTypeName, augTypeBuilder);
1029 if (!augSchema.getChildNodes().isEmpty()) {
1030 context.addTypeToAugmentation(augTypeBuilder, augSchema);
1033 context.addAugmentType(augTypeBuilder);
1034 return augTypeBuilder;
1037 private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1038 final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1039 return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1043 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1044 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1045 final QName nodeType = unknownSchemaNode.getNodeType();
1046 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1047 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1048 return unknownSchemaNode.getNodeParameter();
1055 * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1056 * consists from name of augmented node and serial number of its augmentation.
1058 * @param builders map of builders which were created in the package to which the augmentation belongs
1059 * @param genTypeName string with name of augmented node
1060 * @return string with unique name for augmentation builder
1062 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1064 if (builders != null) {
1065 while (builders.containsKey(genTypeName + index)) {
1069 return genTypeName + index;
1073 * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1074 * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1075 * already part of them).
1077 * @param module current module
1078 * @param parent generated type builder which represents any node. The subnodes of this node are added
1079 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1080 * container, choice.
1081 * @param childOf parent type
1082 * @param schemaNodes set of data schema nodes which are the children of the node for which
1083 * <code>typeBuilder</code> was created
1084 * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1085 * child nodes) could be added to it.
1087 private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1088 final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes, final boolean inGrouping) {
1089 if (schemaNodes != null && parent != null) {
1090 final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1091 for (final DataSchemaNode schemaNode : schemaNodes) {
1092 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1093 addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1101 * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1104 * @param module current module
1105 * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1106 * to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1107 * container, choice.
1108 * @param childOf parent type
1109 * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1111 * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1112 * The getter method could be added to it.
1114 private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1115 final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes,
1116 final boolean inGrouping) {
1117 if (schemaNodes != null && typeBuilder != null) {
1118 final Type baseInterface = childOf(typeBuilder);
1119 for (final DataSchemaNode schemaNode : schemaNodes) {
1120 if (!schemaNode.isAugmenting()) {
1121 addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1129 * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1131 * @param node data schema node which is added to <code>typeBuilder</code> as a method
1132 * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1133 * @param childOf parent type
1134 * @param module current module
1136 private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1137 final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1138 if (node != null && typeBuilder != null) {
1139 if (node instanceof LeafSchemaNode) {
1140 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1141 } else if (node instanceof LeafListSchemaNode) {
1142 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1143 } else if (node instanceof ContainerSchemaNode) {
1144 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1145 } else if (node instanceof ListSchemaNode) {
1146 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1147 } else if (node instanceof ChoiceSchemaNode) {
1148 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1149 } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1150 opaqueToGeneratedType(context, typeBuilder, node);
1152 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1153 typeBuilder.getFullyQualifiedName());
1159 * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1160 * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1161 * and names of all parents node.
1163 * @param context current module
1164 * @param basePackageName string with the module package name
1165 * @param parent parent type
1166 * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1168 * @throws IllegalArgumentException
1170 * <li>if <code>basePackageName</code> is null</li>
1171 * <li>if <code>choiceNode</code> is null</li>
1174 private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1175 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1176 if (!choiceNode.isAddedByUses()) {
1177 final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(context,
1178 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1179 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1180 choiceTypeBuilder.addImplementsType(choiceIn(parent));
1181 annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1182 context.addChildNodeType(choiceNode, choiceTypeBuilder);
1184 final GeneratedType choiceType = choiceTypeBuilder.build();
1185 generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1187 constructGetter(parent, choiceType, choiceNode);
1191 private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1192 final DataSchemaNode anyNode) {
1193 if (!anyNode.isAddedByUses()) {
1194 final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(context,
1195 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1196 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1197 anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1198 defaultImplementedInterace(anyxmlTypeBuilder);
1199 annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1200 context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1202 constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1207 * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1208 * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1209 * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1210 * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1212 * @param context current module context
1213 * @param refChoiceType type which represents superior <i>case</i>
1214 * @param choiceNode choice case node which is mapped to generated type
1215 * @throws IllegalArgumentException
1217 * <li>if <code>refChoiceType</code> equals null</li>
1218 * <li>if <code>caseNodes</code> equals null</li>
1221 private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1222 final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1223 checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1224 checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1226 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1227 if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1228 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1229 caseTypeBuilder.addImplementsType(refChoiceType);
1230 defaultImplementedInterace(caseTypeBuilder);
1231 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1232 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1233 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1234 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1235 if (caseChildNodes != null) {
1236 final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1238 if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1239 SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1241 if (parent instanceof AugmentationSchemaNode) {
1242 final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1243 final SchemaPath targetPath = augSchema.getTargetPath();
1244 SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1245 if (targetSchemaNode instanceof DataSchemaNode
1246 && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1247 if (targetSchemaNode instanceof DerivableSchemaNode) {
1248 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1251 if (targetSchemaNode == null) {
1252 throw new IllegalStateException(
1253 "Failed to find target node from grouping for augmentation " + augSchema
1254 + " in module " + context.module().getName());
1257 parent = targetSchemaNode;
1260 checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1261 Type childOfType = findChildNodeByPath(parent.getPath());
1262 if (childOfType == null) {
1263 childOfType = findGroupingByPath(parent.getPath());
1265 resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1267 resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1272 processUsesAugments(caseNode, context, inGrouping);
1277 * Generates list of generated types for all the cases of a choice which are added to the choice through
1280 * @param module current module
1281 * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1282 * from an other package (pcg1) than an augmenting choice (pcg2) then case's
1283 * of the augmenting choice will belong to pcg2.
1284 * @param targetType Type which represents target choice
1285 * @param targetNode node which represents target choice
1286 * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1288 * @throws IllegalArgumentException
1290 * <li>if <code>basePackageName</code> is null</li>
1291 * <li>if <code>targetType</code> is null</li>
1292 * <li>if <code>augmentedNodes</code> is null</li>
1295 // FIXME: nullness rules need to untangled in this method
1296 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1297 private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1298 final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1299 final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1300 checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1301 checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1303 for (final DataSchemaNode caseNode : augmentedNodes) {
1304 if (caseNode != null) {
1305 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1306 caseTypeBuilder.addImplementsType(targetType);
1307 defaultImplementedInterace(caseTypeBuilder);
1309 CaseSchemaNode node = null;
1310 final String caseLocalName = caseNode.getQName().getLocalName();
1311 if (caseNode instanceof CaseSchemaNode) {
1312 node = (CaseSchemaNode) caseNode;
1313 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1314 final String targetNodeLocalName = targetNode.getQName().getLocalName();
1315 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1316 if (dataSchemaNode instanceof ChoiceSchemaNode
1317 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1318 node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1323 node = findNamedCase(targetNode, caseLocalName);
1325 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1326 if (childNodes != null) {
1327 resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1330 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1331 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1336 private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1337 final SchemaPath nodePath = targetNode.getPath();
1338 final SchemaPath parentSp = nodePath.getParent();
1339 if (parentSp.getParent() == null) {
1340 return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1343 final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1344 GeneratedTypeBuilder childOfType = null;
1345 if (parent instanceof CaseSchemaNode) {
1346 childOfType = findCaseByPath(parent.getPath());
1347 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1348 childOfType = findChildNodeByPath(parent.getPath());
1349 } else if (parent instanceof GroupingDefinition) {
1350 childOfType = findGroupingByPath(parent.getPath());
1353 if (childOfType == null) {
1354 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1360 private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1361 final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1362 return cases.isEmpty() ? null : cases.get(0);
1365 private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1366 // New parser with encapsulated type
1367 if (leaf.getPath().equals(type.getPath())) {
1371 // Embedded type definition with new parser. Also takes care of the old parser with bits
1372 if (leaf.getPath().equals(type.getPath().getParent())) {
1379 private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1380 final List<PatternConstraint> patternConstraints) {
1381 if (!patternConstraints.isEmpty()) {
1382 final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1383 .append(BindingMapping.getPropertyName(leafName));
1384 typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1385 typeProvider.resolveRegExpressions(patternConstraints));
1390 * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1392 * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1393 * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1394 * @param module Module in which type was defined
1395 * @return boolean value
1397 * <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1399 * <li>true - in other cases</li>
1402 private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1403 final ModuleContext context, final boolean inGrouping) {
1404 if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1408 final Module parentModule = findParentModule(schemaContext, leaf);
1409 Type returnType = null;
1411 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1412 if (isInnerType(leaf, typeDef)) {
1413 if (typeDef instanceof EnumTypeDefinition) {
1414 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1415 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(), typeBuilder, context);
1416 typeProvider.putReferencedType(leaf.getPath(), returnType);
1417 } else if (typeDef instanceof UnionTypeDefinition) {
1418 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1419 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1420 // Store the inner type within the union so that we can find the reference for it
1421 context.addInnerTypedefType(typeDef.getPath(), returnType);
1422 } else if (typeDef instanceof BitsTypeDefinition) {
1423 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1425 if (genTOBuilder != null) {
1426 returnType = genTOBuilder.build();
1429 // It is constrained version of already declared type (inner declared type exists, only for special
1430 // cases (Enum, Union, Bits), which were already checked.
1431 // In order to get proper class we need to look up closest derived type and apply restrictions from leaf
1433 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1434 final TypeDefinition<?> baseOrDeclaredType = getBaseOrDeclaredType(typeDef);
1435 // we need to try to lookup an already generated type in case the leafref is targetting a generated type
1436 if (baseOrDeclaredType instanceof LeafrefTypeDefinition) {
1437 final SchemaNode leafrefTarget =
1438 typeProvider.getTargetForLeafref((LeafrefTypeDefinition) baseOrDeclaredType, leaf);
1439 if (leafrefTarget instanceof TypedDataSchemaNode) {
1440 returnType = context.getInnerType(((TypedDataSchemaNode) leafrefTarget).getType().getPath());
1443 if (returnType == null) {
1444 returnType = typeProvider.javaTypeForSchemaDefinitionType(baseOrDeclaredType, leaf,
1445 restrictions, inGrouping);
1448 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1451 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1452 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1453 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1456 if (returnType == null) {
1460 if (typeDef instanceof EnumTypeDefinition) {
1461 typeProvider.putReferencedType(leaf.getPath(), returnType);
1464 final MethodSignatureBuilder getter = constructGetter(typeBuilder, returnType, leaf);
1465 processContextRefExtension(leaf, getter, parentModule);
1469 private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1470 // Returns DerivedType in case of new parser.
1471 final TypeDefinition<?> baseType = typeDef.getBaseType();
1472 return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1475 private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1476 final Module module) {
1477 for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1478 final QName nodeType = node.getNodeType();
1479 if ("context-reference".equals(nodeType.getLocalName())) {
1480 final String nodeParam = node.getNodeParameter();
1481 IdentitySchemaNode identity = null;
1482 String basePackageName = null;
1483 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1484 final Iterator<String> iterator = splittedElement.iterator();
1485 final int length = Iterables.size(splittedElement);
1487 identity = findIdentityByName(module.getIdentities(), iterator.next());
1488 basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1489 } else if (length == 2) {
1490 final String prefix = iterator.next();
1491 final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1492 if (dependentModule == null) {
1493 throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1496 identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1497 basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1499 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1502 if (identity == null) {
1503 throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1507 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1508 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1509 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1510 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1515 private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1516 for (final IdentitySchemaNode id : identities) {
1517 if (id.getQName().getLocalName().equals(name)) {
1524 private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1525 for (final ModuleImport imp : imports) {
1526 if (imp.getPrefix().equals(prefix)) {
1527 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1533 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1534 final boolean isReadOnly) {
1535 if (leaf != null && toBuilder != null) {
1537 final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1538 if (typeDef instanceof UnionTypeDefinition) {
1539 // GeneratedType for this type definition should have be already created
1540 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1541 returnType = mc.getTypedefs().get(typeDef.getPath());
1542 if (returnType == null) {
1543 // This may still be an inner type, try to find it
1544 returnType = mc.getInnerType(typeDef.getPath());
1546 } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1547 // Annonymous enumeration (already generated, since it is inherited via uses).
1548 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1549 QName qname = originalLeaf.getQName();
1550 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1552 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1554 return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1560 * Converts <code>leaf</code> schema node to property of generated TO builder.
1562 * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1563 * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1564 * @param returnType property type
1565 * @param isReadOnly boolean value which says if leaf property is|isn't read only
1566 * @return boolean value
1568 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1569 * name equals null or if leaf is added by <i>uses</i>.</li>
1570 * <li>true - other cases</li>
1573 private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1574 final Type returnType, final boolean isReadOnly) {
1575 if (returnType == null) {
1578 final String leafName = leaf.getQName().getLocalName();
1579 final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1580 propBuilder.setReadOnly(isReadOnly);
1581 propBuilder.setReturnType(returnType);
1582 addComment(propBuilder, leaf);
1584 toBuilder.addEqualsIdentity(propBuilder);
1585 toBuilder.addHashIdentity(propBuilder);
1586 toBuilder.addToStringProperty(propBuilder);
1591 * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1593 * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1594 * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1595 * @param module module
1596 * @return boolean value
1598 * <li>true - if <code>node</code>, <code>typeBuilder</code>,
1599 * nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1600 * <li>false - other cases</li>
1603 private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1604 final ModuleContext context, final boolean inGrouping) {
1605 if (node == null || typeBuilder == null || node.isAddedByUses()) {
1609 final QName nodeName = node.getQName();
1611 final TypeDefinition<?> typeDef = node.getType();
1612 final Module parentModule = findParentModule(schemaContext, node);
1614 Type returnType = null;
1615 if (typeDef.getBaseType() == null) {
1616 if (typeDef instanceof EnumTypeDefinition) {
1617 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1618 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName, typeBuilder, context);
1619 typeProvider.putReferencedType(node.getPath(), returnType);
1620 } else if (typeDef instanceof UnionTypeDefinition) {
1621 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1622 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1623 } else if (typeDef instanceof BitsTypeDefinition) {
1624 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1625 node, parentModule);
1626 returnType = genTOBuilder.build();
1628 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1629 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1630 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1633 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1634 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1635 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1638 constructGetter(typeBuilder, listTypeFor(returnType), node);
1642 private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1643 final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1644 final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1645 returnTypeBuilder.setIsUnion(true);
1646 addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1647 returnTypeBuilder.setSchemaPath(typeDef.getPath());
1648 returnTypeBuilder.setModuleName(parentModule.getName());
1649 final GeneratedTransferObject returnType = returnTypeBuilder.build();
1651 genTOBuilder.setTypedef(true);
1652 genTOBuilder.setIsUnion(true);
1653 AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1655 createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1659 private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1660 final GeneratedTransferObject returnType, final Module parentModule) {
1661 // Append enclosing path hierarchy without dots
1662 final StringBuilder sb = new StringBuilder();
1663 genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1664 final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1665 JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1666 unionBuilder.setIsUnionBuilder(true);
1668 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1669 method.setReturnType(returnType);
1670 method.addParameter(STRING, "defaultValue");
1671 method.setAccessModifier(AccessModifier.PUBLIC);
1672 method.setStatic(true);
1674 final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1675 typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1678 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1679 final SchemaNode schemaNode) {
1680 return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1683 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1684 final SchemaNode schemaNode, final Type baseInterface) {
1685 final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1686 return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1690 * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1691 * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1692 * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1693 * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1694 * If <code>schemaNode</code> is instance of
1695 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1696 * which are specified in <i>uses</i>.
1698 * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1699 * @param schemaNode schema node for which is created generated type builder
1700 * @param parent parent type (can be null)
1701 * @return generated type builder <code>schemaNode</code>
1703 private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1704 final Type baseInterface, final ModuleContext context) {
1705 JavaTypeName name = renames.get(schemaNode);
1707 name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1710 final GeneratedTypeBuilder it = addRawInterfaceDefinition(context, name, schemaNode);
1711 it.addImplementsType(baseInterface);
1712 if (!(schemaNode instanceof GroupingDefinition)) {
1713 it.addImplementsType(augmentable(it));
1715 if (schemaNode instanceof DataNodeContainer) {
1716 final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1717 groupingsToGenTypes(context, containerSchema.getGroupings());
1718 addImplementedInterfaceFromUses(containerSchema, it);
1725 * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1726 * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1727 * If it is not found it is created and added to <code>genTypeBuilders</code>.
1729 * @param packageName string with the package name to which returning generated type builder belongs
1730 * @param schemaNode schema node which provide data about the schema node name
1731 * @param prefix return type name prefix
1732 * @return generated type builder for <code>schemaNode</code>
1733 * @throws IllegalArgumentException
1735 * <li>if <code>schemaNode</code> is null</li>
1736 * <li>if <code>packageName</code> is null</li>
1737 * <li>if QName of schema node is null</li>
1738 * <li>if schemaNode name is null</li>
1741 private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final JavaTypeName identifier,
1742 final SchemaNode schemaNode) {
1743 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1744 checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1745 final String schemaNodeName = schemaNode.getQName().getLocalName();
1746 checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1748 // FIXME: Validation of name conflict
1749 final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1750 qnameConstant(newType, context.moduleInfoType(), schemaNode.getQName().getLocalName());
1752 final Module module = context.module();
1753 addCodegenInformation(newType, module, schemaNode);
1754 newType.setSchemaPath(schemaNode.getPath());
1755 newType.setModuleName(module.getName());
1757 final String packageName = identifier.packageName();
1758 final String simpleName = identifier.simpleName();
1759 if (!genTypeBuilders.containsKey(packageName)) {
1760 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1761 builders.put(simpleName, newType);
1762 genTypeBuilders.put(packageName, builders);
1764 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1765 if (!builders.containsKey(simpleName)) {
1766 builders.put(simpleName, newType);
1773 * Creates the name of the getter method name from <code>localName</code>.
1775 * @param localName string with the name of the getter method
1776 * @param returnType return type
1777 * @return string with the name of the getter method for <code>methodName</code> in JAVA method format
1779 public static String getterMethodName(final String localName, final Type returnType) {
1780 return BindingMapping.getGetterMethodName(localName, BOOLEAN.equals(returnType));
1784 * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1785 * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1786 * and <code>returnType</code> information are added to the builder.
1788 * @param interfaceBuilder generated type builder for which the getter method should be created
1789 * @param returnType type which represents the return type of the getter method
1790 * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1791 * @param comment string with comment for the getter method
1792 * @param status status from yang file, for deprecated annotation
1793 * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1795 private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1796 final SchemaNode node) {
1797 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1798 getterMethodName(node.getQName().getLocalName(), returnType));
1799 getMethod.setReturnType(returnType);
1801 annotateDeprecatedIfNecessary(node, getMethod);
1802 addComment(getMethod, node);
1807 private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1808 final ListSchemaNode node) {
1809 final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1810 BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1811 getMethod.setReturnType(returnType).setDefault(true);
1812 annotateDeprecatedIfNecessary(node, getMethod);
1816 * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1819 * @param basePackageName string contains the module package name
1820 * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1821 * or as a property to <code>genTOBuilder</code> if is part of the list key
1822 * @param typeBuilder generated type builder for the list schema node
1823 * @param genTOBuilder generated TO builder for the list keys
1824 * @param listKeys list of string which contains names of the list keys
1825 * @param module current module
1826 * @throws IllegalArgumentException
1828 * <li>if <code>schemaNode</code> equals null</li>
1829 * <li>if <code>typeBuilder</code> equals null</li>
1832 private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1833 final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1834 final List<String> listKeys, final boolean inGrouping) {
1835 checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1836 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1838 if (schemaNode instanceof LeafSchemaNode) {
1839 final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1840 final String leafName = leaf.getQName().getLocalName();
1841 Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1842 if (listKeys.contains(leafName)) {
1844 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1846 resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1849 } else if (!schemaNode.isAddedByUses()) {
1850 if (schemaNode instanceof LeafListSchemaNode) {
1851 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1852 } else if (schemaNode instanceof ContainerSchemaNode) {
1853 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1854 (ContainerSchemaNode) schemaNode, inGrouping);
1855 } else if (schemaNode instanceof ChoiceSchemaNode) {
1856 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1857 } else if (schemaNode instanceof ListSchemaNode) {
1858 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1859 } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1860 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1865 private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1866 final GeneratedTOBuilder genTOBuilder) {
1867 checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1869 if (genTOBuilder != null) {
1870 final GeneratedTransferObject genTO = genTOBuilder.build();
1871 // Add Identifiable.getKey() for items
1872 typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1873 .addAnnotation(OVERRIDE_ANNOTATION);
1874 context.addGeneratedTOBuilder(genTOBuilder);
1879 * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1881 * @param list of string with names of the list keys
1882 * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1883 * an empty list is returned.
1885 private static List<String> listKeys(final ListSchemaNode list) {
1886 final List<QName> keyDefinition = list.getKeyDefinition();
1887 switch (keyDefinition.size()) {
1889 return Collections.emptyList();
1891 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1893 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1894 for (final QName keyDef : keyDefinition) {
1895 listKeys.add(keyDef.getLocalName());
1902 * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1903 * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1904 * enclosing transfer objects.
1906 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1907 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1908 * @param leaf string with name for generated TO builder
1909 * @param parentModule parent module
1910 * @return generated TO builder for <code>typeDef</code>
1912 private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1913 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1914 final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1915 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1917 checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1918 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1919 final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1920 types.forEach(resultTOBuilder::addEnclosingTransferObject);
1921 genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1923 for (GeneratedTOBuilder builder : types) {
1924 if (builder.isUnion()) {
1925 final GeneratedTransferObject type = builder.build();
1926 createUnionBuilder(builder, typeBuilder, type, parentModule);
1930 return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1934 * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1935 * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1936 * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1939 * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1940 * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1941 * @param leaf string with name for generated TO builder
1942 * @param parentModule parent module
1943 * @return generated TO builder for <code>typeDef</code>
1945 private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1946 final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1947 final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1948 allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1949 typeBuilder.addEnclosingTransferObject(genTOBuilder);
1950 return genTOBuilder;
1954 * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1955 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1956 * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1957 * to <code>builder</code>
1959 * @param dataNodeContainer element which contains the list of used YANG groupings
1960 * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1961 * @return generated type builder with all implemented types
1963 private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1964 final GeneratedTypeBuilder builder) {
1965 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1966 final GeneratedTypeBuilder genType = findGroupingByPath(usesNode.getGroupingPath());
1967 if (genType == null) {
1968 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + " is not resolved for "
1969 + builder.getFullyQualifiedName());
1972 builder.addImplementsType(genType.build());
1977 private JavaTypeName findAliasByPath(final SchemaPath path) {
1978 for (final ModuleContext ctx : genCtx.values()) {
1979 final JavaTypeName result = ctx.getAlias(path);
1980 if (result != null) {
1987 private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1988 for (final ModuleContext ctx : genCtx.values()) {
1989 final GeneratedTypeBuilder result = ctx.getChildNode(path);
1990 if (result != null) {
1997 private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1998 for (final ModuleContext ctx : genCtx.values()) {
1999 final GeneratedTypeBuilder result = ctx.getGrouping(path);
2000 if (result != null) {
2007 private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2008 for (final ModuleContext ctx : genCtx.values()) {
2009 final GeneratedTypeBuilder result = ctx.getCase(path);
2010 if (result != null) {
2017 private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
2018 // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
2019 return parent.createEnclosed(BindingMapping.getClassName(child), "$");
2022 private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
2023 switch (node.getStatus()) {
2025 // FIXME: we really want to use a pre-made annotation
2026 builder.addAnnotation(DEPRECATED_ANNOTATION);
2029 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
2035 throw new IllegalStateException("Unhandled status in " + node);
2039 private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2040 defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2043 private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2044 defineImplementedInterfaceMethod(typeBuilder, new ReferencedTypeImpl(typeBuilder.getIdentifier()))
2048 private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2049 final Type classType) {
2050 final MethodSignatureBuilder ret = typeBuilder
2051 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2052 .setAccessModifier(AccessModifier.PUBLIC)
2053 .setReturnType(classType(classType));
2054 ret.addAnnotation(OVERRIDE_ANNOTATION);